Vai al contenuto

FTPClient, connects to a FTP server

Vai all indice del manuale di programmazione
Tipo: Blocco funzione
Libreria LogicLab: eLLabNetworkLib
Libreria Codesys: Non disponibile

Questo blocco funzione da eseguire in task Back, permette di gestire la connessione al server FTP definito in FTPServer con username definito in User e password definita in Password.

Attivando Store il file locale definito in LocalFile viene trasferito nel server FTP con il nome indicato in RemoteFile, terminato il trasferimento si attiva l’uscita Done che rimane attiva fino alla disabilitazione del comando.

Attivando Retrieve il file nel server FTP con il nome indicato in RemoteFile viene trasferito in locale con il nome definito in LocalFile, terminato il trasferimento si attiva l’uscita Done che rimane attiva fino alla disabilitazione del comando.

Attivando Delete il file nel server FTP con il nome indicato in RemoteFile viene cancellato e si attiva l’uscita Done che rimane attiva fino alla disabilitazione del comando.

In caso di errore l’esecuzione comando termina e si attiva per un loop l’uscita Fault e si attiva l’uscita Done che rimane attiva fino alla disabilitazione del comando.

Upgrade list

FTPClient_v4

Eliminato parametro Timeout, aggiunto parametri TRatio, ETime e CRetry, in uscita. Migliorata la gestione del resume sui comandi di Store e Retrieve.

Datalogger con trasferimento automatico file su server FTP

Il programma FTPDataLogger (Download) esegue l’acquisizione di 2 ingressi analogici ed ad ogni minuto ne esegue la storicizzazione dei valori su di un file in formato CSV, ogni ora il file di log viene automaticamente trasferito su di un server FTP remoto nel cloud.

Il programma può essere modificato per le proprie esigenze acquisendo un numero maggiore di ingressi analogici o tramite l’FB ModbusMaster acquisendo valori da strumenti con il protocollo Modbus. Una particolarità del programma e l’utilizzo del FB FIFOFile che storicizza i dati nel registro FIFO durante il trasferimento del file di log sul server FTP remoto in modo da non perdere le registrazioni.

Dare una occhiata al programma sorgente è utile per apprendere non solo come utilizzare il FB FTPClient ma anche per comprendere come gestire il file system del sistema eseguendo la scrittura di file in formato CSV.

Attivazione server FTP su Windows

Configurare un server FTP (File Transfer Protocol) su Windows è una soluzione che permette tramite il FB FTPClient di eseguire trasferimenti di files tra programma LogicLab e PC. Per installare i componenti del server FTP occorre:

  • Aprire il Pannello di controllo e fare click su Programmi.
  • In Programmi e funzionalità, fare click su Attiva o disattiva le funzionalità di Windows.
  • Attivare tutte le opzioni del Server FTP e la Console di gestione IIS.

Procedendo, i componenti per configurare un server FTP verranno installati sul PC. Per configurare un sito FTP, occorre:

  • Aprire il Pannello di controllo e fare click su Sistema e sicurezza.
  • Fare clic su Strumenti di amministrazione-> Gestione IIS.
  • Nel riquadro Connessioni, fare clic con pulsante destro del mouse su Siti e selezionare Aggiungi sito FTP.
  • Proseguire con le informazioni richieste, nome e cartella del server, binding su tutti gli indirizzi IP, autenticazione di base per tutti gli utenti definiti in Windows.

Ora se tutte le impostazioni sono corrette con un client FTP sarà possibile all’interno dello stesso PC accedere via localhost al server FTP autenticandosi con le credenziali di un utente di Windows.

Screenshot attivazione server FTP su Windows

Abilitare l’accesso da rete

Per abilitare l’accesso al server FTP da rete occorre creare una regola nel firewall:

  • Aprire il Pannello di controllo e fare click su Windows Defender Firewall.
  • Fare clic su Consenti app o funzionalità….
  • Abilitare Server FTP.
Screenshot abilitazione firewall su server FTP

Descrizione

Store (BOOL) Comando trasferimento file da directory locale a server FTP.
Retrieve (BOOL) Comando trasferimento file da server FTP a directory locale.
Delete (BOOL) Comando cancellazione file su server FTP.
SpyOn (BOOL) Se attivo permette di spiare il funzionamento della FB.
FTPServer (@STRING) Puntatore stringa definizione server FTP.
FTPPort (UINT) Definizione porta connessione a server FTP.
User (@STRING) Puntatore stringa definizione nome utente.
Password (@STRING) Puntatore stringa definizione password.
LocalFile (@STRING) Puntatore stringa definizione nome del file locale.
RemoteFile (@STRING) Puntatore stringa definizione nome del file su server FTP. Se nel nome vengono definite cartelle (Esempio /DirA/DirB/File.txt), il FB provvederà alla loro creazione.
Done (BOOL) Si attiva al termine della esecuzione comando. Rimane attivo fino alla disabilitazione di tutti i comandi, per eseguire un nuovo comando disabilitare e poi riabilitare il comando.
Fault (BOOL) Attivo per un loop se errore esecuzione.
TRatio (REAL) Percentuale di trasferimento effettuata.
ETime (TIME) Ritorna il tempo impiegato esecuzione comando.
CRetry (UDINT) Numero di tentativi effettuati.
Errors (UDINT) Contatore errori di esecuzione.

Immagine FB FTPClient_v4

Spionaggio funzionamento

Se SpyOn attivo è possibile utilizzare utilizzare la console di spionaggio per verificare il funzionamento della FB. Sono previsti vari livelli di triggers.

Trigger di spionaggio
16#00000001Tx: Comandi inviati al server FTP.
16#00000002Rx: Stati risposta dal server FTP.
16#10000000Lg: Messaggi di log funzionamento.
16#40000000Er: Errori di esecuzione.

Analizzare i messaggi visualizzati nella console di spionaggio è un aiuto per comprendere eventuali errori nelle sequenze.

Messaggi in spionaggio
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
Messaggi comando store su server FTP di Windows
09:23:31.314477|FTPClient:Lg|------------------------------------------------[Store start]--
09:23:31.314527|FTPClient:Lg|[xxxx] Send file: C:/System/Logs.txt => Logs.txt
09:23:31.324019|FTPClient:Rx|[0001] 220 Microsoft FTP Service..
09:23:34.323580|FTPClient:Lg|[0002] Retry counter:1
09:23:34.325435|FTPClient:Tx|[0004] USER User..
09:23:34.330186|FTPClient:Rx|[0004] 331 Password required..
09:23:34.332144|FTPClient:Tx|[0006] PASS Password..
09:23:34.337412|FTPClient:Rx|[0006] 230 User logged in...
09:23:37.338216|FTPClient:Tx|[0009] TYPE I..
09:23:37.342520|FTPClient:Rx|[0009] 200 Type set to I...
09:23:37.344783|FTPClient:Tx|[0021] FEAT..
09:23:37.349798|FTPClient:Rx|[0021] 211-Extended features supported:..
09:23:37.352881|FTPClient:Rx|[0022] LANG EN*..
09:23:37.355346|FTPClient:Rx|[0022] UTF8..
09:23:37.358139|FTPClient:Rx|[0022] AUTH TLS;TLS-C;SSL;TLS-P;..
09:23:37.360768|FTPClient:Rx|[0022] PBSZ..
09:23:37.363523|FTPClient:Rx|[0022] PROT C;P;..
09:23:37.365927|FTPClient:Rx|[0022] CCC..
09:23:37.368278|FTPClient:Rx|[0022] HOST..
09:23:37.370645|FTPClient:Rx|[0022] SIZE..
09:23:37.373015|FTPClient:Rx|[0022] MDTM..
09:23:37.375574|FTPClient:Rx|[0022] REST STREAM..
09:23:37.378080|FTPClient:Rx|[0022] 211 END..
09:23:37.378111|FTPClient:Lg|[0022] Server allows the resume command
09:23:37.379064|FTPClient:Lg|[0100] User logged in
09:23:37.382805|FTPClient:Tx|[9902] CWD /..
09:23:37.388474|FTPClient:Rx|[9902] 250 CWD command successful...
09:23:37.390961|FTPClient:Tx|[9002] PASV..
09:23:37.396246|FTPClient:Rx|[9002] 227 Entering Passive Mode (192,168,1,122,242,221)...
09:23:37.397649|FTPClient:Lg|[9002] Try data connection to PASV IP:192.168.1.122, Port:62173
09:23:37.403935|FTPClient:Lg|[9003] Data connection Ok to PASV IP
09:23:37.405550|FTPClient:Tx|[1202] REST 0..
09:23:37.410027|FTPClient:Rx|[1202] 350 Restarting at 0...
09:23:37.412724|FTPClient:Tx|[1302] STOR Logs.txt..
09:23:37.424600|FTPClient:Rx|[1302] 125 Data connection already open; Transfer starting...
09:23:37.977779|FTPClient:Rx|[1501] 226 Transfer complete...
09:23:40.979023|FTPClient:Tx|[9101] SIZE Logs.txt..
09:23:40.984463|FTPClient:Rx|[9101] 213 63960..
09:23:40.985295|FTPClient:Lg|[9101] Remote file length: 63960
09:23:40.987348|FTPClient:Tx|[9501] QUIT..
09:23:40.991892|FTPClient:Rx|[9501] 221 Goodbye...
09:23:42.986620|FTPClient:Lg|[9501] 63960 bytes been transferred, 1 retry
09:23:42.986665|FTPClient:Lg|--------------------------------------------------[Store end]--

Esempi

Come utilizzare gli esempi.

ST_FTPClient: Viene gestita la connessione ad un server FTP gestendo il comando di Store per inviare un file dalla cartella locale del sistema al server FTP. Il comando Retrieve per trasferire un file dal server FTP alla cartella locale del sistema. Il comando Delete per cancellare il file sul server FTP.

ST_FTPFileTransfer: Esempio di trasferimento di un file da un server FTP ad un’altro, il file viene appoggiato sul disco locale. Nell’esempio come server FTP sono stati utilizzati due terminali Weintek.

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]
Was this article helpful?