#!/home/cbp/miniconda3/envs/cbp-base/bin/python
# -*- coding: utf-8 -*-
'''
Created on 25 Jun 2015

@author: Kimon Tsitsikas

Copyright © 2015 Kimon Tsitsikas, Delmic

This file is part of Odemis.

Odemis is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation.

Odemis is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with Odemis. If not, see http://www.gnu.org/licenses/.
'''

import logging
import os
import sys
import serial
import time
import fcntl
from odemis.util import to_str_escape

def main(args):
    """
    Handles the command line arguments
    args is the list of arguments passed
    return (int): value to return to the OS as program exit code
    """

    port = args[1]
    logging.debug("Trying to connect to device on port %s", port)
    # For now just turn off & on
    # value = args[2]

    # Connect to serial device
    ser = serial.Serial(
        port=port,
        timeout=5  # s
    )
    fcntl.flock(ser.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)

    # Purge
    ser.flush()
    ser.flushInput()

    # check IDN to make sure it is the correct HW
    cmd = b"*IDN?\n"
    ser.write(cmd)
    ans = b''
    char = None
    while char != b'\n':
        char = ser.read()
        ans += char
    logging.debug("Device identified itself as '%s'", to_str_escape(ans))
    if ans.startswith(b"Delmic Analog PMT"):
        # Send command
        logging.info("Will now reset the power relay for 10s.")
        ser.write(b"RELAY 0\n")
        time.sleep(10)
        ser.write(b"RELAY 1\n")
        logging.info("Power relay is active again.")
    else:
        return 1

    return 0

if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    try:
        handler = logging.FileHandler("/var/log/odemis-relay.log")
        handler.setFormatter(logging.Formatter('%(asctime)s (%(module)s) %(levelname)s: %(message)s'))
        logging.getLogger().addHandler(handler)
    except Exception:
        logging.warning("Logging failed to open log file")

    try:
        ret = main(sys.argv)
    except Exception:
        logging.exception("Failure during execution.")
        ret = 128
    exit(ret)
