Tuesday, December 18, 2018

python picture analysis automotive

import pyautogui
import time
import os

'''
# keyhold
# alt + L - Drones:Launch drone
# R - Drones:Return to drone bay
# Alt+H - Reprocessing Plant
# PointTogoX PointTogoY - point to jump in Asteroid belt
# need to install in linux next app - wmctrl
'''

def SetActiveWindow(name):
    try:
        time.sleep(0.1)
        os.system('wmctrl -a "EVE - {}"'.format(name))
        return 1
    except Exception as e:
        print("Window is not opened " + str(e))
        return 0

#Constants
You_character_name = ''
PointComehomeX = 887
PointComehomeY = 475
PointComehomeX1 = 0
PointComehomeY1 = 0
teamViewerkillX = 1198
teamViewerkillY = 587
neut_checkX = 66
neut_checkY = 882

def killteamview():
    detectteamview = os.system('wmctrl -l | grep Sponsored')
    time.sleep(0.5)
    if detectteamview == 256:
        time.sleep(0.1)
    else:
        os.system('wmctrl -a "Sponsored session"')
        pyautogui.moveTo(teamViewerkillX, teamViewerkillY)
        time.sleep(0.5)
        print("Kill this bug")
        pyautogui.click()

def check_neut():
    neutcheckX = neut_checkX
    neutcheckY = neut_checkY
    im = pyautogui.screenshot()
    time.sleep(0.1)

    #cheack wite color
    for i in range(0, 30):
        char1 = im.getpixel((neutcheckX, neutcheckY))
        R = int(char1[0])
        G = int(char1[1])
        B = int(char1[2])

        while R >= 250 and G >= 250 and B >= 250:
            print("White pixel FUke")
            neutcheckY = neutcheckY + 1
            char1 = im.getpixel((neutcheckX, neutcheckY))
            R = int(char1[0])
            G = int(char1[1])
            B = int(char1[2])
            #print("valid")
        neutcheckY = neutcheckY + 5

        #cheack neutral in local
        if R > G and R > B and R > 30:
            print(R, G, B)
            print("Neut in system i go home")
            return_drone_to_board()
            jump_to_home()


def jump_to_home():
    time.sleep(1)
    killteamview()
    time.sleep(1)
    if SetActiveWindow(You_character_name) == 1:
        time.sleep(1)
        # Way to home
        PointComehomeX1 = PointComehomeX - 34
        PointComehomeY1 = PointComehomeY + 47
        pyautogui.moveTo(PointComehomeX, PointComehomeY)
        pyautogui.click()
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.moveTo(PointComehomeX1, PointComehomeY1)
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.press('f2')
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.press('d')
        time.sleep(80)
        pyautogui.press('d')
    else:
        print("Window is not opened")

def return_drone_to_board():
    time.sleep(1)
    killteamview()
    time.sleep(1)
    if SetActiveWindow(You_character_name) == 1:
        # drone come home
        time.sleep(2)
        pyautogui.press('r')
        time.sleep(3)
        pyautogui.press('r')
    else:
        print("Window is not opened")

def start_working_day():

    check_neut()
    print("next")
    time.sleep(5)

while True:
    start_working_day()

Tuesday, August 7, 2018

python use module pyautogui automatization

import pyautogui
import time
import os
import random

'''
# keyhold
# Alt+L - Drones:Launch drone
# R - Drones:Return to drone bay
# Alt+H - Reprocessing Plant
# PointTogoX PointTogoY - point to jump in Asteroid belt
# need to install in linux next app - wmctrl
'''

def SetActiveWindow(name):
    try:
        time.sleep(0.1)
        os.system('wmctrl -a "EVE - {}"'.format(name))
        return 1
    except Exception as e:
        print("Window EVE is not opened " + str(e))
        return 0

#Constants
You_character_name = ''
PointUndocButtonX = 914
PointUndocButtonY = 464
PointTogoX = 114
PointTogoY = 466
PointTogoSecX = 114
PointTogoSecY = 486
PointTogoX1 = 0
PointTogoY1 = 0
PointTogoX2 = 0
PointTogoY2 = 0
PointSelectOreX = 847
PointSelectOreY = 483
PointSelectOreX1 = 0
PointSelectOreY1 = 0
PointSelectOreX2 = 0
PointSelectOreY2 = 0
PointSelectOreX3 = 0
PointSelectOreY3 = 0
PointComehomeX = 887
PointComehomeY = 483
PointComehomeX1 = 0
PointComehomeY1 = 0
teamViewerkillX = 1198
teamViewerkillY = 587

def killteamview():
    detectteamview = os.system('wmctrl -l | grep Sponsored')
    time.sleep(0.5)
    if detectteamview == 256:
        time.sleep(0.1)
    else:
        os.system('wmctrl -a "Sponsored session"')
        pyautogui.moveTo(teamViewerkillX, teamViewerkillY)
        time.sleep(0.5)
        print("Kill this bug")
        pyautogui.click()

# Select Mining - start mining
def SelectMining():
    time.sleep(1)
    killteamview()
    time.sleep(1)
    if SetActiveWindow(You_character_name) == 1:
        #select in menu Mining - ore1
        PointSelectOreX1 = PointSelectOreX - 34
        PointSelectOreY1 = PointSelectOreY + 47
        #select in menu Mining - ore2
        PointSelectOreX2 = PointSelectOreX1 + 4
        PointSelectOreY2 = PointSelectOreY1 + 17
        time.sleep(2)
        pyautogui.moveTo(PointSelectOreX, PointSelectOreY)
        time.sleep(1)
        pyautogui.click()
        time.sleep(2)
        #select menu Mining
        pyautogui.moveTo(PointSelectOreX1, PointSelectOreY1)
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        # -Ore 1
        pyautogui.keyDown('ctrlleft')
        time.sleep(1)
        pyautogui.click()
        time.sleep(3)
        pyautogui.keyUp('ctrlleft')
        time.sleep(1)
        pyautogui.press('f1')
        time.sleep(1)
        # -Ore 2
        pyautogui.moveTo(PointSelectOreX2, PointSelectOreY2)
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.keyDown('ctrlleft')
        time.sleep(1)
        pyautogui.click()
        time.sleep(3)
        pyautogui.keyUp('ctrlleft')
        time.sleep(1)
        pyautogui.moveTo(PointSelectOreX2, PointSelectOreY2)
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.press('f2')
        time.sleep(1)
        #Salvage drone engage
        pyautogui.press('f')
        time.sleep(3)
    else:
        print("Window EVE is not opened")

def UnSelectMining():
    time.sleep(1)
    killteamview()
    time.sleep(1)
    if SetActiveWindow(You_character_name) == 1:
        time.sleep(2)
        #select in menu Mining - ore1
        PointSelectOreX1 = PointSelectOreX - 34
        PointSelectOreY1 = PointSelectOreY + 47
        #select in menu Mining - ore2
        PointSelectOreX2 = PointSelectOreX1 + 4
        PointSelectOreY2 = PointSelectOreY1 + 17
        #choose overview mine
        pyautogui.moveTo(PointSelectOreX, PointSelectOreY)
        time.sleep(1)
        pyautogui.click()
        # choose ore 1 and unselect
        time.sleep(1)
        pyautogui.moveTo(PointSelectOreX1, PointSelectOreY1)
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.hotkey('ctrlleft', 'shiftleft')
        # choose ore 2 and unselect
        time.sleep(1)
        pyautogui.moveTo(PointSelectOreX2, PointSelectOreY2)
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.hotkey('ctrlleft', 'shiftleft')
        time.sleep(1)
        # Unpress ore strip miners 1 2
        pyautogui.press('f1')
        time.sleep(1)
        pyautogui.press('f2')
        time.sleep(1)
        # Unselect targeting
        pyautogui.moveTo(215.639)
        time.sleep(1)
        pyautogui.click(215,639, button='right')
        time.sleep(2)
    else:
        print("Window EVE is not opened")

def docExit():
    time.sleep(1)
    killteamview()
    time.sleep(1)
    if SetActiveWindow(You_character_name) == 1:
        pyautogui.moveTo(PointUndocButtonX,PointUndocButtonY)
        time.sleep(1)
        pyautogui.click()
        time.sleep(2)
    else:
        print("Window EVE is not opened")

def SelectPointJump1():
    time.sleep(1)
    killteamview()
    time.sleep(1)
    if SetActiveWindow(You_character_name) == 1:
        time.sleep(1)
        pyautogui.hotkey('altleft', 'e')
        # Use random_coodrinate location(One or two)
        rnd = random.randint(0,1)
        if rnd == 1:
            pyautogui.moveTo(PointTogoX, PointTogoY)
            PointTogoX1 = PointTogoX + 20
            PointTogoY1 = PointTogoY + 5
        else:
            pyautogui.moveTo(PointTogoSecX, PointTogoSecY)
            PointTogoX1 = PointTogoSecX + 20
            PointTogoY1 = PointTogoSecY + 5
        time.sleep(1)
        pyautogui.click(button='right')
        time.sleep(2)
        pyautogui.moveTo(PointTogoX1, PointTogoY1)
        time.sleep(1)
        pyautogui.moveTo(PointTogoX1, PointTogoY1)
        pyautogui.click(button='right')
        time.sleep(2)
        pyautogui.moveTo(423, 644)
        time.sleep(1)
        pyautogui.click()
        time.sleep(2)
        pyautogui.hotkey('altleft', 'e')
        time.sleep(2)
    else:
        print("Window EVE is not opened")


def launch_drone():
    time.sleep(1)
    killteamview()
    time.sleep(1)
    if SetActiveWindow(You_character_name) == 1:
        time.sleep(1)
        # -launch drone
        for i in range(10):
            time.sleep(2)
            pyautogui.hotkey('altleft', 'l')
    else:
        print("Window EVE is not opened")

def return_drone_to_board():
    time.sleep(1)
    killteamview()
    time.sleep(1)
    if SetActiveWindow(You_character_name) == 1:
        # drone come home
        time.sleep(2)
        pyautogui.press('r')
        time.sleep(3)
        pyautogui.press('r')
        time.sleep(3)
        pyautogui.press('r')
        time.sleep(3)
        pyautogui.press('r')
        # off strip miners
        time.sleep(3)
        pyautogui.press('f1')
        time.sleep(3)
        pyautogui.press('f2')
        time.sleep(1)
        pyautogui.moveTo(509, 602)
        time.sleep(1)
        pyautogui.click(button='right')
        time.sleep(2)
    else:
        print("Window EVE is not opened")

def jump_to_home():
    time.sleep(1)
    killteamview()
    time.sleep(1)
    if SetActiveWindow(You_character_name) == 1:
        time.sleep(1)
        # Way to home
        PointComehomeX1 = PointComehomeX - 34
        PointComehomeY1 = PointComehomeY + 47
        time.sleep(2)
        pyautogui.moveTo(PointComehomeX, PointComehomeY)
        pyautogui.click()
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.moveTo(PointComehomeX1, PointComehomeY1)
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.press('d')
        time.sleep(80)
        pyautogui.press('d')
    else:
        print("Window EVE is not opened")

def SellOreInStation():
    time.sleep(1)
    killteamview()
    time.sleep(1)
    if SetActiveWindow(You_character_name) == 1:
        time.sleep(2)
        pyautogui.hotkey('altleft', 'c')
        time.sleep(3)
        # select Ore channel
        pyautogui.moveTo(125, 410)
        time.sleep(1)
        pyautogui.click()
        time.sleep(3)
        # select all
        pyautogui.moveTo(358, 502)
        time.sleep(1)
        pyautogui.click()
        time.sleep(1)
        pyautogui.hotkey('ctrlleft', 'a')
        time.sleep(1)
        pyautogui.moveTo(322, 427)
        time.sleep(1)
        pyautogui.click(button='right')
        time.sleep(2)
        pyautogui.moveTo(367, 468)
        time.sleep(2)
        pyautogui.click()
        # reprocess
        time.sleep(3)
        pyautogui.moveTo(772, 877)
        time.sleep(1)
        pyautogui.click()
        time.sleep(3)
        # close Inventory
        pyautogui.hotkey('altleft', 'h')
        time.sleep(2)
        pyautogui.hotkey('altleft', 'c')
        time.sleep(1)
    else:
        print("Window EVE is not opened")

def start_working_day():

    docExit()
    time.sleep(10)
    SelectPointJump1()
    time.sleep(22)
    #SelectPointJump1
    #time.sleep(50)
    launch_drone()
    time.sleep(1)
    SelectMining()
    time.sleep(600)
    UnSelectMining()
    time.sleep(1)
    SelectMining()
    time.sleep(600)
    UnSelectMining()
    time.sleep(2)
    SelectMining()
    time.sleep(600)
    return_drone_to_board()
    time.sleep(5)
    jump_to_home()
    time.sleep(20)
    SellOreInStation()
    time.sleep(10)


while True:
    start_working_day()

Friday, August 3, 2018

Python calculate CRC8 from data array

# Calculate CRC8 from data array 
def Count_CRC8(dataArray):
    crc = 0x00 
    for data in dataArray:
        for i in range(8):
            temp = (crc ^ data) & 0x1 
            if (temp == 1):
                crc = (crc) ^ 0x18
            crc = (crc >> 1) & 0x7f
            if(temp == 1):
                crc |= 0x80
            data >>= 1     
    return crc
 
'''
How to use
We have array a = ['0x01','0xc5','0x18']

use:
Count_CRC8(a)
 
''' 

Python send bit byte and read bit byte using serial port

import serial, time

# initialization and open the port# possible timeout values:# 
1. None: wait forever, block call# 
2. 0: non-blocking mode, return immediately# 
3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
ser.port = "/dev/ttyUSB1" 
ser.baudrate = 115200 
ser.bytesize = serial.EIGHTBITS   
# number of bits per bytes 
ser.parity = serial.PARITY_NONE   
# set parity check: no parity 
ser.stopbits = serial.STOPBITS_ONE   
# number of stop bits
#ser.timeout = None 
#block read 
ser.timeout = 1  # non-block read# ser.timeout = 2 
#timeout block read
ser.xonxoff = False  # disable software flow control
ser.rtscts = False  # disable hardware (RTS/CTS) flow control 
ser.dsrdtr = False  # disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2  # timeout for write
 
# Connect to board using serial port with speed 'baudrate' 
def connect_to_board(baudrate):
    try:
        ser.baudrate = baudrate
        if (ser.isOpen() == False):
            ser.open()
        ser.flushInput()  # flush input buffer, discarding all its contents         
        ser.flushOutput()  # flush output buffer, aborting current output 
        return True 
    except Exception as e:
        print("Error open serial port: " + str(e))
        return False 
 
# Connect to board with number of try 
def try_connect_to_board(baudrate, count_of_Try):
    tryCount = count_of_Try
    connection = connect_to_board(baudrate)
    while tryCount > 0 and connection == False:
        connection = connect_to_board(baudrate)
        tryCount = tryCount - 1 
        time.sleep(1)
    if tryCount == 0 and connection == False:
        print("Critical error in opening serial port")
        exit()

# Close serial port 
def Close_serial_board():
    try:
        ser.close()
        return True    except Exception as e:
        print("Error open serial port: " + str(e))
        return False 
 
# Set reset in line 
def try_Set_line_in_reset():
    try:
        Resetbyte = (b'\xf0')
        tryCount = 4         
        lineState = 0
        ser.write(Resetbyte)
        time.sleep(0.5)  # give the serial port sometime to receive the data 
        response = ser.readline()
        while response == b'\xf0' or response == b'' and tryCount != 0:
            ser.write(Resetbyte)
            time.sleep(0.5)
            response = ser.readline()
            tryCount = tryCount - 1 
            print('Try reset line state - {}' + str(tryCount))
        if response != b'\xf0' or b'':
            print('Device detected - {} '.format(response))
            lineState = 1 
    except Exception as e:
        print("There is a problem in reseting line state: " + str(e))
    return lineState

# Send 1 bit information, 1 or 0 
def SendBit(bit):
    try:
        if bit == 0:
            Zerobyte = (b'\x00')
            ser.write(Zerobyte)
            #time.sleep(0.5)             
            cheakBit = ser.read(1)
            if cheakBit != b'\x00':
                print("Readed 0 bit not the same")
        elif bit == 1:
            Onebyte = (b'\xff')
            ser.write(Onebyte)
            #time.sleep(0.5)             
            cheakBit = ser.read(1)
            if cheakBit != b'\xff':
                print("Readed 1 bit not the same")
        else:
            print("Sended bit is not correct")
    except Exception as e:
        print("Error in sending bit : " + str(e))
        exit()

# Send 1 byte of information
 def SendByte(byte):
    try:
        sendByte = []
        for i in range(8):
            bit = byte & 0x01;
            SendBit(bit)
            sendByte.append(bit)
            time.sleep(0.1)
            byte = byte >> 1     
    except Exception as e:
        print("error open serial port: " + str(e))
        exit()

#Read 1 bit information, FF or 0 
def ReadBit():
    try:
        Zerobyte = (b'\xff')
        ser.write(Zerobyte)
        time.sleep(0.1)
        cheakBit = ser.read(1)
        if cheakBit == b'\xff':
            return 1 
        else:
            return 0 
    except Exception as e3:
        print("error open serial port: " + str(e3))
        exit()

# Read 1 byte information 
def ReadByte():
    byte = []
    for i in range(8):
        #print("Operation number is {}".format(i)) 
        bit = ReadBit()
        #time.sleep(0.1)         
        byte.append(bit)
    #print(byte)
    byte.reverse()
    byte = ''.join(map(str, byte))
    #print(byte) 
    byte = int(byte, 2)
    #print(byte) 
    byte = hex(byte)
    return byte

 
'''
How to use
try_connect_to_board(115200, 5) 
SendByte(0xcc)
ReadByte() 
''' 

Python send data in serial port and receive data from serial port

import serial, time

# initialization and open the port# possible timeout values:# 
1. None: wait forever, block call# 
2. 0: non-blocking mode, return immediately# 
3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
ser.port = "/dev/ttyUSB1" 
ser.baudrate = 115200 
ser.bytesize = serial.EIGHTBITS   
# number of bits per bytes 
ser.parity = serial.PARITY_NONE   
# set parity check: no parity 
ser.stopbits = serial.STOPBITS_ONE   
# number of stop bits
#ser.timeout = None 
#block read 
ser.timeout = 1  # non-block read# ser.timeout = 2 
#timeout block read
ser.xonxoff = False  # disable software flow control
ser.rtscts = False  # disable hardware (RTS/CTS) flow control 
ser.dsrdtr = False  # disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2  # timeout for write
 
import re

# Send 1 command is serial port and receive data array
def sendCmd(input):
    try:
        ser.write(input.encode())
        time.sleep(0.1)
        dataArray = []
        data = ser.readline()
        startSendingdata_time = time.clock()
        print("Sending data in serial port: {}".format(input))
        # cheaktimer if data isn't going for 3 sec         
        if len(data) == 0:
            lostData_time = time.clock()
        while len(data) == 0 and (lostData_time - startSendingdata_time) < 3:
            time.sleep(1)
            lostData_time = time.clock()
            print("There isn't any data, system is waiting")
        while not len(data) == 0:
            data = ser.readline()
            # cheak if data has spases and non-data information             
            if data != b'# \r\n' and data != b'# ' and data != b'':
                data = (data[0:-2])
                data = data.decode('ascii')
                dataWithout_non_printable_characters = re.sub(r'(\x1b[/[])[0-9]?[;]?[0-9]?[0-9]{1}m', "", data)
                dataArray.append(dataWithout_non_printable_characters)
    except Exception as e:
        print("Can't send data in serial port: " + str(e))
        exit()
    return dataArray

'''
How to use - for example linux pwd command: 
sendCmd('pwd' + '\r\n')
 
answer: 
'/root'
''' 

Tuesday, August 26, 2014

Automatization in Python testing GUI (Python paramiko, Python xlrd, Python FTP)

Моя задача была протестировать работу WEB GUI приложения которое распознает видео и делает снимки далее выводит список комбинаций найденных на снимках.

Видео файл - в котором показываются однорукие бандиты казино, распознаются видео остановки барабанов и комбинаций выпавших.

import xlrd
from tkinter import *
from tkinter import messagebox
import paramiko
import time

'''
Function help to destroy program window
'''
def quit(root):
    root.destroy()


'''
Start program, connection by SSH
'''
def startConnectToSSH(event):
    try:
        host = str(loginent1.get())
        user = str(loginent2.get())
        secret = str(loginent3.get())
        port = int(loginent4.get())
       
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname=host, username=user, password=secret, port=port)
        quit(loginssh)
        print("Connect is done")

       
        class videoProcessingDisplay():
            '''
            Function for display in UI all information
            '''
            def insertOtchet(self, str3):
                tex1.insert(INSERT, str3, "a")
               
        class videoProcessingClass():
          
            '''
            Function for clear rezults display 
            '''
            def clearOtchetWindow(self, event):
                tex1.delete(1.0, END)
           
            '''
            Button check Connect to SSH 
            '''
            def checkConnecttoSSH(self, event):
                disp.insertOtchet("Wait please check connection")
                disp.insertOtchet("\n")
                try:
                    client.exec_command('ls')
                    disp.insertOtchet("Connection is active")
                    disp.insertOtchet("\n")
                except BaseException as e:
                    disp.insertOtchet("Connection restored, stay 1 min.")
                    disp.insertOtchet("\n")
                    client.connect(hostname=host, username=user, password=secret, port=port)
                    return 2
                return 1
           
            '''
            Auto check Connect to SSH, automated
            '''
            def autoCheckConnecttoSSH(self):
                disp.insertOtchet("Wait please auto check connection")
                disp.insertOtchet("\n")
                try:
                    client.exec_command('ls')
                    disp.insertOtchet("Connection is active")
                    disp.insertOtchet("\n")
                except BaseException as e:
                    disp.insertOtchet("Connection restored, stay 1 min.")
                    disp.insertOtchet("\n")
                    client.connect(hostname=host, username=user, password=secret, port=port)
                    return 2
                return 1
           
            '''
            Main function how compare 2 files, automated
            '''
            def nashaloSravneniya(self, event):
                def convertFromdoubleToString(str4):
                    arr3 = []
                    for i in str4:
                        if i == 1.0:
                            arr3.append("GR")
                        elif i == 2.0:
                            arr3.append("OR")
                        elif i == 3.0:
                            arr3.append("PL")
                        elif i == 4.0:
                            arr3.append("LE")
                        elif i == 5.0:
                            arr3.append("BE")
                        elif i == 6.0:
                            arr3.append("CH")
                        elif i == 7.0:
                            arr3.append("GR")
                        else:
                            print("Error in elements")
                            break
            #             print(arr3)   
                    return arr3
               
                '''
                function how compare 2 string for example and say if is error
                a = [GR    GR    GR    ME    ME    CH    ME    ME    PL    OR    LE    LE    CH    ME    ME]
                b = [LE    OR    OR    LE    LE    LE    BE    BE    BE    OR    OR    GR    PL    PL    CH]
                '''
               
                def sravnenieStrok(str1,str2):
                    arr1 = []
                    arr2 = []
               
                    for i in str1:
                        arr1.append(i.rstrip().replace(" ","").split(","))
                    for i2 in str2:
                        arr2.append(i2.rstrip().replace(" ","").split(","))
                    #proverka dlini strok
                    if len(arr1[0]) != len(arr2[0]):
                        disp.insertOtchet("Error: files has different reels configs, check files")
                   
                    #probegau po 15 znacheniyam strok i sravnivau ix   
                    i3 = 1
                    bads = 0
                    while i3 <= 15:
                        #print(arr1[i3], arr2[i3])
                        if arr1[i3] == arr2[i3]:
                            i3=i3+1
                        else:
                            i3=i3+1
                            bads=bads+1
                    disp.insertOtchet("Errors = {}" .format(bads))
                    disp.insertOtchet("\n")
                    return bads  
               
               
                choiseFomatFile = int(var.get())
                #print(choiseFomatFile)
                if choiseFomatFile == 0:
                    str5 = str(ent1.get())
                    str6 = str(ent2.get())
                    disp.insertOtchet("Choise csv format")
                   
                   
                    ins = open(str5, "r" )
                    testFileRows = []
                    for line in ins:
                        testFileRows.append(line.split(";"))
                    ins.close()
                   
                    ins1 = open(str6, "r" )
                    customerFileRows = []
                    for line1 in ins1:
                        customerFileRows.append(line1.split(";"))
                    ins1.close()
                   
                    try:
                        koefficentOfCorrection=0
               
                        for rownum in range(len(customerFileRows)):
                            numeraciyaStrok = ("Row =", rownum+1)
                            disp.insertOtchet(str(numeraciyaStrok))
                            disp.insertOtchet("\n")
                            if sravnenieStrok(testFileRows[rownum],customerFileRows[rownum+koefficentOfCorrection])>3:
                                disp.insertOtchet("String is very different, check comparing with next customer row")
                                disp.insertOtchet("\n")
                                if sravnenieStrok(testFileRows[rownum],customerFileRows[rownum+1])>3:
                                    disp.insertOtchet("Finaly, in test file row has many errors")
                                    disp.insertOtchet("\n")
                                else:
                                    koefficentOfCorrection=koefficentOfCorrection+1
                                    disp.insertOtchet("Timestamp is missed, to customer row number add 1 point. Correction = {}".format(koefficentOfCorrection))
                                    disp.insertOtchet("\n")
                               
                    except  AttributeError as err:
                        error = ("Error: {} break operation".format(err))
                        disp.insertOtchet("\n")
                        disp.insertOtchet(str(error))
                    except  IndexError as err1:
                        error1 = ("Number of timestamps is different in testing file and customer file")
                        disp.insertOtchet("\n")
                        disp.insertOtchet(str(error1))
                   
                else:
                    disp.insertOtchet("Choise xls format")
                    str5 = str(ent1.get())
                    str6 = str(ent2.get())
                    Testfile = ("Test file",   str5)
                    Customerfile = ("Customer file", str6)
               
                    disp.insertOtchet(str(Testfile))
                    disp.insertOtchet("\n")
                    disp.insertOtchet(str(Customerfile))
                    disp.insertOtchet("\n")
                   
               
                      
                    rbCustom = xlrd.open_workbook(str5,formatting_info=True)
                    sheet = rbCustom.sheet_by_index(0)
               
                    rbProgect = xlrd.open_workbook(str6,formatting_info=True)
                    sheetProgect = rbProgect.sheet_by_index(0)
            
                    '''
                    body of program, in opened both .xls files compare elements and do rezults table
                    '''
                   
                    try:
               
                        for rownum in range(sheet.nrows):
                            numeraciyaStrok = ("Row =", rownum+1)
                            disp.insertOtchet(str(numeraciyaStrok))
                            disp.insertOtchet("\n")
                            rowTest = sheet.row_values(rownum)
                            rowCustomer = sheetProgect.row_values(rownum)
                            sravnenieStrok(rowTest,rowCustomer)
                    except  AttributeError as err:
                        error = ("Error: {} break operation".format(err))
                        disp.insertOtchet("\n")
                        disp.insertOtchet(str(error))
           
           
            
            '''
            Command line client to server, button
            '''
            def testConnectBySSH(self, event):
                if self.autoCheckConnecttoSSH() == 1:
                    str6 = str(ent3.get())
                    disp.insertOtchet("\n")
                    stdin, stdout, stderr = client.exec_command(str6)
                    data = stdout.read() + stderr.read()
                    disp.insertOtchet(data)
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
            '''
            Send Digitizing.war to server, automated
            '''
            def testUploadFile(self):
                if self.autoCheckConnecttoSSH() == 1:
                    disp.insertOtchet("Upload Digitizing.war to server")
                    disp.insertOtchet("\n")
                    ftp = client.open_sftp()
                    ftp.put('Digitizing.war', 'Digitizing.war')
                    ftp.close()
                    disp.insertOtchet("Ok, file copy from PC to server")
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
           
            '''
            Download rezults from server button
            '''   
            def testDownloadFile(self,event):
                if self.autoCheckConnecttoSSH() == 1:
                    disp.insertOtchet("Download rezults from server")
                    disp.insertOtchet("\n")
                    #cleapatra 10 min
                    stdin, stdout, stderr = client.exec_command("wget \"http://192.168.10.221:8080/Digitizing/RawDataResponder?vid=21&cols=5&rows=3\" --output-document=Cleapatra10min_x264.csv")
                    #cleapatra 1 min
                    #stdin, stdout, stderr = client.exec_command("wget \"http://192.168.10.221:8080/Digitizing/RawDataResponder?vid=22&cols=5&rows=3\" --output-document=Cleapatra1min_x264.csv")
                    time.sleep( 1 )
                    ftp = client.open_sftp()
                    #cleapatra 10 min
                    ftp.get('Cleapatra10min_x264.csv', 'Cleapatra10min_x264.csv')
                    #cleapatra 1 min
                    #ftp.get('Cleapatra1min_x264.csv', 'Cleapatra1min_x264.csv')
                    ftp.close()
                    disp.insertOtchet("Ok, file with rezults is comming to PC")
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")

            '''
            Download rezults from server in automated scripts
            '''   
            def testDownloadFileAutomat(self):
                if self.autoCheckConnecttoSSH() == 1:
                    disp.insertOtchet("Download rezults from server")
                    disp.insertOtchet("\n")
                    #cleapatra 10 min
                    stdin, stdout, stderr = client.exec_command("wget \"http://192.168.10.221:8080/Digitizing/RawDataResponder?vid=21&cols=5&rows=3\" --output-document=Cleapatra10min_x264.csv")
                    #cleapatra 1 min
                    #stdin, stdout, stderr = client.exec_command("wget \"http://192.168.10.221:8080/Digitizing/RawDataResponder?vid=22&cols=5&rows=3\" --output-document=Cleapatra1min_x264.csv")
                    time.sleep( 1 )
                    ftp = client.open_sftp()
                    #cleapatra 10 min
                    ftp.get('Cleapatra10min_x264.csv', 'Cleapatra10min_x264.csv')
                    #cleapatra 1 min
                    #ftp.get('Cleapatra1min_x264.csv', 'Cleapatra1min_x264.csv')
                    ftp.close()
                    disp.insertOtchet("Ok, file with rezults is comming to PC")
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
           
            '''
            Get status of Video processing in server
            '''         
            def getStatusofVideoProcess(self):
                if self.autoCheckConnecttoSSH() == 1:
                    disp.insertOtchet("Get process = ")
                   
                    #cleopatra 1 min
                    #stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=getprocprogress&videoID=22\"")
                    #cleopatra 10 min
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=getprocprogress&videoID=21\"")
                               
                    data = stdout.read() + stderr.read()
                    pattern = r"progress\":([0-9]{1,3})"
                    regexp = re.compile(pattern)
                    s = regexp.findall(str(data))
                    znachenieVideoProcess = s[0]
                    disp.insertOtchet(znachenieVideoProcess)
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
                return znachenieVideoProcess
           
           
            '''
            Update new Build of VideoRecognization programon to Server
            ''' 
            def updateNewBuildofVideoRecognizationProgramonServer(self, event):
                if self.autoCheckConnecttoSSH() == 1:
                    time.sleep( 1 )
                    disp.insertOtchet("Process of updateing new build on server is start, remain 30 second")
                    disp.insertOtchet("\n")
                   
                    time.sleep( 1 )
                    stdin, stdout, stderr = client.exec_command("rm Digitizing.war")
                   
                    time.sleep( 1 )
                    main.testUploadFile()
                   
                    time.sleep( 5 )
            
                    stdin, stdout, stderr = client.exec_command("/opt/tomcat8/bin/shutdown.sh")
                   
                    time.sleep( 2 )
                   
                    stdin, stdout, stderr = client.exec_command("sudo rm -rf /opt/tomcat8/webapps/Digitizing")
                   
                    time.sleep( 5 )
                   
                    stdin, stdout, stderr = client.exec_command("cp Digitizing.war /opt/tomcat8/webapps/")
                   
                    time.sleep( 5 )
                   
                    stdin, stdout, stderr = client.exec_command("cd /opt/tomcat8/webapps/ && unzip Digitizing.war -d Digitizing")
                   
                    time.sleep( 10 )
                   
                    stdin, stdout, stderr = client.exec_command("/opt/tomcat8/bin/startup.sh")
                   
                    time.sleep( 5 )
                   
                    stdin, stdout, stderr = client.exec_command("sudo reboot")
            
                    disp.insertOtchet("\n")
                    disp.insertOtchet("Operation is well done")
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
       
            '''
            Start process VideoRecognization on Server
            '''         
            def startProcessVideoRecognizationOnServer(self, event):
                if self.autoCheckConnecttoSSH() == 1:
                    time.sleep( 1 )
                   
                    disp.insertOtchet("Start process of video recognization on server")
                    print("Start process of video recognization on server")
                    disp.insertOtchet("\n")
                    time.sleep( 2 )
               
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=cleanup\"")
                    
                    disp.insertOtchet("Clean tables \n")
                    print("Clean tables")
                    time.sleep( 2 )
                    
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=inittables\"")
                    
                    disp.insertOtchet("Create tables \n")
                    print("Create tables")
                    time.sleep( 2 )
                   
                    stdin, stdout, stderr = client.exec_command("cd && rm Cleapatra10min_x264.csv")
                   
                    time.sleep( 1 )
                            
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=addproject&name=testVideo53&reels=2&description=Autotest\"")
                    
                    disp.insertOtchet("Create progect \n")
                    print("Create progect")
                    time.sleep( 2 )
       
                    #cleopatra 10 min
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=addvideo&fileName=Cleapatra10min_x264.mp4\"")           
                    #cleopatra 1 min
                    #stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=addvideo&fileName=Cleapatra1min_x264.mp4\"")
                    
                    disp.insertOtchet("Open file Cleapatra10min_x264.mp4 \n")
                    print("Open file Cleapatra10min_x264.mp4")
                    time.sleep( 2 )
                   
                    #cleopatra 10 min
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=startvideoproc&videoID=21&timestamp=0&cols=5&rows=3&x1=0.10015649452269171&y1=0.3235908141962422&x2=0.917057902973396&y2=0.32150313152400833&x3=0.10485133020344288&y3=0.9728601252609603&x4=0.8998435054773083&y4=0.9624217118997912\"")
                    #cleopatra 1 min
                    #stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=startvideoproc&videoID=22&timestamp=0&cols=5&rows=3&x1=0.10015649452269171&y1=0.3235908141962422&x2=0.917057902973396&y2=0.32150313152400833&x3=0.10485133020344288&y3=0.9728601252609603&x4=0.8998435054773083&y4=0.9624217118997912\"")
                    
                    disp.insertOtchet("Video proccesing is start \n")
                    print("Video proccesing is start")
                    time.sleep( 2 )
                   
                    b=0
                    while True:
                        print(b)
                        if ((int(self.getStatusofVideoProcess()) != 0) or b==1):
                            b=1
                            if ((int(self.getStatusofVideoProcess()) == 0 or int(self.getStatusofVideoProcess()) == 100) and b==1):
                                main.testDownloadFileAutomat()
                                print("Download rezults !")
                                break
                            else:
                                disp.insertOtchet("Wait please, process in progress = \n")
                                print("In progress = ", self.getStatusofVideoProcess(), "\n")
                                disp.insertOtchet(self.getStatusofVideoProcess())
                                time.sleep( 5 )
                        else:
                            disp.insertOtchet("Wait please, process in progress = \n")
                            print("Wait please, process in progress = ", self.getStatusofVideoProcess(), "\n")
                            disp.insertOtchet(self.getStatusofVideoProcess())
                            time.sleep( 2 )
           
                
            
                    disp.insertOtchet("Ok, file with rezults is comming to PC press button Compare combinations in files")
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
                   
        disp = videoProcessingDisplay()
        main = videoProcessingClass()
        
        '''
        GUI of program
        '''
        user = Tk()
        user.title("Vuni combination tester")
        user.grid(100, 100, 300, 300)
       
        def handler():
            if messagebox.askyesno("Exit", "Exit from program") == True:
                client.close()
                quit(user)
        user.protocol("WM_DELETE_WINDOW", handler)
       
        lab1 = Label(user, text="Testing file name ", font="Arial 10")
        ent1 = Entry(user, width=40, bd=3, text="testing file")
        ent1.insert(0, "Cleapatra10min_x264.csv")
       
        lab2 = Label(user, text="Customer file name ", font="Arial 10")
        ent2 = Entry(user, width=40, bd=3, text="customer file")
        ent2.insert(0, "LastVariandCleapatra10min_x264.csv")
       
        ent3 = Entry(user, width=40, bd=3, text="command line")
        ent3.insert(0, "cp Digitizing.war /opt/tomcat8/webapps/")
       
        tex1 = Text(user,width=50, height=25, font="Verdana 12",wrap=WORD)
       
        but1 = Button(user, text="Compare combinations in files ", width=25, height=1, font="Verdana 12")
        but2 = Button(user, text="Command to server by SSH", width=25, height=1, font="Verdana 12")
        but3 = Button(user, text="Clear window", width=25, height=1, font="Verdana 12")
        but4 = Button(user, text="Upload new build to server 30 sec", width=25, height=1, font="Verdana 12")
        but5 = Button(user, text="Start process of video on server", width=25, height=1, font="Verdana 12")
        but6 = Button(user, text="Check connection to Server", width=25, height=1, font="Verdana 12")
        but7 = Button(user, text="Download rezults", width=25, height=1, font="Verdana 12")
       
        but1.bind("<Button-1>", main.nashaloSravneniya)
        but2.bind("<Button-1>", main.testConnectBySSH)
        but3.bind("<Button-1>", main.clearOtchetWindow)
        but4.bind("<Button-1>", main.updateNewBuildofVideoRecognizationProgramonServer)
        but5.bind("<Button-1>", main.startProcessVideoRecognizationOnServer)
        but6.bind("<Button-1>", main.checkConnecttoSSH)
        but7.bind("<Button-1>", main.testDownloadFile)
       
        var=IntVar()
        var.set(0)
        rad0 = Radiobutton(user,text="csv",
                  variable=var,value=0)
        rad1 = Radiobutton(user,text="xls",
                  variable=var,value=1)
       
        lab1.grid(row=1, column=0)
        ent1.grid(row=2, column=0)
        lab2.grid(row=3, column=0)
        ent2.grid(row=4, column=0)
        tex1.grid(row=0, column=1)
        ent3.grid(row=6, column=1)
       
        rad0.grid(row=5, column=1)
        rad1.grid(row=5, column=2)
       
        but1.grid(row=5, column=0)
        but2.grid(row=6, column=0)
        but3.grid(row=7, column=0)
        but4.grid(row=8, column=0)
        but5.grid(row=9, column=0)   
        but6.grid(row=0, column=0)
        but7.grid(row=10, column=0)
       
        user.mainloop()
       
    except TimeoutError and paramiko.ssh_exception.AuthenticationException:
        messagebox.showwarning("Error", "Connect to host is unavailible")
        quit(loginssh)
        #print("Connect to host is unavailible - {}".format(err))


'''
If user press button Cancel, exit program
'''
def exitProgramAborted(event):
    print("Cancel")
    loginssh.quit()

if __name__ == "__main__":
   
    loginssh = Tk()
    loginssh.title("Connect to Server by SSH")
    loginssh.grid(100, 100, 200, 200)
   
    loginlab1 = Label(loginssh, text="Server machine host ", font="Arial 10")
    loginent1 = Entry(loginssh, width=40, bd=3, text="192.168.10.221")
    loginent1.insert(0, "192.168.10.221")
   
    loginlab2 = Label(loginssh, text="User name", font="Arial 10")
    loginent2 = Entry(loginssh, width=40, bd=3, text="user")
    loginent2.insert(0, "user")
   
    loginlab3 = Label(loginssh, text="User password", font="Arial 10")
    loginent3 = Entry(loginssh, width=40, bd=3, text="userpass")
    loginent3.insert(0, "userpass")
   
    loginlab4 = Label(loginssh, text="Server port", font="Arial 10")
    loginent4 = Entry(loginssh, width=40, bd=3, text="22")
    loginent4.insert(0, "22")
   
    loginbut1 = Button(loginssh, text="Cancel", width=10, height=2, font="Verdana 12")
    loginbut2 = Button(loginssh, text="Connect", width=10, height=2, font="Verdana 12")
   
    loginlab1.grid(row=0, column=0)
    loginent1.grid(row=0, column=1)
    loginlab2.grid(row=1, column=0)
    loginent2.grid(row=1, column=1)
    loginlab3.grid(row=2, column=0)
    loginent3.grid(row=2, column=1)
    loginlab4.grid(row=3, column=0)
    loginent4.grid(row=3, column=1)
   
    loginbut1.bind("<Button-1>", exitProgramAborted)
    loginbut2.bind("<Button-1>", startConnectToSSH)
   
    loginbut1.grid(row=4, column=1)
    loginbut2.grid(row=4, column=2)
   
   
    loginssh.mainloop()