gisce / iec870ree

IEC-870-5-102 for REE Spanish Electric meters
GNU Affero General Public License v3.0
13 stars 11 forks source link

USB to IR connect #31

Open javiergentoo opened 2 years ago

javiergentoo commented 2 years ago

Hello

I would like to connect directly to the meters with a USB to Infrared conector. Could somebody help me, how use theses examples for this kind of connection ?

Thanks Javier

javiergentoo commented 2 years ago

Hello How I can use it conecting without modem, directly to the USB ?

ecarreras commented 2 years ago

Hello @javiergentoo I think it's possible but we have to implement a new PhysicalLayer as we implemented Modem and Ip, at this moment we don't have implemented this layer because we only use this protocol in server side.

But if you want to implement this we can help you and you can make a pull-request 💪🏻

javiergentoo commented 2 years ago

Hello Eduard Thanks for your reply, I will try to do it,

IgnacioHR commented 2 years ago

I’m interested on this too. I’ve installed at home one SAGEM CX2000-9 and I purchased a KMK116 for reading it from the infrared connector. Reading the documentation of the SAGEM CX2000 I first tried using IEC62056-21 but I receive no response from the meter. I learn later that in Spain the meters use IEC870-5-102 so that might explain why I’ve been unable to read the meter. So I’m planning to implement a new PhysicalLayer for the serial device (it looks trivial to do) but I feel a bit insecure moving forward because my lack of knowledge and lack of available documentation from the meter. In other words, if the meter is implementing IEC870-5-102 on the optical connection that is nowhere documented in the product documentation. I’ll be happy to hear from other who already success in using the optical connection about how to do it. Also I’ll share my progress here if you don’t disagree.

IgnacioHR commented 2 years ago

Well, I’ve finished my test and the implementation of a serial physical layer (very simple) and I’ve had no success in using it. Here is what I’m doing:

(venv) ihr@electra:~/iec870ree $ python examples/serial_cliente.py -d 1 -p 1 -c 0
INFO:root:Started /dev/ttyUSB0 1 1 0
INFO:iec870ree.serial:try open port 0
INFO:iec870ree.serial:serial port /dev/ttyUSB0 opened
INFO:iec870ree.serial:read thread Starting
INFO:iec870ree:sending frame
 ----- FixedAsdu Begin -----
 RES: 0 PRM: 1 FCB: 0 FCV: 0 CF(cod. funcion): 9
 DER: 1
 checksum: 74 0x4a
 10:49:01:00:4a:16
----- FixedAsdu End -----
INFO:root:->10:49:01:00:4a:16
INFO:iec870ree:receiving frame
Traceback (most recent call last):
  File "/home/ihr/iec870ree/examples/serial_cliente.py", line 68, in <module>
    run_example(port, der, dir_pm, clave_pm)
  File "/home/ihr/iec870ree/examples/serial_cliente.py", line 25, in run_example
    link_layer.link_state_request()
  File "/home/ihr/iec870ree/examples/../iec870ree/protocol.py", line 443, in link_state_request
    raise ProtocolException("Link state request didn't get response")
iec870ree.protocol.ProtocolException: Protocol Exception: Link state request didn't get response

As you can see I receive nothing. I don’t know why. It looks like the meter is not working? or it has the optical port blocked? my distributor is UFD and they do not respond to my questions so I don’t know how to move forward. In any case I’ve made a pull request for anyone to test my code or help me determine what’s going on.

tinogis commented 1 year ago

A SAGEM CX2000-9 meter is a PRIME meter. This technology meters usually does not implements iec-870-ree protocol. It uses DLMS/COSEM protocol.

IgnacioHR commented 1 year ago

@tinogis Thank you for your response! I'm unable to read the meter either using iec-870-ree or iec62056-21 that is required to start using DLMS/COSEM. I think the problem is the meter is, somehow, manipulated from the distribution company and the port is unreadable for users. I think this is not legal but you now in Spain nobody stick to the laws! Let me even develop further this point:

Looking at the Spanish laws: (sorry for the text in Spanish)

El punto 5 del ART 43 de la Ley 24/2013, de 26 de diciembre, del Sector Eléctrico establece que las controversias entre particulares y proveedores de suministro eléctrico deben enviarse al Ministerio de Industria, Energía y Turismo.

I asked the Minister about how to execute that controversy and here is the response:

Buenas tardes. En contestación a su consulta procede señalar, en relación con la presentación de controversia de acuerdo con lo recogido en el art. 43.5 de la Ley 24/2013, de 26 de diciembre, que esa disposición no resulta de aplicación debido a que el procedimiento para su tramitación, al que se refiere el párrafo segundo de ese mismo artículo, aún no ha sido aprobado.

WOW. the Law was published in 2013 and it is almost 10 years since them!

sergioitig commented 10 months ago

@IgnacioHR hola, me interesa hacer la conexión directamente por serial en local, sin tener que hacer capa de transporte ni por IP ni por modem, es posible puedas publicar el script examples/serial_cliente.py, para poder testearlo yo a ver si puedo hacer conexión. En cuanto a la conexión mediante el puerto óptico que has mencionado anteriormente, solo cumplen los fabricantes con el protocolo IEC62056-21 a nivel de hard pero no implementan el protocolo a nivel de soft, por lo que te puedes volver loco aplicando las peticiones OBIS que no responden nada, para eso este puerto es posible mandarle las tramas del protocolo IEC870-5-102 y utilizarlo.

muchas gracias de antemano

IgnacioHR commented 10 months ago

@sergioitig Te acabo de enviar el script por mail. Espero que te sirva y que podamos avanzar en este tema.

Saludos Ignacio

javiergentoo commented 10 months ago

Hola @IgnacioHR podría disponer del script para probarlo ? Muchas Gracias

IgnacioHR commented 10 months ago

Lo comparto por aquí. No es nada del otro mundo.

import sys
import logging
from os.path import dirname, realpath, sep, pardir
library_path = dirname(realpath(__file__)) + sep + pardir
sys.path.append(library_path)

import getopt
import logging
import iec870ree
import iec870ree.serial
import iec870ree.protocol
import datetime

def run_example(port, baudrate, der, dir_pm, clave_pm):
    end_date = datetime.datetime.now()
    start_date = end_date - datetime.timedelta(days = 2)

    physical_layer = iec870ree.serial.Serial(port, baudrate)
    link_layer = iec870ree.protocol.LinkLayer(der, dir_pm)
    link_layer.initialize(physical_layer)
    app_layer = iec870ree.protocol.AppLayer()
    app_layer.initialize(link_layer)

    physical_layer.connect()
    link_layer.link_state_request()
    link_layer.remote_link_reposition()
    logging.info("before authentication")
    resp = app_layer.authenticate(clave_pm)
    logging.info("CLIENTE authenticate response {}".format(resp))
    logging.info("before read")
    for resp in app_layer.read_integrated_totals(start_date, end_date):
        logging.info("read response {}".format(resp))
    app_layer.finish_session()
    physical_layer.disconnect()

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)

    argv = sys.argv[1:]
    try:
        argv = sys.argv[1:]
        opts, args = getopt.getopt(argv,"t:d:p:c:b:",
                                   ["port=", "der=", "dir_pm=",
                                   "clave_pm=","baudrate="])
    except getopt.GetoptError:
       logging.error('wrong command')
       sys.exit(2)

    port = "/dev/ttyUSB0"
    der = None
    dir_pm = None
    clave_pm = None
    baidrate = 9600
    for opt, arg in opts:
        if opt == '-h':
          logging.error("help not implemented")
          sys.exit()
        elif opt in ("-t", "--port"):
          port = arg
        elif opt in ("-d", "--der"):
          der = int(arg)
        elif opt in ("-p", "--dir_pm"):
          dir_pm = int(arg)
        elif opt in ("-c", "--clave_pm"):
          clave_pm = int(arg)
        elif opt in ("-b", "--baudrate"):
          baudrate = int(arg)

    logging.info('Started {} {} {} {} {}'.format(port, baudrate, der, dir_pm,
                                                 clave_pm))
    run_example(port, baudrate, der, dir_pm, clave_pm)

E insisto en que no he conseguido ver ninguna respuesta en mi contador. No obstante estoy atento por si puedo servir de alguna ayuda.

sergioitig commented 10 months ago

Hola os cuento cosas

Tengo el siguiente contador con este medido óptico

IMG_20231127_104147_387

Porque con otros dos que tengo, envía la trama, pero no recibe,

IMG_20231127_104159_718 IMG_20231127_104209_981

Puede que la conexión en los conversores los tenga mal, pero no funcionan el primero de ORBIS si funciona

El script abre el puerto serial, ahora estoy en win con el COM3, pero lo he probado con raspberrypi en un ttyUSB01 y también conecta bien

Me ha dado un error en el método read_integrated_totals, porque no está definido en el protocolo que tengo yo y he puesto otro método el de ext_read_instant_values y funciona perfectamente, no he tocado nada de tu script salvo lo parámetros, que por cierto no se pasarlos por consola, los he de poner directamente en el código, y he hecho un bucle infinito y me devuelve todo bien, pero al final me sale un error cuando llama a physical_layer.disconnect() lo pongo en captura, sabeis que puede ser? aaa

Si necesitáis mas info de lo que he hecho me decís Gracias

javiergentoo commented 10 months ago

Hola @IgnacioHR muchisimas gracias. Hoy no podre pero cuando saque un tiempo lo pruebo y a ver que puedo aportar

IgnacioHR commented 10 months ago

@sergioitig Gran aporte! Yo tengo dos sondas ópticas, una de KMK y la otra es china (sin marca concreta). La de KMK me costó más de 100€ y pensé que debía funcionar pero por lo que cuentas tú, ya somos dos a los que no nos funciona.

Por lo que dices, el lector de ORBIS sí funciona y es el que se necesita para poder avanzar. Voy a enviar un correo a orbis para preguntar por el lector porque no lo veo en su página web a ver si puedo hacerme con uno.

Respecto al problema que comentar en "read_port" no tengo claro a qué podría ser debido. Hay que depurar el script pero suena a problema de comunicaciones.

IgnacioHR commented 10 months ago

@javiergentoo cuéntanos qué sonda óptica tienes a ver si encontramos más de una que funcione.

javiergentoo commented 10 months ago

Buenas, tengo una que compre en Circutor y tengo que buscarla, ya que ayer no la encontre para empezar a hacer las pruebas, ya os contare cuando la encuentre. :(

javiergentoo commented 10 months ago

Buenas Estoy haciendo las pruebas, pero no encuentra el modulo serial: "import iec870ree.serial ModuleNotFoundError: No module named 'iec870ree.serial' Esta todo instalado "pip install iec870ree" Me falta algo por instalar ? Saludos Javier

IgnacioHR commented 10 months ago

Los archivos están en un pull request que hice en este proyecto. Te paso una URL para que investigues desde ahí:

https://github.com/gisce/iec870ree/pull/38/files

javiergentoo commented 10 months ago

Gracias @IgnacioHR

apanazo commented 10 months ago

Hola. Tengo cierta experiencia en la lectura de contadores, casi siempre desde aplicaciones comerciales, os comento los problemas que he tenido habitualmente, por si sirve de ayuda a alguien: (hay que decir que casi siempre mis lecturas son directas por puerto serie, o a través de un conversor ethernet-serial atacando el puerto serie del contador)

apanazo commented 10 months ago

Buenas, he podido hacer unas pruebas por el puerto infrarrojo con el modulo serial y el script de @IgnacioHR . Al principio no recibía respuesta, recordé que en el contador que estaba la parametrización de las comunicaciones es 9600 8 E 1, así que tuve que forzar en serial.py a la paridad par, añadiendo "parity=serial.PARITY_EVEN" en la línea 41, quedando: self.sport = serial.Serial(self.serial_port, baudrate=9600, timeout=1, parity=serial.PARITY_EVEN) Con esto conseguí conectar y recibir respuestas, recibiendo al final el mismo error que @sergioitig . Esto creo que lo he corregido, modificando el serial.py, en el método read_port, en la línea 89, cambiando el "continue" existente por "break", quedando: if not response: break Espero haberme explicado, y que os funcione.

Como información, para estas pruebas he utilizado un lector IR tipo Circutor Cirwatt Q30301, con conexion serie RS232, y conectado a un conversor USB-serie.

Saludos

sergioitig commented 7 months ago

@apanazo gracias por tu aporte para la corrección del error que me aparece como a ti, lo aplicaré para corregirlo