Ver Mensaje Individual
  #8
Antiguo 10 de septiembre de 2025, 15:29
fastpho
El Foro es mi casa
Innovación: Por aportar innovaciones - Issue reason: SQLite + OO Cobol class Concurso: Primer puesto: Ganador/a del Primer puesto en un concurso - Issue reason: Acceso a datos Cobol vía web 
Última Actividad 21.08.2026 18:08
Posts Posts: 365
Likes enviados Enviados: 252
Likes recibidos Recibidos: 243

✅ *Interpolaridad de Python con PowerCobol*
ℹEjemplo de geolocalizacion usando la api de Nominatim
para procesar enviando direccion para obtener los datos
y genera un archivo .csv

Gracias a @@Jorgeanna,

Código COBOL:
  1.  ENVIRONMENT     DIVISION.
  2.  DATA            DIVISION.
  3.  WORKING-STORAGE SECTION.
  4.  01 ObjetoGenerico   pic x(21) value "LocPyCOM.elsCOMObject".
  5.  01 URLCom           object reference COM.
  6.  01 TextoDireccion   pic x(100).
  7.  01 ResultadoUrl     pic x(100).
  8.  
  9.  01 Numero           pic s9(9) comp-5.
  10.  
  11.  
  12.  *>Geolocalizacion
  13.  01 ResultadoGeol    pic x(100).
  14.  01 valorEstado      pic x(5).
  15.  01 valorLatitud.
  16.      03 v-Lat        pic x(15).
  17.  01 valorLongitud.
  18.      03 v-Lon        pic x(15).
  19.      
  20.  01 Tiempo           pic s9(9) comp-5.
  21.  01 Url              pic x(512).
  22.  01 url-maps         pic x(34) value "https://www.google.com/maps/place/".
  23.  01 returnvalue      pic s9(9) comp-5.
  24.  01 lang             pic x(3) value "esp".
  25.  PROCEDURE       DIVISION.
  26.     *> Objeto Creo
  27.      invoke COM "CREATE-OBJECT" using ObjetoGenerico returning URLCom. *> creo el objeto    
  28.      
  29.      if URLCom = NULL
  30.               display "ERROR: No se pudo crear objeto URLCom COM"
  31.               exit program
  32.      else
  33.               display "OK: se pudo crear objeto URLCom COM"    
  34.      end-if.
  35.    
  36.      *> Set Atributo numero cliente
  37.      move 530 to Numero.
  38.  
  39.      invoke URLCom "setValue" using Numero returning ResultadoUrl. *>Metodo.
  40. *     display ResultadoUrl.
  41.    
  42. *    *> Get Atributo numero cliente
  43.      move zeros to Numero.
  44.      invoke URLCom "getValue" returning Numero.
  45.      display "Retorno getValue:" , Numero.
  46.    
  47.      
  48.      *> Metodo Geola
  49.      move "Text" OF CmText-DIREC to TextoDireccion.
  50.      move spaces                 to ResultadoGeol.
  51.      invoke URLCom "CrearLocalizacion" using TextoDireccion returning ResultadoGeol. *>Metodo.
  52.      display "ResultadoGeol:" , ResultadoGeol.
  53.      unstring ResultadoGeol delimited by "|" into valorEstado valorLatitud  valorLongitud
  54.      end-unstring.
  55.  
  56. *    CALL "Sleep"        WITH STDCALL USING  BY VALUE Tiempo.    
  57.  
  58.      display "Estado:" , valorEstado.
  59.      display "LAtitud:" , v-Lat.
  60.      display "LOngitud:" , v-Lon.
  61.    
  62. *muestro valores
  63.      move valorLatitud  to "Text" OF CmText-Latitud.
  64.      
  65.      move valorLongitud to "Text" OF CmText-Longitud.
  66.      
  67.      move valorEstado   to "Text" OF CmText-ESTADO.
  68.  
  69.  
  70. *Muestra Maps
  71.  
  72.      string  
  73.          url-maps   delimited by spaces
  74.          
  75.          valorLatitud delimited by spaces
  76.          
  77.          ","           delimited by spaces
  78.          valorLongitud delimited by spaces
  79.          
  80.          into Url
  81.      end-string.
  82.      display Url.
  83.      MOVE Url TO "Text" OF CmText-URL.
  84.  
  85.  
  86. *Rutina OrdoWebView      
  87. *    INVOKE OrdoWebView1 "About".
  88.      MOVE POW-TRUE TO "Anchor" OF OrdoWebView1.
  89.      MOVE "https://www.google.com/" TO "HomeURL" OF OrdoWebView1.
  90.      MOVE Url TO "HomeURL" OF OrdoWebView1.
  91.    
  92.      *> Metodo url
  93.      move spaces                 to ResultadoUrl.
  94.      move Url                    to TextoDireccion.
  95.      invoke URLCom "url" using TextoDireccion returning ResultadoUrl. *>Metodo.
  96.  
  97.      
  98.      MOVE 2 to "SearchEngine" OF OrdoWebView1. *>Google.
  99.      INVOKE OrdoWebView1 "Init" USING Lang.
  100.      move 0 to "MousePointer" OF pow-self.  
  101.    
  102.  
  103. *final.
  104.      set URLCom to NULL.
  105.          
  106.      
  107.      

Código PYTHON:
  1. #Fecha 08-09-2025
  2. #Programa:elsisloc.py
  3. #para ejectuar ambiente desarrollo : python elsisloc.py --register o python elsisloc.py --unregister
  4.  
  5.  
  6. # Método 1: Eliminar claves del registro manualmente
  7. #reg delete "HKEY_CLASSES_ROOT\LocPyCOM.elsCOMObject" /f
  8. #reg delete "HKEY_CLASSES_ROOT\LocPyCOM.elsCOMObject.1" /f
  9. #reg delete "HKEY_CLASSES_ROOT\CLSID\{fc6bf508-392e-45e9-bd6e-44943fcb216f}" /f
  10.  
  11. import pythoncom
  12. import win32com.server.register
  13. from win32com.server.exception import COMException
  14. import ctypes
  15. import csv
  16. import os
  17. import sys
  18. import time
  19. from geopy.geocoders import Nominatim
  20.  
  21. # Configuración
  22. user_agent = "mi_aplicacion_geolocalizacion_v1"
  23. timeout = 10
  24. max_retries = 3
  25. retry_delay = 1
  26.  
  27. # Archivo de salida - usar ruta absoluta para evitar problemas con .exe
  28. if getattr(sys, 'frozen', False):
  29.     # Si estamos en un ejecutable PyInstaller
  30.     base_path = os.path.dirname(sys.executable)
  31. else:
  32.     # Si estamos ejecutando desde Python
  33.     base_path = os.path.dirname(os.path.abspath(__file__))
  34. output_file = os.path.join(base_path, "coordenadas.csv")
  35.  
  36. # Geolocalizador (mover a función para evitar problemas de inicialización)
  37. def get_geolocator():
  38.     return Nominatim(user_agent=user_agent, timeout=timeout)
  39.  
  40. class Controller:
  41.    
  42.    _public_methods_ = ['setValue', 'getValue','url','CrearLocalizacion']
  43.    _reg_progid_ = "LocPyCOM.elsCOMObject"
  44.    _reg_verprogid_ = "LocPyCOM.elsCOMObject.1"
  45.    _reg_desc_ = "Python Test COM Servicio"
  46.    _reg_class_spec_ = "elsisloc.Controller"  
  47.    _reg_clsid_ = "{fc6bf508-392e-45e9-bd6e-44943fcb216f}"
  48.  
  49.    def __init__(self):
  50.       """Constructor de la clase"""
  51.       print("Servidor COM correctamente")
  52.       self.value = 1
  53.       # Inicializar el archivo CSV
  54.       self.inicializar_archivo_csv()
  55.  
  56.  
  57.    def inicializar_archivo_csv(self):
  58.         """Inicializa el archivo CSV si no existe"""
  59.         try:
  60.             if not os.path.exists(output_file):
  61.                 with open(output_file, "w", newline="", encoding='utf-8') as csvfile:
  62.                     writer = csv.writer(csvfile)
  63.                     writer.writerow(["Cliente" , "Dirección", "Latitud", "Longitud", "Estado","Timestamp"])
  64.         except Exception as e:
  65.             print(f"Error al inicializar CSV: {str(e)}")
  66.  
  67.    def CrearLocalizacion(self, direccion):
  68.         """
  69.        Procesa una sola dirección y la geocodifica
  70.        Args:
  71.            direccion (str): La dirección a geocodificar
  72.        Returns:
  73.            str: Resultado del proceso o mensaje de error
  74.        """
  75.         try:
  76.             # Validar que se proporcione la dirección
  77.             if not direccion or direccion.strip() == "":
  78.                 return "ERROR: La dirección no puede estar vacía"
  79.            
  80.             direccion = direccion.strip()
  81.             print(f"Procesando dirección: {direccion}")
  82.            
  83.             latitud, longitud = self.geocodificar(direccion)
  84.            
  85.             if latitud and longitud:
  86.                 resultado = f"Dirección: {direccion}, Latitud: {latitud}, Longitud: {longitud}"
  87.                 print(resultado)
  88.                 self.guardar_resultado(direccion, latitud, longitud, "OK")
  89.                 return f"OK|{latitud}|{longitud}"
  90.             else:
  91.                 error_msg = f"Error al geocodificar la dirección: {direccion}"
  92.                 print(error_msg)
  93.                 self.guardar_resultado(direccion, "", "", "ERROR")
  94.                 return f"ERROR|No se pudo geocodificar la dirección"
  95.            
  96.         except Exception as e:
  97.             error_msg = f"ERROR: {str(e)}"
  98.             print(error_msg)
  99.             return error_msg            
  100.    def geocodificar(self, direccion):
  101.         """
  102.        Geocodifica una dirección con reintentos
  103.        """
  104.         geolocator = get_geolocator()
  105.        
  106.         for attempt in range(max_retries):
  107.             try:
  108.                 print(f"Intento {attempt + 1} para: {direccion}")
  109.                 location = geolocator.geocode(direccion)
  110.                
  111.                 if location:
  112.                     return location.latitude, location.longitude
  113.                 else:
  114.                     print(f"No se encontraron resultados para: {direccion}")
  115.                     return None, None
  116.                    
  117.             except Exception as e:
  118.                 print(f"Error en intento {attempt + 1}: {str(e)}")
  119.                 if attempt < max_retries - 1:
  120.                     time.sleep(retry_delay * (attempt + 1))  # Aumentar delay progresivamente
  121.                 else:
  122.                     print(f"Falló después de {max_retries} intentos")
  123.                     return None, None
  124.  
  125.    def guardar_resultado(self, direccion, latitud, longitud, estado):
  126.         """
  127.        Guarda el resultado en el archivo CSV
  128.        """
  129.         try:
  130.             with open(output_file, "a", newline="", encoding='utf-8') as csvfile:
  131.                 writer = csv.writer(csvfile)
  132.                 timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
  133.                 nrocliente = self.value
  134.                 writer.writerow([nrocliente,direccion, latitud, longitud, estado, timestamp])
  135.         except Exception as e:
  136.             print(f"Error al guardar en CSV: {str(e)}")
  137.  
  138.    def setValue(self, new_value):
  139.       """
  140.      Set Numero del cliente
  141.      """
  142.       try:
  143.          self.value = new_value
  144.          return
  145.       except Exception as e:
  146.          raise COMException(f"Error en el valor enviado: {str(e)}")
  147.  
  148.    def getValue(self):
  149.       """
  150.      Get Numero del cliente
  151.      """
  152.       try:
  153.          return self.value if self.value is not None else "Value not set"
  154.       except Exception as e:
  155.          raise COMException(f"Error al obtener valor: {str(e)}")
  156.      
  157.    def url(self, Texto):
  158.       try:
  159.          import webbrowser
  160.          webbrowser.open(Texto)
  161.          return Texto
  162.      
  163.       except Exception as e:
  164.          raise COMException(f"Error navegador: {str(e)}")      
  165.  
  166. def show_message(message, title="Informacion"):
  167.    ctypes.windll.user32.MessageBoxW(0, message, title, 0x40)
  168.  
  169. def DllRegisterServer(silent=False):
  170.    try:
  171.       pythoncom.CoInitialize()
  172.       win32com.server.register.UseCommandLine(Controller)
  173.       message = "Objeto registrado exitosamente."
  174.    except Exception as e:
  175.       message = f"Error al registrar el objeto: {e}"
  176.    finally:
  177.       pythoncom.CoUninitialize()
  178.    if not silent:
  179.       show_message(message, "Objeto registrado")
  180.  
  181. def DllUnregisterServer(silent=False):
  182.    try:
  183.       pythoncom.CoInitialize()
  184.       win32com.server.register.UnregisterServer(
  185.          Controller._reg_clsid_,
  186.          Controller._reg_progid_
  187.       )
  188.       message = "Objeto anulado exitosamente."
  189.    except Exception as e:
  190.       message = f"Error al anular el registro del objeto: {e}"
  191.    finally:
  192.       pythoncom.CoUninitialize()
  193.    if not silent:
  194.       show_message(message, "Objeto no registrado")
  195.  
  196. if __name__ == '__main__':
  197.    import sys
  198.    silent = False
  199.    if len(sys.argv) > 1:
  200.       if len(sys.argv) > 2:  
  201.          if sys.argv[2] == '--silent':
  202.             silent = True
  203.       if sys.argv[1] == '--register':
  204.          DllRegisterServer(silent)
  205.       elif sys.argv[1] == '--unregister':
  206.          DllUnregisterServer(silent)
  207.       elif "/Automate" in sys.argv:
  208.          import win32com.server.localserver
  209.          win32com.server.localserver.serve([Controller._reg_clsid_])
  210.    else:
  211.          show_message("Use:\nelsisloc.exe --register\nelsisloc.exe --unregister\n--silent: Silent mode", "Ayuda")
Saludos ...
Imágenes Adjuntas
 
fastpho is offline   Responder Con Cita