Path: blob/master/stream/ipro-adam-app/python/pymain.py
644 views
# import threading;12# debug3import traceback45# import numpy as np;6# import cv2;7import libAdamApiPython89# if print() output is delay, enalbe the following lines.10# sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', buffering=1)11# sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', buffering=1)121314def debugDbg(str):15# libAdamApiPython.adam_debug_print(libAdamApiPython.ADAM_LV_DBG, "[DBG] {}".format(str))16print(f"[DBG] {str}")171819def debugErr(str):20# libAdamApiPython.adam_debug_print(libAdamApiPython.ADAM_LV_ERR, "[ERR] {}".format(str))21print(f"[ERR] {str}")222324loop = None25license_key = memoryview(b"")26token = memoryview(b"")27stream_log_level = 028enum_values = ["10", "20", "30", "40", "50"]293031# Store pref names as constants32LICENSE_KEY_PREF = "LICENSE_KEY"33TOKEN_PREF = "TOKEN"34LOGGING_PREF = "LOGGING"353637def stopCB():38global loop39print("Stop callback")40loop.exit()414243ADAM_HTTP_REQ_TYPE_GET = 044ADAM_HTTP_REQ_TYPE_POST = 1454647def create_respone_header(body, status=200):48content_length = len(body)49assert len(str(status)) == 3, "status code must be 3 digits"50header = f"HTTP/1.1 {status} OK\r\nContent-Type: text/html\r\nContent-Length: {content_length}\r\n"5152return header535455def write_env_file(token, license_key, log_level):56debugDbg("Writing stream credentials to /ai_data/env-file.ini")5758env_vars = {59"TOKEN": token,60"LICENSE_KEY": license_key,61"LOGGING": enum_values[log_level],62}6364# Write or overwrite environment variables to ini file65env_file_path = "/ai_data/env-file.ini"66with open(env_file_path, "w") as env_file:67env_file.write("[DEFAULT]\n")68for key, value in env_vars.items():69env_file.write(f"{key}={value}\n")707172def httpCB(reqType, reqData):73global license_key74global token75global stream_log_level7677print("HTTP callback: type=%d" % reqType)78debugDbg("HTTP callback: reqType=%d" % reqType)7980# body = b'body'81# header = "header"82# return (header, body)8384# Html key words to be replaced85template_literals = [86"@pInstallID",87"@LICENSE_KEY_PREF",88"@TOKEN_PREF",89"@LOGGING_PREF_10",90"@LOGGING_PREF_20",91"@LOGGING_PREF_30",92"@LOGGING_PREF_40",93"@LOGGING_PREF_50",94]9596try:97# get data directory98appPath = libAdamApiPython.adam_get_app_data_dir_path()99with open(f"{appPath}/index.html") as fp:100htmlData = fp.read()101102print("reqType:%d" % reqType)103debugDbg("call httpCB: reqType=%d" % reqType)104if reqType == ADAM_HTTP_REQ_TYPE_GET:105debugDbg("Show html")106# load AppPref107loadPref()108elif reqType == ADAM_HTTP_REQ_TYPE_POST:109debugDbg("Edit html")110# set AppPref111setPref(reqData.decode("utf-8"))112else:113debugErr("call httpCB: reqType=%d" % reqType)114115# set AppPref parameter116context = []117# Get App Install ID118install_id = "%08X" % libAdamApiPython.InstallId119context.append(install_id)120context.append(license_key.tobytes().decode("utf-8"))121context.append(token.tobytes().decode("utf-8"))122context.extend(get_stream_log_level_context(stream_log_level))123124debugDbg(f"Context: {context}")125126# replace parameters in html127cnt = 0128for keywd in template_literals:129htmlData = htmlData.replace(keywd, context[cnt])130cnt += 1131header = create_respone_header(htmlData)132133except Exception as e:134debugErr(f"httpCB Exception: {e}")135htmlData = f"Server Error: {traceback.format_exc()}"136header = create_respone_header(htmlData, 500)137138body = bytes(htmlData, "utf-8")139return header, body140141142def get_stream_log_level_context(stream_log_level: int) -> list:143"""144Generate selected attribute for stream log level options.145"""146selected = 'selected="selected"'147unselected = ""148149context = []150151for i, _value in enumerate(enum_values):152if stream_log_level == i:153context.append(selected)154else:155context.append(unselected)156157return context158159160def appPrefCB(prefTuple):161global license_key162global token163global stream_log_level164165libAdamApiPython.adam_lock_appPref()166167if prefTuple == LICENSE_KEY_PREF:168license_key = memoryview(169libAdamApiPython.adam_get_appPref(LICENSE_KEY_PREF).encode()170)171elif prefTuple == TOKEN_PREF:172token = memoryview(libAdamApiPython.adam_get_appPref(TOKEN_PREF).encode())173174elif prefTuple == LOGGING_PREF:175stream_log_level = libAdamApiPython.adam_get_appPref(LOGGING_PREF)176else:177print("Undefined AppPrefName: %s" % prefTuple)178179libAdamApiPython.adam_unlock_appPref()180181182def loadPref():183global license_key184global token185global stream_log_level186187libAdamApiPython.adam_lock_appPref()188license_key = memoryview(189libAdamApiPython.adam_get_appPref(LICENSE_KEY_PREF).encode()190)191token = memoryview(libAdamApiPython.adam_get_appPref(TOKEN_PREF).encode())192stream_log_level = libAdamApiPython.adam_get_appPref(LOGGING_PREF)193194libAdamApiPython.adam_unlock_appPref()195196debugDbg("loadPref adam_get_appPref")197debugDbg(f" license_key:{license_key}")198debugDbg(f" token:{token}")199debugDbg(f" stream_log_level :{stream_log_level}")200201libAdamApiPython.adam_debug_print(202libAdamApiPython.ADAM_LV_INF,203f"PLATEREC - license_key={license_key}, token={token}, stream_log_level={stream_log_level}",204)205206if license_key and token:207license_key_pref = license_key.tobytes().decode("utf-8")208token_pref = token.tobytes().decode("utf-8")209write_env_file(token_pref, license_key_pref, stream_log_level)210211212def setPref(pref_str):213global license_key214global token215global stream_log_level216217debugDbg(f"Set Pref: {pref_str}")218pref = pref_str.split(",")219license_key_pref = pref[0]220token_pref = pref[1]221log_level_pref = pref[2]222223license_key = memoryview(license_key_pref.encode())224token = memoryview(token_pref.encode())225stream_log_level = enum_values.index(log_level_pref)226227libAdamApiPython.adam_lock_appPref()228libAdamApiPython.adam_set_appPref({LICENSE_KEY_PREF: license_key_pref})229libAdamApiPython.adam_set_appPref({TOKEN_PREF: token_pref})230libAdamApiPython.adam_set_appPref({LOGGING_PREF: stream_log_level})231libAdamApiPython.adam_unlock_appPref()232233debugDbg("setPref adam_set_appPref")234debugDbg(f" license_key:{license_key_pref}")235debugDbg(f" license_token:{token_pref}")236debugDbg(f" stream_log_level :{stream_log_level}")237238write_env_file(token_pref, license_key_pref, stream_log_level)239240241def startProcessing():242global loop243loop = libAdamApiPython.adamEventloop()244loadPref()245loop.dispatch()246del loop247print("Finish: Process")248249250if __name__ == "__main__":251print("Start: main thread")252# adam.setPrintLevel(0xffffffff)253254libAdamApiPython.adam_set_stop_callback(stopCB)255libAdamApiPython.adam_set_http_callback(httpCB)256libAdamApiPython.adam_set_appPref_callback(appPrefCB)257258# Case of executing image processing in same thread.259startProcessing()260261print("Finish: main thread")262263264