from channel import write_tag, read_tag
import json
from file_logger import filelogger as log

PLC_IP_ADDRESS = "10.20.4.18"

value = "{'tag': 'input1_cfg.ispond', 'value': 1}"

# {"tag": string, "val": }
try:
    new_val = json.loads(str(value).replace("'", '"'))
    tag_n = str(new_val['tag'])  # "cmd_Start"
    val_n = new_val['value']
    print("IP_ADDRESS: {}, VALUES: {} -- {}".format(PLC_IP_ADDRESS, tag_n, val_n))
    write_res = write_tag(str(PLC_IP_ADDRESS), tag_n, val_n, plc_type="Micro800")
    print("Result of multisensor_writeplctag(self, name, {}, plc_type=\"Micro800\") = {}".format(value, write_res))
    if write_res is None:
        write_res = "Error writing to PLC..."
    print(write_res)
    # return write_res
except ValueError as e:
    log.error("Error writing to PLC: {}\n{}".format(value, e))
    # return e
except KeyError as e:
    log.error("KeyError for key {} in JSON object: {}".format(e, value))
    # return e
# except Exception as e:
#     log.error("Caught error in _writeplctag({}): {}".format(value, e))
    # return e

