Path: blob/master/stream/ipro-adam-app/python/pymain.py
1082 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 debug_dbg(str):15# libAdamApiPython.adam_debug_print(libAdamApiPython.ADAM_LV_DBG, "[DBG] {}".format(str))16print(f"[DBG] {str}")171819def debug_err(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 stop_cb():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):56debug_dbg("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 http_cb(req_type, req_data):73global license_key74global token75global stream_log_level7677print(f"HTTP callback: type={req_type}")78debug_dbg(f"HTTP callback: reqType={req_type}")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 directory98app_path = libAdamApiPython.adam_get_app_data_dir_path()99with open(f"{app_path}/index.html") as fp:100html_data = fp.read()101102print(f"reqType:{req_type}")103debug_dbg(f"call httpCB: reqType={req_type}")104if req_type == ADAM_HTTP_REQ_TYPE_GET:105debug_dbg("Show html")106# load AppPref107load_pref()108elif req_type == ADAM_HTTP_REQ_TYPE_POST:109debug_dbg("Edit html")110# set AppPref111set_pref(req_data.decode("utf-8"))112else:113debug_err(f"call httpCB: reqType={req_type}")114115# set AppPref parameter116context = []117# Get App Install ID118install_id = f"{libAdamApiPython.InstallId:08X}"119context.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))123124debug_dbg(f"Context: {context}")125126# replace parameters in html127for i, keywd in enumerate(template_literals):128html_data = html_data.replace(keywd, context[i])129header = create_respone_header(html_data)130131except Exception as e:132debug_err(f"httpCB Exception: {e}")133html_data = f"Server Error: {traceback.format_exc()}"134header = create_respone_header(html_data, 500)135136body = bytes(html_data, "utf-8")137return header, body138139140def get_stream_log_level_context(stream_log_level: int) -> list:141"""142Generate selected attribute for stream log level options.143"""144selected = 'selected="selected"'145unselected = ""146147context = []148149for i, _value in enumerate(enum_values):150if stream_log_level == i:151context.append(selected)152else:153context.append(unselected)154155return context156157158def app_pref_cb(pref_tuple):159global license_key160global token161global stream_log_level162163libAdamApiPython.adam_lock_appPref()164165if pref_tuple == LICENSE_KEY_PREF:166license_key = memoryview(167libAdamApiPython.adam_get_appPref(LICENSE_KEY_PREF).encode()168)169elif pref_tuple == TOKEN_PREF:170token = memoryview(libAdamApiPython.adam_get_appPref(TOKEN_PREF).encode())171172elif pref_tuple == LOGGING_PREF:173stream_log_level = libAdamApiPython.adam_get_appPref(LOGGING_PREF)174else:175print(f"Undefined AppPrefName: {pref_tuple}")176177libAdamApiPython.adam_unlock_appPref()178179180def load_pref():181global license_key182global token183global stream_log_level184185libAdamApiPython.adam_lock_appPref()186license_key = memoryview(187libAdamApiPython.adam_get_appPref(LICENSE_KEY_PREF).encode()188)189token = memoryview(libAdamApiPython.adam_get_appPref(TOKEN_PREF).encode())190stream_log_level = libAdamApiPython.adam_get_appPref(LOGGING_PREF)191192libAdamApiPython.adam_unlock_appPref()193194debug_dbg("loadPref adam_get_appPref")195debug_dbg(f" license_key:{license_key}")196debug_dbg(f" token:{token}")197debug_dbg(f" stream_log_level :{stream_log_level}")198199libAdamApiPython.adam_debug_print(200libAdamApiPython.ADAM_LV_INF,201f"PLATEREC - license_key={license_key}, token={token}, stream_log_level={stream_log_level}",202)203204if license_key and token:205license_key_pref = license_key.tobytes().decode("utf-8")206token_pref = token.tobytes().decode("utf-8")207write_env_file(token_pref, license_key_pref, stream_log_level)208209210def set_pref(pref_str):211global license_key212global token213global stream_log_level214215debug_dbg(f"Set Pref: {pref_str}")216pref = pref_str.split(",")217license_key_pref = pref[0]218token_pref = pref[1]219log_level_pref = pref[2]220221license_key = memoryview(license_key_pref.encode())222token = memoryview(token_pref.encode())223stream_log_level = enum_values.index(log_level_pref)224225libAdamApiPython.adam_lock_appPref()226libAdamApiPython.adam_set_appPref({LICENSE_KEY_PREF: license_key_pref})227libAdamApiPython.adam_set_appPref({TOKEN_PREF: token_pref})228libAdamApiPython.adam_set_appPref({LOGGING_PREF: stream_log_level})229libAdamApiPython.adam_unlock_appPref()230231debug_dbg("setPref adam_set_appPref")232debug_dbg(f" license_key:{license_key_pref}")233debug_dbg(f" license_token:{token_pref}")234debug_dbg(f" stream_log_level :{stream_log_level}")235236write_env_file(token_pref, license_key_pref, stream_log_level)237238239def start_processing():240global loop241loop = libAdamApiPython.adamEventloop()242load_pref()243loop.dispatch()244del loop245print("Finish: Process")246247248if __name__ == "__main__":249print("Start: main thread")250# adam.setPrintLevel(0xffffffff)251252libAdamApiPython.adam_set_stop_callback(stop_cb)253libAdamApiPython.adam_set_http_callback(http_cb)254libAdamApiPython.adam_set_appPref_callback(app_pref_cb)255256# Case of executing image processing in same thread.257start_processing()258259print("Finish: main thread")260261262