# -*- coding: utf-8 -*-
# ##############################################################################
#
#           Copyright (c) AIM GmbH 2019, 79111 Freiburg, Germany.
#
#           All rights reserved. No part of this software may
#           be published, distributed, translated or otherwise
#           reproduced by any means or for any purpose without
#           the prior written consent of AIM GmbH, Freiburg.
#
#-------------------------------------------------------------------------------
#   $Workfile:   easyload615a_remote_client.py$
#-------------------------------------------------------------------------------
#
#   Description:
"""
    Provides a socket based interface to control the most important 
    Dataloader-functions of EasyLOAD-615A as there are:
        "A665BUILD"
        "ETHFIND"
        "AFDXFIND"
        "INFO"
        "UPLOAD"
        "MDOWNLOAD"
        "TDILOAD"
        "ABORT"
        "GETLOG"
    For detailed information read the EasyLOAD-615A User Manual
"""
#
#
# ##############################################################################
import socket
import time
import sys

import tempfile

defaultHOST = "localhost"
defaultPORT = 5150


class EasyLOAD615ARemoteInterface():
    """
    Provides a socket based interface to control the most important Dataloader-functions of EasyLOAD-615A
    """
    def __init__(self, bPrintResponses = True):
        self._sock = None
        self._lresponses = []
        self._bPrintResponses = bPrintResponses

    def __del__(self):
        self._close()

    def _connect(self, aHost=defaultHOST, aPort=defaultPORT):
        self._close()

        for res in socket.getaddrinfo(aHost, aPort, socket.AF_UNSPEC, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self._sock = socket.socket(af, socktype, proto)
            except socket.error as msg:
                self._sock = None
                continue
            try:
                self._sock.connect(sa)
            except socket.error as msg:
                self._sock.close()
                self._sock = None
                continue
            break
        if self._sock is None:
            raise Exception('could not open socket')
        
    def _close(self):
        if not self._sock is None:
            self._sock.close()
            self._sock = None       

    def _sendCmd(self, cmdString):        
        self._sock.sendall( (cmdString+'\0').encode())

    def _receiveTillEnd(self, timeoutSecs=5):
        startTime = time.time()
        bTimeOut = False
        bCommandFinished = False
        bError = False
        lErrorResponses = [
            "Unrecognized or not yet supported Command",
            "Operation Not Licensed",
            "Connection Not Available",
            "Target Not Available",
            "Command Not Allowed",
            "Command Error",
            "Syntax Error",
            "DLP Error Occured",
            "Fatal DLP Error",
            "Error Message Received from DLP"
        ]
        while not bCommandFinished and not bTimeOut:
            s = self._sock.recv(1024)
            s = s.decode()
            if len(s):
                for errorResp in lErrorResponses:
                    if s.count(errorResp):
                        bCommandFinished = True
                        bError = True
                        break                
                if s.count("Command Execution Complete") or s.count("Command Execution in progress..."):
                    bCommandFinished = True    
                if self._bPrintResponses:
                    print(s)            
                self._lresponses += s.split('\n')
            if (timeoutSecs > 0.0) and (time.time() - startTime > timeoutSecs):
                bTimeOut = True
            else:
                if not bCommandFinished:
                    time.sleep(0.1)

        if bCommandFinished and not bError:
            return True
        else:
            return False

    def _responseContains(self, aString):
        for response in self._lresponses:
            if response.count(aString):
                return True
        return False


    def _handleCmd(self, sCmd, timeOutSecs=5):
        if len(sCmd) == 0:
            return False

        if self._sock is None: # if not connected yet... do it now with default settings!!!
            self._connect()

        self._lresponses = []
        self._sendCmd(sCmd)
        bRet = self._receiveTillEnd(timeOutSecs)
        self._close() # easyload automatically closes the socket after a command was handled
        return bRet


    def buildMediaSet(self, sPathToEmdFile, checkAfterwards=False):
        sCmd = "A665BUILD" + " " + sPathToEmdFile + (" -V" if checkAfterwards else "")
        if self._handleCmd(sCmd):
            if self._responseContains("was successfully created"):
                return True
        return False

    def loadTdiFile(self, sPathToTdiFile):
        sCmd = "TDILOAD" + " " + sPathToTdiFile
        if self._handleCmd(sCmd):
            return True
        return False


    def info(self, sTHWId, sTHWPos, timeOutSecs=5):
        sCmd = "INFO" + " " + sTHWId +  " " +  sTHWPos
        if self._handleCmd(sCmd, timeOutSecs + 0.5):
            if self._responseContains("Information Message Received"):
                return True
        return False


    def upload(self, sPathToLumOrLuh, sTHWId, sTHWPos, timeOutSecs=30.0, checkBefore=False):
        sCmd = "UPLOAD" + " " + sTHWId +  " " +  sTHWPos + " " + sPathToLumOrLuh + (" -V" if checkBefore else "")
        if self._handleCmd(sCmd, timeOutSecs):
            if self._responseContains("Incorrect File Type"):
                return False
            return True
        return False


    def mediaDownload(self, sPathToLnr, sTHWId, sTHWPos, timeOutSecs=30.0):
        sCmd = "MDOWNLOAD" + " " + sTHWId +  " " +  sTHWPos + " " + sPathToLnr
        if self._handleCmd(sCmd, timeOutSecs):
            return True
        return False


    def ethFind(self, sIpAddr, udpport, timeOutSecs=5):
        sCmd = "ETHFIND %s %u %u" % (sIpAddr, udpport, timeOutSecs)
        if self._handleCmd(sCmd, timeOutSecs + 0.5):
            if self._responseContains("Find Request Failed"):
                return False
            return True
        return False


    def fdxFind(self, sTHWId, sTHWPos, timeOutSecs=5):
        sCmd = "AFDXFIND" + " " + sTHWId +  " " +  sTHWPos + " %u"%(timeOutSecs) 
        if self._handleCmd(sCmd, timeOutSecs + 0.5):
            if self._responseContains("Find Request Failed"):
                return False
            return True
        return False

    def getLog(self):
        if self._handleCmd("GETLOG", 5.0):
            if self._responseContains("Found operation for Remote_IF_CMD"):
                return True
        return False

    def abort(self):
        if self._handleCmd("ABORT", 5.0):
            if self._responseContains("Found operation for Remote_IF_CMD"):
                return True
        return False





 
by

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling