#!/usr/bin/python

# $Header: https://oberon.oapd.inaf.it/shins/trunk/shins/test/end_2_end/telnet_connection.py 353 2017-12-14 11:06:33Z depa $

# Test script
# test basic telnet connection to motors using MoCon commands

import telnetlib
import timer
import signal
import sys

def connect(_host, _port, _timeout):
    # card number... is always 1
    CONST_CARD_N = 1
    # all MoCon have the same user and password. Commands are sent using telnetlib
    # `write` method. Carriage return `\r\n` must follow each command string
    tn = telnetlib.Telnet(_host, _port, _timeout)
    return tn

def test_connection(hostIP):

    # hosts = {
    # "host0": "192.168.1.51", # test MoCon in office
    # "host1": "192.168.103.50", # MoCon1 Stepper motors: 2 ADC, 1 rotator 
    # "host2": "192.168.103.51", # MoCon2 DC motors
    # "host3": "192.168.103.52", # MoCon3 DC motors
    # }
    # host0 = "192.168.1.51" # test MoCon in office
    # host1 = "192.168.103.50" # MoCon1 Stepper motors: 2 ADC, 1 rotator 
    # host2 = "192.168.103.51" # MoCon2 DC motors
    # host3 = "192.168.103.52" # MoCon3 DC motors

    # port is always the same
    port = 4000
    CONST_CARD_N = 1 # this does not change each IP has 1 card
    timeout = 3
    # for key in hosts.keys():
    onlineFlag = 0
    T = timer.timer()
    T.begin()
    print "\n> Opening telnet connection to host {} on port {}".format(hostIP, port)
    try :
        tn = connect(hostIP, port, timeout)

        if T.elapsed() >= timeout:
            onlineFlag = 0 # host is not reachable
            print "Connection to {} timeout!".format(hostIP)
        else:
            onlineFlag = 1

            print "> Closing connection\n"
        tn.close()

    except Exception as error:
        print error, onlineFlag

    return onlineFlag


# We have three MoCon boards: 3 hosts
if __name__ == "__main__":
    print "\nBEGIN TEST\n"
    # host0 = "192.168.1.51" # test MoCon in office
    # host1 = "" # MoCon1 Stepper motors: 2 ADC, 1 rotator 
    # host2 = "" # MoCon2 DC motors
    # host3 = "" # MoCon3 DC motors

    hosts = {
        "host0": "192.168.1.51", # test MoCon in office
        "host1": "192.168.103.50", # MoCon1 Stepper motors: 2 ADC, 1 rotator 
        "host2": "192.168.103.51", # MoCon2 DC motors
        "host3": "192.168.103.52", # MoCon3 DC motors
    }


    # # port is always the same
    # port = 4000
    # CONST_CARD_N = 1

    for key in hosts.keys():
        test_connection(hosts[key])

    # print "> Closing connection\n"
    # tn.close()

    print "\nEND TEST\n"

