Ejemplo n.º 1
0
 def __init__(self):
     self.media = None
     self.trace = TraceLevel.INFO
     self.iec = False
     self.client = GXDLMSSecureClient(True)
     #  Objects to read.
     self.readObjects = []
Ejemplo n.º 2
0
 def __init__(self) -> None:
     super().__init__()
     self.notify = GXReplyData()
     self.client = GXDLMSSecureClient()
     self.client.interfaceType = InterfaceType.PDU
     self.client.ciphering.security = Security.ENCRYPTION
     self.client.ciphering.blockCipherKey = GXCommon.hexToBytes(key_hex)
     self.translator = GXDLMSTranslator()
     self.reply = GXByteBuffer()
 def __init__(self):
     self.media = None
     self.trace = TraceLevel.INFO
     self.iec = False
     self.invocationCounter = None
     self.client = GXDLMSSecureClient(True)
     #  Objects to read.
     self.readObjects = []
     self.outputFile = None
Ejemplo n.º 4
0
 def __init__(self):
     self.media = None
     self.trace = TraceLevel.INFO
     self.client = GXDLMSSecureClient(True)
Ejemplo n.º 5
0
class MediaListener(IGXMediaListener):
    def __init__(self) -> None:
        super().__init__()
        self.notify = GXReplyData()
        self.client = GXDLMSSecureClient()
        self.client.interfaceType = InterfaceType.PDU
        self.client.ciphering.security = Security.ENCRYPTION
        self.client.ciphering.blockCipherKey = GXCommon.hexToBytes(key_hex)
        self.translator = GXDLMSTranslator()
        self.reply = GXByteBuffer()

    def onError(self, sender, ex):
        """
        Represents the method that will handle the error event of a Gurux
        component.
        sender :  The source of the event.
        ex : An Exception object that contains the event data.
        """
        print("Error has occured. " + str(ex))

    def onMediaStateChange(self, sender, e):
        """Media component sends notification, when its state changes.
        sender : The source of the event.
        e : Event arguments.
        """
        print("Media state changed. " + str(e))

    def onTrace(self, sender, e):
        """Called when the Media is sending or receiving data.
        sender : The source of the event.
        e : Event arguments.
        """
        print("trace:" + str(e))

    def onPropertyChanged(self, sender, e):
        """
        Event is raised when a property is changed on a component.
        sender : The source of the event.
        e : Event arguments.
        """
        print("Property {!r} has hanged.".format(str(e)))

    def onReceived(self, sender, e: ReceiveEventArgs):
        self.reply.set(e.data)
        data = GXReplyData()
        try:
            if not self.client.getData(self.reply, data, self.notify):
                self.reply.clear()
                #If all data is received.
                if self.notify.complete:
                    if not self.notify.isMoreData():
                        #Show received data as XML.
                        xml = self.translator.dataToXml(self.notify.data)
                        print(xml)
                        #Print received data.
                        self.printData(self.notify.value, 0)

                        #Example is sending list of push messages in first parameter.
                        if isinstance(self.notify.value, list):
                            objects = self.client.parsePushObjects(
                                self.notify.value[0])
                            #Remove first item because it's not needed anymore.
                            objects.pop(0)
                            Valueindex = 1
                            for obj, index in objects:
                                self.client.updateValue(
                                    obj, index, self.notify.value[Valueindex])
                                Valueindex += 1
                                #Print value
                                print(
                                    str(obj.objectType) + " " +
                                    obj.logicalName + " " + str(index) + ": " +
                                    str(obj.getValues()[index - 1]))
                        self.notify.clear()
                        self.reply.clear()
        except Exception as ex:
            print(ex)
            self.notify.clear()
            self.reply.clear()

    @classmethod
    def printData(cls, value, offset):
        sb = ' ' * 2 * offset
        if isinstance(value, list):
            print(sb + "{")
            offset = offset + 1
            #Print received data.
            for it in value:
                cls.printData(it, offset)
            print(sb + "}")
            offset = offset - 1
        elif isinstance(value, bytearray):
            #Print value.
            print(sb + GXCommon.toHex(value))
        else:
            #Print value.
            print(sb + str(value))
Ejemplo n.º 6
0
class GXSettings:
    #
    # Constructor.
    #
    def __init__(self):
        self.media = None
        self.trace = TraceLevel.INFO
        self.iec = False
        self.client = GXDLMSSecureClient(True)
        #  Objects to read.
        self.readObjects = []

    #
    # Show help.
    #
    @classmethod
    def showHelp(self):
        print("GuruxDlmsSample reads data from the DLMS/COSEM device.")
        print(
            "GuruxDlmsSample -h [Meter IP Address] -p [Meter Port No] -c 16 -s 1 -r SN"
        )
        print(" -h \t host name or IP address.")
        print(" -p \t port number or name (Example: 1000).")
        print(" -S \t serial port.")
        print(" -i IEC is a start protocol.")
        print(" -a \t Authentication (None, Low, High).")
        print(" -P \t Password for authentication.")
        print(" -c \t Client address. (Default: 16)")
        print(" -s \t Server address. (Default: 1)")
        print(" -n \t Server address as serial number.")
        print(
            " -r [sn, sn]\t Short name or Logican Name (default) referencing is used."
        )
        print(" -w WRAPPER profile is used. HDLC is default.")
        print(" -t [Error, Warning, Info, Verbose] Trace messages.")
        print(
            " -g \"0.0.1.0.0.255:1; 0.0.1.0.0.255:2\" Get selected object(s) with given attribute index."
        )
        print("Example:")
        print("Read LG device using TCP/IP connection.")
        print(
            "GuruxDlmsSample -r SN -c 16 -s 1 -h [Meter IP Address] -p [Meter Port No]"
        )
        print("Read LG device using serial port connection.")
        print("GuruxDlmsSample -r SN -c 16 -s 1 -sp COM1 -i")
        print("Read Indian device using serial port connection.")
        print("GuruxDlmsSample -S COM1 -c 16 -s 1 -a Low -P [password]")

    # Returns command line parameters.
    #
    # @param args
    #            Command line parameters.
    # @param optstring
    #            Expected option tags.
    # @return List of command line parameters
    #
    @classmethod
    def __getParameters(self, args, optstring):
        list_ = list()
        skipNext = False
        for index in range(1, len(args)):
            if skipNext:
                skipNext = False
            else:
                if args[index][0] != '-' and args[index][0] != '/':
                    raise ValueError("Invalid parameter: " + args[index])

                pos = optstring.index(args[index][1])
                if pos == -1:
                    raise ValueError("Invalid parameter: " + args[index])

                c = GXCmdParameter()
                c.tag = args[index][1]
                list_.append(c)
                if pos < len(optstring) - 1 and optstring[1 + pos] == ':':
                    skipNext = True
                    if len(args) <= index:
                        c.missing(True)
                    c.value = args[1 + index]
        return list_

    def getParameters(self, args):
        parameters = GXSettings.__getParameters(args, "h:p:c:s:r:it:a:p:wP:g:")
        hostName = None
        port = 0
        for it in parameters:
            if it.tag == 'w':
                self.client.setInterfaceType(InterfaceType.WRAPPER)
            elif it.tag == 'r':
                if it.value == "sn":
                    self.client.setUseLogicalNameReferencing(False)
                elif it.value == "ln":
                    self.client.setUseLogicalNameReferencing(True)
                else:
                    raise ValueError("Invalid reference option.")
            elif it.tag == 'h':
                #  Host address.
                hostName = it.value
            elif it.tag == 't':
                #  Trace.
                self.trace = TraceLevel[it.value.upper()]
            elif it.tag == 'p':
                #  Port.
                port = int(it.value)
            elif it.tag == 'P':
                #  Password
                self.client.password = it.value
            elif it.tag == 'i':
                #  IEC.
                self.iec = True
            elif it.tag == 'g':
                #  Get (read) selected objects.
                for o in it.value.split(";,"):
                    tmp = o.split(":")
                    if len(tmp):
                        raise ValueError(
                            "Invalid Logical name or attribute index.")
                    self.readObjects.append(
                        (tmp[0].strip(), int(tmp[1].strip())))
            elif it.tag == 'S':
                self.media = serial.Serial(it.value)
            elif it.tag == 'a':
                try:
                    it.value = it.value.upper()
                    if it.value.startswith("HIGH"):
                        it.value = "HIGH_" + it.value[4:]
                    self.client.authentication = Authentication[it.value]
                except Exception as e:
                    #raise ValueError("Invalid Authentication option: '" + it.value + "'. (None, Low, High, HighMd5, HighSha1, HighGmac, HighSha256)")
                    raise ValueError("Invalid Authentication option: '" +
                                     it.value + "'. (None, Low, HighGmac)")
            elif it.tag == 'o':
                pass
            elif it.tag == 'c':
                self.client.clientAddress = int(it.value)
            elif it.tag == 's':
                self.client.serverAddress = int(it.value)
            elif it.tag == '?':
                if it.tag == 'c':
                    raise ValueError("Missing mandatory client option.")
                elif it.tag == 's':
                    raise ValueError("Missing mandatory server option.")
                elif it.tag == 'h':
                    raise ValueError("Missing mandatory host name option.")
                elif it.tag == 'p':
                    raise ValueError("Missing mandatory port option.")
                elif it.tag == 'r':
                    raise ValueError("Missing mandatory reference option.")
                elif it.tag == 'a':
                    raise ValueError(
                        "Missing mandatory authentication option.")
                elif it.tag == 'S':
                    raise ValueError("Missing mandatory Serial port option.\n")
                elif it.tag == 't':
                    raise ValueError("Missing mandatory trace option.\n")
                else:
                    self.showHelp()
                    return 1
            else:
                self.showHelp()
                return 1

        if hostName != None and port != 0:
            self.media = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_address = (hostName, port)
            self.media.connect(server_address)

        if self.media == None:
            GXSettings.showHelp()
            return 1
        return 0
Ejemplo n.º 7
0
class GXSettings:
    #
    # Constructor.
    #
    def __init__(self):
        self.media = None
        self.trace =   TraceLevel.OFF    #TraceLevel.INFO
        self.iec = False
        self.client = GXDLMSSecureClient(True)
        #  Objects to read.
        self.readObjects = []

    #
    # Show help.
    #
    @classmethod
    def showHelp(cls):
        print("GuruxDlmsSample reads data from the DLMS/COSEM device.")
        print("GuruxDlmsSample -h [Meter IP Address] -p [Meter Port No] -c 16 -s 1 -r SN")
        print(" -h \t host name or IP address.")
        print(" -p \t port number or name (Example: 1000).")
        print(" -S \t serial port.")
        print(" -i IEC is a start protocol.")
        print(" -a \t Authentication (None, Low, High).")
        print(" -P \t Password for authentication.")
        print(" -c \t Client address. (Default: 16)")
        print(" -s \t Server address. (Default: 1)")
        print(" -n \t Server address as serial number.")
        print(" -r [sn, sn]\t Short name or Logican Name (default) referencing is used.")
        print(" -w WRAPPER profile is used. HDLC is default.")
        print(" -t [Error, Warning, Info, Verbose] Trace messages.")
        print(" -g \"0.0.1.0.0.255:1; 0.0.1.0.0.255:2\" Get selected object(s) with given attribute index.")
        print("Example:")
        print("Read LG device using TCP/IP connection.")
        print("GuruxDlmsSample -r SN -c 16 -s 1 -h [Meter IP Address] -p [Meter Port No]")
        print("Read LG device using serial port connection.")
        print("GuruxDlmsSample -r SN -c 16 -s 1 -sp COM1 -i")
        print("Read Indian device using serial port connection.")
        print("GuruxDlmsSample -S COM1 -c 16 -s 1 -a Low -P [password]")
        print("------------------------------------------------------")
        print("Available serial ports:")
        print(GXSerial.getPortNames())

    # Returns command line parameters.
    #
    # @param args
    #            Command line parameters.
    # @param optstring
    #            Expected option tags.
    # @return List of command line parameters
    #
    @classmethod
    def __getParameters(cls, args, optstring):
        list_ = list()
        skipNext = False
        for index in range(1, len(args)):
            if skipNext:
                skipNext = False
            else:
                if args[index][0] != '-' and args[index][0] != '/':
                    raise ValueError("Invalid parameter: " + args[index])

                pos = optstring.index(args[index][1])
                if pos == - 1:
                    raise ValueError("Invalid parameter: " + args[index])

                c = GXCmdParameter()
                c.tag = args[index][1]
                list_.append(c)
                if pos < len(optstring) - 1 and optstring[1 + pos] == ':':
                    skipNext = True
                    if len(args) <= index:
                        c.missing = True
                    c.value = args[1 + index]
        return list_


    def getParameters(self, args):
        parameters = GXSettings.__getParameters(args, "h:p:c:s:r:it:a:p:wP:g:S:")
        for it in parameters:
            if it.tag == 'w':
                self.client.interfaceType = InterfaceType.WRAPPER
            
            #ln/sn reference config
            elif it.tag == 'r':
                if it.value == "sn":
                    self.client.useLogicalNameReferencing = False
                elif it.value == "ln":
                    self.client.useLogicalNameReferencing = True
                else:
                    raise ValueError("Invalid reference option.")
            
            #Tcp/ip host address
            elif it.tag == 'h':
                #  Host address.
                if not self.media:
                    self.media = GXNet(NetworkType.TCP, it.value, 0)
                else:
                    self.media.hostName = it.value
            
            #Debug/Trace config
            elif it.tag == 't':
                #  Trace.
                if it.value == "Off":
                    self.trace = TraceLevel.OFF
                elif it.value == "Error":
                    self.trace = TraceLevel.ERROR
                elif it.value == "Warning":
                    self.trace = TraceLevel.WARNING
                elif it.value == "Info":
                    self.trace = TraceLevel.INFO
                elif it.value == "Verbose":
                    self.trace = TraceLevel.VERBOSE
                else:
                    raise ValueError("Invalid trace level(Off, Error, Warning, Info, Verbose).")
            
            #network port config
            elif it.tag == 'p':
                #  Port.
                if not self.media:
                    self.media = GXNet(NetworkType.TCP, None, int(it.value))
                else:
                    self.media.port = int(it.value)
            
            #low authentication password config
            elif it.tag == 'P':
                #  Password
                self.client.password = it.value
            
            #IEC/dlms config
            elif it.tag == 'i':
                #  IEC.
                self.iec = True

            #selected object config
            elif it.tag == 'g':
                #  Get (read) selected objects.
                for o in it.value.split(";,"):
                    tmp = o.split(":")
                    if len(tmp) != 2:
                        raise ValueError("Invalid Logical name or attribute index.")
                    self.readObjects.append((tmp[0].strip(), int(tmp[1].strip())))
                    print("read objects: " + str(self.readObjects))
            
            #serial port config
            elif it.tag == 'S':     #Serial Port
                #self.media = GXSerial(port='/dev/ttyUSB0')
                self.media = GXSerial(None)
                tmp = it.value.split(':')
                self.media.port = tmp[0]
                if len(tmp) > 1:
                    self.media.baudRate = int(tmp[1])
                    self.media.dataBits = int(tmp[2][0: 1])
                    self.media.parity = Parity(tmp[2][1: len(tmp[2]) - 2] .Substring(1, tmp[2].Length - 2))
                    self.media.stopBits = int(tmp[2][len(tmp[2]) - 1:])
            
            #authentication type config 
            elif it.tag == 'a':
                try:
                    it.value = it.value.upper()
                    print ("it.value: " + str(it.value))
                    if it.value.startswith("HIGH"):
                        it.value = "HIGH_" + it.value[4:]

    
                    self.client.authentication = Authentication[it.value]
                except Exception:
                    #raise ValueError("Invalid Authentication option: '" +
                    #it.value + "'.  (None, Low, High, HighMd5, HighSha1,
                    #HighGmac, HighSha256)")
                    raise ValueError("Invalid Authentication option: '" + it.value + "'. (None, Low, HighGmac)")
            
            elif it.tag == 'o':
                pass
            
            #client address config 
            elif it.tag == 'c':
                self.client.clientAddress = int(it.value)
            
            #server address config
            elif it.tag == 's':
                self.client.serverAddress = int(it.value)
            
            #help 
            elif it.tag == '?':
                if it.tag == 'c':
                    raise ValueError("Missing mandatory client option.")
                if it.tag == 's':
                    raise ValueError("Missing mandatory server option.")
                if it.tag == 'h':
                    raise ValueError("Missing mandatory host name option.")
                if it.tag == 'p':
                    raise ValueError("Missing mandatory port option.")
                if it.tag == 'r':
                    raise ValueError("Missing mandatory reference option.")
                if it.tag == 'a':
                    raise ValueError("Missing mandatory authentication option.")
                if it.tag == 'S':
                    raise ValueError("Missing mandatory Serial port option.\n")
                if it.tag == 't':
                    raise ValueError("Missing mandatory trace option.\n")
                self.showHelp()
                return 1
            
            else:
                self.showHelp()
                return 1

        if not self.media:
            GXSettings.showHelp()
            return 1
        return 0


    def get_fixed_config_parameters(self):     
        #ln/sn reference config
        self.client.useLogicalNameReferencing = True

        #Debug/Trace config
        self.trace = TraceLevel.OFF    #TraceLevel.INFO
            
        #low authentication password config
        self.client.password = "******"
            
        #IEC config
        self.iec = False
            
        #serial port config
        self.media = GXSerial(None)
        self.media.port = '/dev/ttyUSB0'
        self.media.baudrate = BaudRate.BAUD_RATE_9600
        self.media.bytesize = 8
        self.media.parity = Parity.NONE
        self.media.stopbits = StopBits.ONE

        #authentication type config 
        self.client.authentication = Authentication.LOW
                
        #client address config 
        self.client.clientAddress = 32
            
        #server address config
        self.client.serverAddress = self.client.getServerAddress2(1, 0x10, 2)

        if not self.media:
            GXSettings.showHelp()
            return 1
        return 0

    def get_dynamic_config_parameters(self, physicalAdd):     
        #ln/sn reference config
        self.client.useLogicalNameReferencing = True

        #Debug/Trace config
        self.trace = TraceLevel.INFO    #TraceLevel.INFO
            
        #low authentication password config
        self.client.password = "******"
            
        #IEC config
        self.iec = False
            
        #serial port config
        self.media = GXSerial(None)
        self.media.port = '/dev/ttyUSB0'
        self.media.baudrate = BaudRate.BAUD_RATE_9600
        self.media.bytesize = 8
        # self.media.parity = Parity.EVEN
        self.media.parity = Parity.NONE
        self.media.stopbits = StopBits.ONE

        #authentication type config 
        self.client.authentication = Authentication.NONE
                
        #client address config 
        self.client.clientAddress = 16
            
        #server address config
        self.client.serverAddress = self.client.getServerAddress2(1, physicalAdd, 4)

        if not self.media:
            GXSettings.showHelp()
            return 1
        return 0