FTPClient, se conecta a un servidor FTP

Lista

Esta página es parte del Manual de programación IEC 61131-3. Ir al índice.

Este bloque de funciones de ejecutar en tarea Atrás, permite gestionar la conexión al servidor FTP definido en FTPServer con nombre de usuario definido en User y contraseña definida en Password.

activando Store el archivo local definido en LocalFile se transfiere al servidor FTP con el nombre indicado en RemoteFile, una vez finalizada la transferencia, se activa la salida Done que permanece activo hasta que se deshabilita el comando.

activando Retrieve el archivo en el servidor FTP con el nombre indicado en RemoteFile se transfiere localmente con el nombre definido en LocalFile, una vez finalizada la transferencia, se activa la salida Done que permanece activo hasta que se deshabilita el comando.

activando Delete el archivo en el servidor FTP con el nombre indicado en RemoteFile se borra y la salida se activa Done que permanece activo hasta que se deshabilita el comando.

En caso de error, la ejecución del comando finaliza y la salida se activa para un bucle Fault y la salida se activa Done que permanece activo hasta que se deshabilita el comando.

Lista de actualización

FTPClient_v4

Parámetro eliminado Timeout, parámetros añadidos TRatio, ETime e CRetry, producción. Gestión de currículum mejorada en los comandos Store e Retrieve.

Registrador de datos con transferencia automática de archivos en servidor FTP

El programa FTPDataLogger (Descargar) realiza la adquisición de 2 entradas analógicas y cada minuto realiza la historización de los valores en un archivo en formato CSV, cada hora el archivo de registro se transfiere automáticamente a un servidor FTP remoto en la nube.

El programa se puede modificar para adaptarlo a sus necesidades adquiriendo un mayor número de entradas analógicas o mediante el FB ModbusMaster adquiriendo valores de instrumentos con protocolo Modbus. Una característica especial del programa es el uso del FB FIFOFile que almacena los datos en el registro FIFO durante la transferencia del archivo de registro al servidor FTP remoto para no perder los registros.

Echar un vistazo al programa fuente es útil para aprender no solo cómo usar el FB FTPClient sino también para comprender cómo administrar el sistema de archivos del sistema escribiendo archivos en formato CSV.

Círculo de información

Función de bloqueo

CÓDIGOS: indisponible

Laboratorio lógico: eLLabNetworkLib

Descripción

Store (BOOL) Comando de transferencia de archivos desde el directorio local al servidor FTP.
Retrieve (BOOL) Comando de transferencia de archivos desde el servidor FTP al directorio local.
Delete (BOOL) Comando de eliminación de archivos en el servidor FTP.
SpyOn (BOOL) Si está activo, te permite espiar el funcionamiento del FB.
FTPServer (@STRING) Puntero de cadena de definición de servidor FTP.
FTPPort (UINT) Definición de puerto para la conexión al servidor FTP.
User (@STRING) Puntero de cadena de definición de nombre de usuario.
Password (@STRING) Puntero de cadena de definición de contraseña.
LocalFile (@STRING) Puntero de cadena de definición de nombre de archivo local.
RemoteFile (@STRING) Puntero de cadena de definición de nombre de archivo en el servidor FTP. Si las carpetas están definidas en el nombre (ejemplo /DirA/DirB/File.txt), el FB los creará.
Done (BOOL) Se activa al final de la ejecución del comando. Permanece activo hasta que se deshabilitan todos los comandos; para ejecutar un nuevo comando, deshabilite y luego vuelva a habilitar el comando.
Culpa (BOOL) Activo para un bucle en caso de error de ejecución.
Tratamiento (REAL) Porcentaje de transferencia realizada.
etime (TIME) Devuelve el tiempo necesario para ejecutar el comando.
CRReintentar (UDINT) Número de intentos realizados.
Errors (UDINT) Contador de errores de ejecución.

Imagen FB FTPClient_v4

Operación de espionaje

Se SpyOn active puede utilizar la consola espía para comprobar el funcionamiento del FB. Hay varios niveles de factores desencadenantes.

Desencadenantes de espionaje
16 00000001 #Tx: Comandos enviados al servidor FTP.
16 00000002 #Rx: Estados de respuesta del servidor FTP.
16 10000000 #LG: Mensajes de registro de operaciones.
16 40000000 #que: Errores de ejecución

Analizar los mensajes que se muestran en la consola de espionaje te ayuda a comprender cualquier error en las secuencias..

Mensajes en espionaje
Messaggi di connessione al server validi per tutti comandi.

| FTPClient:Rx|[0010] 227 Entering Passive Mode (81,88,52,106,222,229)          Apertura connessione passiva
| FTPClient:Lg|[0010] PASV port:57061                                           Porta per connessione passiva
| FTPClient:Lg|[0022] Server do not allows the resume command                   Server non supporta il comando di resume
| FTPClient:Lg|[0022] Server allows the resume command                          Server supporta il comando di resume
| FTPClient:Lg|[0100] User logged in                                            Client connesso al server

Messaggi del comando di store.

| FTPClient:Lg|[1000] Send file: Local file => Remote file                      Informazioni sul file locale e remoto
| FTPClient:Lg|[1000] File to send length: xxxxxxx                              Dimensione file locale da inviare in bytes
| FTPClient:Tx|[1305] ABOR                                                      Abortita sequenza in corso segue un resume
| FTPClient:Lg|[1405] xxxxxxx bytes has been transferred, xx.xxx KB/S           Dimensione file inviato e velocità di invio
| FTPClient:Lg|--------------------------------------[Store end, xxx.xxx (S)]-- Fine comando e durata

Messaggi del comando di retrieve.

| FTPClient:Lg|[2002] File to receive length: xxxxxx                            Dimensione file da scaricare in bytes (Se resume)
| FTPClient:Lg|[2203] Data reception restart                                    Non si ricevono dati per 80% di Timeout, eseguo resume
| FTPClient:Lg|[2203] Server timeout restart                                    Prima di timeout server eseguo resume (Timeout*2)
| FTPClient:Tx|[2205] ABOR                                                      Abortita sequenza in corso segue un resume
| FTPClient:Lg|[2302] xxxxxxx bytes has been transferred, xx.xxx KB/S           Dimensione file ricevuto e velocità di invio
| FTPClient:Lg|-----------------------------------[Retrieve end, xxx.xxx (S)]-- Fine comando e durata

Ejemplos

Cómo utilizar los ejemplos..

ST_FTPClient: La conexión a un servidor FTP se gestiona administrando el comando Store para enviar un archivo desde la carpeta del sistema local al servidor FTP. El comando Retrieve transferir un archivo desde el servidor FTP a la carpeta del sistema local. El comando Delete para eliminar el archivo en el servidor FTP.

ST_FTPFileTransfer: Ejemplo de transferencia de un archivo de un servidor FTP a otro, el archivo se coloca en el disco local. En el ejemplo, se utilizaron dos terminales Weintek como servidor FTP.

LogicLab (Ptp119)
PROGRAM ST_FTPClient
VAR
    Store : BOOL; (* FTP store command *)
    Retrieve : BOOL; (* FTP retrieve command *)
    Delete : BOOL; (* FTP delete command *)
    CaseNr : USINT; (* Program case *)
    FTP : FTPClient_v4; (* FTP client *)
END_VAR

// *****************************************************************************
// PROGRAM "ST_FTPClient"
// *****************************************************************************
// This program connects to the SlimLine FTP server and allows to transfer file
// from local directory to FTP server and viceversa.
// -----------------------------------------------------------------------------

    // -------------------------------------------------------------------------
    // INITIALIZATION
    // -------------------------------------------------------------------------
    // Program initializations.

    IF (SysFirstLoop) THEN
        FTP.SpyOn:=TRUE; //Spy active
        FTP.FTPServer:=ADR('192.168.0.230'); //Server FTP
        FTP.FTPPort:=21; //Server FTP
        FTP.User:=ADR('Admin'); //User
        FTP.Password:=ADR('Admin'); //Password
    END_IF;

    // -------------------------------------------------------------------------
    // FTP CLIENT
    // -------------------------------------------------------------------------
    // Executs the FTP client and resets the commands on execution fault.

    FTP(); //FTP client
    IF (FTP.Fault) THEN CaseNr:=0; END_IF;

    // -------------------------------------------------------------------------
    // PROGRAM CASES
    // -------------------------------------------------------------------------
    // Program cases management.

    CASE (CaseNr) OF

        // ---------------------------------------------------------------------
        // MANAGES THE COMMAND
        // ---------------------------------------------------------------------
        // Reset commands.

        0:
        FTP.Store:=FALSE; //Store command
        FTP.Retrieve:=FALSE; //Retrieve command
        FTP.Delete:=FALSE; //Delete command

        // Check commands.

        IF (Store) THEN Store:=FALSE; CaseNr:=10; RETURN; END_IF;
        IF (Retrieve) THEN Retrieve:=FALSE; CaseNr:=20; RETURN; END_IF;
        IF (Delete) THEN Delete:=FALSE; CaseNr:=30; RETURN; END_IF;

        // ---------------------------------------------------------------------
        // STORE COMMAND
        // ---------------------------------------------------------------------
        // Command execution.

        10:
        FTP.Store:=TRUE; //Store command
        FTP.LocalFile:=ADR('C:/System/Logs.txt'); //Local file definition
        FTP.RemoteFile:=ADR('D:/Logs.txt'); //Remote file definition
        IF NOT(FTP.Done) THEN RETURN; END_IF;
        FTP.Store:=FALSE; //Store command
        CaseNr:=0; //Program case

        // ---------------------------------------------------------------------
        // RETRIEVE COMMAND
        // ---------------------------------------------------------------------
        // Command execution.

        20:
        FTP.Retrieve:=TRUE; //Retrieve command
        FTP.LocalFile:=ADR('D:/Logs.txt'); //Local file definition
        FTP.RemoteFile:=ADR('C:/System/Logs.txt'); //Remote file definition
        IF NOT(FTP.Done) THEN RETURN; END_IF;
        FTP.Retrieve:=FALSE; //Retrieve command
        CaseNr:=0; //Program case

        // ---------------------------------------------------------------------
        // DELETE COMMAND
        // ---------------------------------------------------------------------
        // Command execution.

        30:
        FTP.Delete:=TRUE; //Delete command
        FTP.LocalFile:=eNULL; //Local file definition
        FTP.RemoteFile:=ADR('D:/Logs.txt'); //Remote file definition
        IF NOT(FTP.Done) THEN RETURN; END_IF;
        FTP.Delete:=FALSE; //Delete command
        CaseNr:=0; //Program case
    END_CASE;

// [End of file]
LogicLab (Ptp119)
PROGRAM ST_FTPFileTransfer
VAR
    DTransfer : BOOL; (* Data transfer command *)
    CaseNr : USINT; (* Program case *)
    FTP : FTPClient_v4; (* FTP client *)
END_VAR

// *****************************************************************************
// PROGRAM "ST_FTPFileTransfer"
// *****************************************************************************
// This program transfers a file from one FTP server to another.
// -----------------------------------------------------------------------------

    // -------------------------------------------------------------------------
    // INITIALIZATION
    // -------------------------------------------------------------------------
    // Program initializations.

    IF (SysFirstLoop) THEN
        FTP.SpyOn:=TRUE; //Spy active
    END_IF;

    // -------------------------------------------------------------------------
    // FTP CLIENT
    // -------------------------------------------------------------------------
    // Executs the FTP client and resets the commands on execution fault.

    FTP(); //FTP client
    IF (FTP.Fault) THEN CaseNr:=0; END_IF;

    // -------------------------------------------------------------------------
    // PROGRAM CASES
    // -------------------------------------------------------------------------
    // Program cases management.

    CASE (CaseNr) OF

        // ---------------------------------------------------------------------
        // TRANSFER FILE
        // ---------------------------------------------------------------------
        // Wait for the command.

        0:
        IF (DTransfer) THEN DTransfer:=FALSE; CaseNr:=10; RETURN; END_IF;

        // ---------------------------------------------------------------------
        // READ FILE FROM THE SERVER AND DELETE IT
        // ---------------------------------------------------------------------
        // Define server credential and connects to it.

        10:
        FTP.FTPServer:=ADR('192.168.0.234'); //Server FTP
        FTP.FTPPort:=21; //Server port
        FTP.User:=ADR('uploadhis'); //User
        FTP.Password:=ADR('111111'); //Password
        FTP.LocalFile:=ADR('D:/Logs.txt'); //Local file definition
        FTP.RemoteFile:=ADR('datalog/Logs.txt'); //Remote file definition
        CaseNr:=CaseNr+1; //Program case

        // ---------------------------------------------------------------------
        // Retrieve command execution.

        11:
        FTP.Retrieve:=TRUE; //Retrieve command
        IF NOT(FTP.Done) THEN RETURN; END_IF;
        FTP.Retrieve:=FALSE; //Retrieve command
        CaseNr:=CaseNr+1; //Program case

        // ---------------------------------------------------------------------
        // Delete command execution.

        12:
        FTP.Delete:=TRUE; //Delete command
        IF NOT(FTP.Done) THEN RETURN; END_IF;
        FTP.Delete:=FALSE; //Delete command
        CaseNr:=20; //Program case

        // ---------------------------------------------------------------------
        // STORE FILE TO THE SERVER
        // ---------------------------------------------------------------------
        // Define server credential and connects to it.

        20:
        FTP.FTPServer:=ADR('192.168.0.216'); //Server FTP
        FTP.FTPPort:=21; //Server port
        FTP.User:=ADR('uploadhis'); //User
        FTP.Password:=ADR('111111'); //Password
        FTP.LocalFile:=ADR('D:/Logs.txt'); //Local file definition
        FTP.RemoteFile:=ADR('datalog/Logs.txt'); //Remote file definition
        CaseNr:=CaseNr+1; //Program case

        // ---------------------------------------------------------------------
        // Command end waiting.

        21:
        FTP.Store:=TRUE; //Store command
        IF NOT(FTP.Done) THEN RETURN; END_IF;
        FTP.Store:=FALSE; //Store command
        CaseNr:=0; //Program case
    END_CASE;

// [End of file]
¿Le resultó útil este artículo?