diff --git a/.obsidian/plugins/obsidian-mindmap-nextgen/data.json b/.obsidian/plugins/obsidian-mindmap-nextgen/data.json index 24fa07e..41f4552 100644 --- a/.obsidian/plugins/obsidian-mindmap-nextgen/data.json +++ b/.obsidian/plugins/obsidian-mindmap-nextgen/data.json @@ -1,10 +1,6 @@ { "version": "2.0", "layout": [ - null, - null, - null, - null, null, null, null, diff --git a/.obsidian/plugins/recent-files-obsidian/data.json b/.obsidian/plugins/recent-files-obsidian/data.json index 5a38d7b..52ccde4 100644 --- a/.obsidian/plugins/recent-files-obsidian/data.json +++ b/.obsidian/plugins/recent-files-obsidian/data.json @@ -1,44 +1,136 @@ { "recentFiles": [ + { + "basename": "FB2120 - MasseliTCP Read - v1.8", + "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - v1.8.md" + }, + { + "basename": "FB2120 - MasseliTCP Read - Descrizzione Software - v1.8", + "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - Descrizzione Software - v1.8.md" + }, + { + "basename": "Hardware used for 485-TCP", + "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Hardware used for 485-TCP.md" + }, + { + "basename": "Versiones", + "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Versiones.md" + }, + { + "basename": "S7-300 - TCON - TRCV", + "path": "01-Documentation/Siemens/PLC Siemens/S7-300 - TCON - TRCV.md" + }, { "basename": "Maselli - ADAM - Protocol", "path": "01-Documentation/Dispositivos - Manuales/Maselli/Maselli - ADAM - Protocol.md" }, { - "basename": "Maselli Proprietary Serial-Socket Protocol", - "path": "01-Documentation/Dispositivos - Manuales/Maselli/Maselli - Utility/Maselli Proprietary Serial-Socket Protocol.md" + "basename": "Progetto 98050 Fiera - Tavolo di accumulo", + "path": "03-VM/44 - 98050 - Fiera/Progetto 98050 Fiera - Tavolo di accumulo.md" }, { - "basename": "Masselli (UR62 & UR29)", - "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Masselli (UR62 & UR29).md" + "basename": "Install Docker on Ubuntu", + "path": "01-Documentation/Dockers/Install Docker on Ubuntu.md" }, { - "basename": "Maselli - Protocol - Gateway - 485 - Ethernet", - "path": "01-Documentation/Dispositivos - Manuales/Maselli/Maselli - Protocol - Gateway - 485 - Ethernet.md" + "basename": "FB Scan Time - FB1", + "path": "03-VM/9..... MASTER Transport/Standard Transport/FB Scan Time - FB1.md" }, { - "basename": "CableMAX - Converter 485 - Serial Adaptor RS232 - CM-RSDB9-PRO", - "path": "01-Documentation/Dispositivos - Manuales/CableMAX - Converter 485 - Serial Adaptor RS232 - CM-RSDB9-PRO.md" + "basename": "5.007382-EXMU01UF - RVU008 - EQPT24731 - Initial Data", + "path": "04-SIDEL/03 - 5.007382-EXMU01UF - RVU008 - EQPT24731/5.007382-EXMU01UF - RVU008 - EQPT24731 - Initial Data.md" }, { - "basename": "Untitled", - "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Untitled.md" + "basename": "OB30 Calculation", + "path": "03-VM/9..... MASTER Transport/Standard Transport/OB30 Calculation.md" + }, + { + "basename": "FB Scan Time OB1 - FB4", + "path": "03-VM/9..... MASTER Transport/Standard Transport/FB Scan Time OB1 - FB4.md" + }, + { + "basename": "Docker Basics - Essential Commands and Usage Guide", + "path": "01-Documentation/Dockers/Docker Basics - Essential Commands and Usage Guide.md" + }, + { + "basename": "Waveshare RS232-485 Ethernet - Wifi - ADAM 4021 - Using Serial200", + "path": "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi/Waveshare RS232-485 Ethernet - Wifi - ADAM 4021 - Using Serial200.md" }, { "basename": "DAR Description - DIET AS REGULAR - SAE452 San Giorgio in Bosco", "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/DAR Description - DIET AS REGULAR - SAE452 San Giorgio in Bosco.md" }, + { + "basename": "Test - Fatto su Maselli - 06-05-2025", + "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Test - Fatto su Maselli - 06-05-2025.md" + }, + { + "basename": "GIT commands HELP", + "path": "01-Documentation/GIT - GitHub/GIT commands HELP.md" + }, + { + "basename": "Notes - Git - Gitea", + "path": "01-Documentation/GIT - GitHub/Notes - Git - Gitea.md" + }, + { + "basename": "Git - Start New Repository with Visual Studio Code - VS Code", + "path": "01-Documentation/GIT - GitHub/Git - Start New Repository with Visual Studio Code - VS Code.md" + }, + { + "basename": "GitHub Privacy", + "path": "01-Documentation/GIT - GitHub/GitHub Privacy.md" + }, + { + "basename": "Visit to Maselli 06-05-2025", + "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Visit to Maselli 06-05-2025.md" + }, { "basename": "Waveshare RS232-485 Ethernet - Wifi - ADAM 4021 - Using com0com - MaselliSimulatorApp Python", "path": "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi/Waveshare RS232-485 Ethernet - Wifi - ADAM 4021 - Using com0com - MaselliSimulatorApp Python.md" }, { - "basename": "com0com Setup Only version 2.2 - version 3 NOT WORKING with Windows 11", - "path": "01-Documentation/Dispositivos - Manuales/COM - Virtual COM com0com/com0com Setup Only version 2.2 - version 3 NOT WORKING with Windows 11.md" + "basename": "CableMAX - Converter 485 - Serial Adaptor RS232 - CM-RSDB9-PRO", + "path": "01-Documentation/Dispositivos - Manuales/CableMAX - Converter 485 - Serial Adaptor RS232 - CM-RSDB9-PRO.md" }, { - "basename": "Waveshare RS232-485 Ethernet - Wifi - ADAM 4021 - Using Serial200", - "path": "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi/Waveshare RS232-485 Ethernet - Wifi - ADAM 4021 - Using Serial200.md" + "basename": "ADAM 4021 - 485 to 4..20ma - Commissioning & Firmware update", + "path": "01-Documentation/Dispositivos - Manuales/ADAM/ADAM 4021 - 485 to 4..20ma - Commissioning & Firmware update.md" + }, + { + "basename": "Maselli Sensor to Siemens PLC Communication Implementation", + "path": "01-Documentation/Dispositivos - Manuales/ADAM/Maselli Sensor to Siemens PLC Communication Implementation.md" + }, + { + "basename": "Masselli (UR62 & UR29)", + "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Masselli (UR62 & UR29).md" + }, + { + "basename": "ADAM -", + "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/ADAM -.md" + }, + { + "basename": "Untitled", + "path": "04-SIDEL/06 - E5.007363 - Modifica O&U - SAE196 (cip integrato)/Untitled.md" + }, + { + "basename": "Communication TSEND_C - TRCV_C", + "path": "01-Documentation/Siemens/PLC Siemens/Communication TSEND_C - TRCV_C.md" + }, + { + "basename": "Maselli Proprietary Serial-Socket Protocol", + "path": "01-Documentation/Dispositivos - Manuales/Maselli/Maselli - Utility/Maselli Proprietary Serial-Socket Protocol.md" + }, + { + "basename": "Maselli - Protocol - Gateway - 485 - Ethernet", + "path": "01-Documentation/Dispositivos - Manuales/Maselli/Maselli - Protocol - Gateway - 485 - Ethernet.md" + }, + { + "basename": "Untitled", + "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Untitled.md" + }, + { + "basename": "com0com Setup Only version 2.2 - version 3 NOT WORKING with Windows 11", + "path": "01-Documentation/Dispositivos - Manuales/COM - Virtual COM com0com/com0com Setup Only version 2.2 - version 3 NOT WORKING with Windows 11.md" }, { "basename": "LAD Descriptions from XDA files from Tia Portal", @@ -88,14 +180,6 @@ "basename": "SAE346 - IO from Electrical Diagram", "path": "04-SIDEL/05 - E5.007161 - Modifica O&U - SAE346/SAE346 - IO from Electrical Diagram.md" }, - { - "basename": "ADAM 4021 - 485 to 4..20ma - Commissioning & Firmware update", - "path": "01-Documentation/Dispositivos - Manuales/ADAM/ADAM 4021 - 485 to 4..20ma - Commissioning & Firmware update.md" - }, - { - "basename": "Maselli Sensor to Siemens PLC Communication Implementation", - "path": "01-Documentation/Dispositivos - Manuales/ADAM/Maselli Sensor to Siemens PLC Communication Implementation.md" - }, { "basename": "Openness Python Library - siemens_tia_scripting", "path": "01-Documentation/Siemens/Openness/Openness Python Library - siemens_tia_scripting.md" @@ -107,98 +191,6 @@ { "basename": "Notas para crear nuevas aplicaciones", "path": "07 - Desarrolo de Proyectos - Scripts - Visual Studio/Proyectos Visual Studio/Notas para crear nuevas aplicaciones.md" - }, - { - "basename": "Visual Studio Notes", - "path": "07 - Desarrolo de Proyectos - Scripts - Visual Studio/Visual Studio Notes.md" - }, - { - "basename": "Conversión LAD a SCL Siemens", - "path": "01-Documentation/Python/Scripts Python/XML to SCL Siemens/Conversión LAD a SCL Siemens.md" - }, - { - "basename": "Untitled", - "path": "04-SIDEL/06 - E5.007363 - Modifica O&U - SAE196 (cip integrato)/Untitled.md" - }, - { - "basename": "E5.007600 - SAE469 - FDM", - "path": "04-SIDEL/07 - E5.007600 - SAE469/E5.007600 - SAE469 - FDM.md" - }, - { - "basename": "Openness Python Library - siemens_tia_scripting - Parsing TIA Portal `_XRef.xml` Files for Call Tree Generation", - "path": "01-Documentation/Siemens/Openness/Openness Python Library - siemens_tia_scripting - Parsing TIA Portal `_XRef.xml` Files for Call Tree Generation.md" - }, - { - "basename": "SIDEL - Passwords", - "path": "01-Documentation/SIDEL/SIDEL - Passwords.md" - }, - { - "basename": "x2 Comparación Excel", - "path": "01-Documentation/AI - IA - LLM - Artificial Intelligence/Prompts/Scripts/Update S7 DB without names/x2 Comparación Excel.md" - }, - { - "basename": "SysInternals Tools - WinInternals", - "path": "01-Documentation/Windows/SysInternals Tools - WinInternals.md" - }, - { - "basename": "Software differences - After compilation", - "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Software problems/Software differences - After compilation.md" - }, - { - "basename": "AWL - STL Types - Parámetros Típicos", - "path": "01-Documentation/Python/Scripts Python/XML to SCL Siemens/AWL - STL Types - Parámetros Típicos.md" - }, - { - "basename": "AWL - STL Types", - "path": "01-Documentation/Python/Scripts Python/XML to SCL Siemens/AWL - STL Types.md" - }, - { - "basename": "Estructura XML Detallada para Topología de Red en Exportaciones AML de TIA Portal", - "path": "01-Documentation/CAx AutomationML/Estructura XML Detallada para Topología de Red en Exportaciones AML de TIA Portal.md" - }, - { - "basename": "Especificación Formal del Formato CAx (AML)", - "path": "01-Documentation/CAx AutomationML/Especificación Formal del Formato CAx (AML).md" - }, - { - "basename": "Recipes names to File", - "path": "01-Documentation/Siemens/Comfort Panels & WinCC/VB Scripts/Recipes names to File.md" - }, - { - "basename": "cSharp Decompiler", - "path": "01-Documentation/Decompiler/cSharp Decompiler.md" - }, - { - "basename": "Report Javier Vargas - SAE052", - "path": "04-SIDEL/12 - SAE052 - Syrup Update & GSD Update/Report Javier Vargas - SAE052.md" - }, - { - "basename": "Visit to Maselli 06-05-2025", - "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Visit to Maselli 06-05-2025.md" - }, - { - "basename": "Test - Fatto su Maselli - 06-05-2025", - "path": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Test - Fatto su Maselli - 06-05-2025.md" - }, - { - "basename": "Differences", - "path": "04-SIDEL/10 - E5.007095 - Modifica O&U - SAE463/Differences.md" - }, - { - "basename": "Change old Promass on Siemens S7-300 for new version - 63 - 300", - "path": "04-SIDEL/00 - MASTER/MIXER/Procedimientos/Change old Promass on Siemens S7-300 for new version - 63 - 300.md" - }, - { - "basename": "Emails", - "path": "04-SIDEL/10 - E5.007095 - Modifica O&U - SAE463/Emails.md" - }, - { - "basename": "SIDEL - Upgrades - Promemoria", - "path": "04-SIDEL/SIDEL - Upgrades - Promemoria.md" - }, - { - "basename": "SIDEL - Master - IPs", - "path": "04-SIDEL/00 - MASTER/SIDEL - Master - IPs.md" } ], "omittedPaths": [], diff --git a/.obsidian/workspace.json b/.obsidian/workspace.json index 703ee85..3cb4d20 100644 --- a/.obsidian/workspace.json +++ b/.obsidian/workspace.json @@ -4,131 +4,71 @@ "type": "split", "children": [ { - "id": "3b4a7d5d0b5c2e8e", + "id": "06a172e6fdedfbf5", "type": "tabs", "children": [ { - "id": "b0de106fff7d02eb", + "id": "46cbecdfd83b10e4", "type": "leaf", "state": { "type": "markdown", "state": { - "file": "04-SIDEL/06 - E5.007363 - Modifica O&U - SAE196 (cip integrato)/Untitled.md", + "file": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Test - Fatto su Maselli - 06-05-2025.md", "mode": "source", "source": false, "backlinks": false }, "icon": "lucide-file", - "title": "Untitled" + "title": "Test - Fatto su Maselli - 06-05-2025" } }, { - "id": "a38d3289675378b0", + "id": "5964c169ed489ae8", "type": "leaf", "state": { "type": "markdown", "state": { - "file": "01-Documentation/Dispositivos - Manuales/Maselli/Maselli - ADAM - Protocol.md", + "file": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Hardware used for 485-TCP.md", "mode": "source", "source": false, "backlinks": false }, "icon": "lucide-file", - "title": "Maselli - ADAM - Protocol" + "title": "Hardware used for 485-TCP" } }, { - "id": "f8c6a0d348e1d9c6", + "id": "e1a87a8e25c39351", "type": "leaf", "state": { "type": "markdown", "state": { - "file": "01-Documentation/Python/Scripts Python/XML to SCL Siemens/LAD Descriptions from XDA files from Tia Portal.md", + "file": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - v1.8.md", "mode": "source", "source": false, "backlinks": false }, "icon": "lucide-file", - "title": "LAD Descriptions from XDA files from Tia Portal" + "title": "FB2120 - MasseliTCP Read - v1.8" } }, { - "id": "9ed1cde3f8b68dde", + "id": "2bc2280b9c18e51a", "type": "leaf", "state": { "type": "markdown", "state": { - "file": "01-Documentation/AI - IA - LLM - Artificial Intelligence/AI Prompts useful.md", + "file": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - v1.8.md", "mode": "source", "source": false, "backlinks": false }, "icon": "lucide-file", - "title": "AI Prompts useful" - } - }, - { - "id": "699ef801ac43a3c8", - "type": "leaf", - "state": { - "type": "markdown", - "state": { - "file": "01-Documentation/Siemens/Openness/Guía de Exportación a Formato SIMATIC SD con TIA Portal Openness y Csharp.md", - "mode": "source", - "source": false, - "backlinks": false - }, - "icon": "lucide-file", - "title": "Guía de Exportación a Formato SIMATIC SD con TIA Portal Openness y Csharp" - } - }, - { - "id": "670831659031a736", - "type": "leaf", - "state": { - "type": "markdown", - "state": { - "file": "04-SIDEL/Projects Description.md", - "mode": "source", - "source": false, - "backlinks": false - }, - "icon": "lucide-file", - "title": "Projects Description" - } - }, - { - "id": "4f5651d4f649293a", - "type": "leaf", - "state": { - "type": "markdown", - "state": { - "file": "01-Documentation/Dispositivos - Manuales/COM - Virtual COM com0com/com0com Setup Only version 2.2 - version 3 NOT WORKING with Windows 11.md", - "mode": "source", - "source": false, - "backlinks": false - }, - "icon": "lucide-file", - "title": "com0com Setup Only version 2.2 - version 3 NOT WORKING with Windows 11" - } - }, - { - "id": "f93c4cd77a711e5b", - "type": "leaf", - "state": { - "type": "markdown", - "state": { - "file": "01-Documentation/Dispositivos - Manuales/Maselli/Maselli - Protocol - Gateway - 485 - Ethernet.md", - "mode": "source", - "source": false, - "backlinks": false - }, - "icon": "lucide-file", - "title": "Maselli - Protocol - Gateway - 485 - Ethernet" + "title": "FB2120 - MasseliTCP Read - v1.8" } } ], - "currentTab": 1 + "currentTab": 2 } ], "direction": "vertical" @@ -148,7 +88,7 @@ "type": "file-explorer", "state": { "sortOrder": "alphabetical", - "autoReveal": false + "autoReveal": true }, "icon": "lucide-folder-closed", "title": "Files" @@ -211,7 +151,7 @@ "state": { "type": "backlink", "state": { - "file": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/DAR Description - DIET AS REGULAR.md", + "file": "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - v1.8.md", "collapseAll": false, "extraContext": false, "sortOrder": "alphabetical", @@ -221,7 +161,7 @@ "unlinkedCollapsed": true }, "icon": "links-coming-in", - "title": "Backlinks for DAR Description - DIET AS REGULAR" + "title": "Backlinks for FB2120 - MasseliTCP Read - v1.8" } }, { @@ -322,54 +262,54 @@ "obsidian-importer:Open Importer": false } }, - "active": "a38d3289675378b0", + "active": "e1a87a8e25c39351", "lastOpenFiles": [ - "01-Documentation/Dispositivos - Manuales/Maselli/Maselli - Utility/Maselli Proprietary Serial-Socket Protocol.md", - "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Masselli (UR62 & UR29).md", - "01-Documentation/Dispositivos - Manuales/Maselli/Maselli - Protocol - Gateway - 485 - Ethernet.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - Descrizzione Software - v1.8.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Hardware used for 485-TCP.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - v1.8.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Untitled/Untitled.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Untitled/doc1.3.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Untitled", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250530095111.png", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250530095053.png", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Versiones.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Untitled 1.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Untitled.md", + "01-Documentation/Siemens/PLC Siemens/S7-300 - TCON - TRCV.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250529221344.png", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250529221334.png", "01-Documentation/Dispositivos - Manuales/Maselli/Maselli - ADAM - Protocol.md", - "01-Documentation/Dispositivos - Manuales/CableMAX - Converter 485 - Serial Adaptor RS232 - CM-RSDB9-PRO.md", - "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Untitled.md", + "03-VM/44 - 98050 - Fiera/Progetto 98050 Fiera - Tavolo di accumulo.md", + "03-VM/44 - 98050 - Fiera/Untitled.md", + "01-Documentation/Dockers/Install Docker on Ubuntu.md", + "03-VM/9..... MASTER Transport/Standard Transport/FB Scan Time - FB1.md", + "04-SIDEL/03 - 5.007382-EXMU01UF - RVU008 - EQPT24731/5.007382-EXMU01UF - RVU008 - EQPT24731 - Initial Data.md", + "03-VM/9..... MASTER Transport/Standard Transport/OB30 Calculation.md", + "03-VM/9..... MASTER Transport/Standard Transport/FB Scan Time OB1 - FB4.md", + "01-Documentation/Dockers/Docker Basics - Essential Commands and Usage Guide.md", + "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi/Waveshare RS232-485 Ethernet - Wifi - ADAM 4021 - Using Serial200.md", "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/DAR Description - DIET AS REGULAR - SAE452 San Giorgio in Bosco.md", - "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi/Waveshare RS232-485 Ethernet - Wifi - ADAM 4021 - Using com0com - MaselliSimulatorApp Python.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Test - Fatto su Maselli - 06-05-2025.md", + "01-Documentation/GIT - GitHub/GIT commands HELP.md", + "01-Documentation/GIT - GitHub/Notes - Git - Gitea.md", + "01-Documentation/GIT - GitHub/Git - Start New Repository with Visual Studio Code - VS Code.md", + "01-Documentation/GIT - GitHub/GitHub Privacy.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Visit to Maselli 06-05-2025.md", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250526165501.png", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos", + "04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP", "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi/adjuntos/Pasted image 20250523122653.png", "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi/adjuntos/Pasted image 20250523122629.png", - "01-Documentation/Dispositivos - Manuales/COM - Virtual COM com0com/com0com Setup Only version 2.2 - version 3 NOT WORKING with Windows 11.md", "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi/adjuntos/Pasted image 20250523122530.png", "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi/adjuntos", - "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi/Waveshare RS232-485 Ethernet - Wifi - ADAM 4021 - Using Serial200.md", "01-Documentation/Dispositivos - Manuales/Waveshare RS232-485 Ethernet - Wifi", - "01-Documentation/Python/Scripts Python/XML to SCL Siemens/LAD Descriptions from XDA files from Tia Portal.md", - "01-Documentation/AI - IA - LLM - Artificial Intelligence/AI Prompts useful.md", - "01-Documentation/Siemens/Openness/Guía de Exportación a Formato SIMATIC SD con TIA Portal Openness y Csharp.md", - "04-SIDEL/Projects Description.md", "01-Documentation/Dispositivos - Manuales/COM - Virtual COM com0com/adjuntos/Pasted image 20250523122236.png", - "04-SIDEL/05 - E5.007161 - Modifica O&U - SAE346/SAE346 - HMI - Machine Configuration.md", - "04-SIDEL/05 - E5.007161 - Modifica O&U - SAE346/COMM - FILLER - MIXER/Comm - Mixer - Filler.md", - "04-SIDEL/05 - E5.007161 - Modifica O&U - SAE346/SAE346 - Software adaptation from Master - Notes.md", - "04-SIDEL/05 - E5.007161 - Modifica O&U - SAE346/SAE346 P&ID.md", - "04-SIDEL/05 - E5.007161 - Modifica O&U - SAE346/SAE346 - Signals - CIP - Filler - Syrop.md", - "04-SIDEL/05 - E5.007161 - Modifica O&U - SAE346/SAE346 - Process diagram.md", - "04-SIDEL/05 - E5.007161 - Modifica O&U - SAE346/SAE346 - Master adaptation to compile.md", - "04-SIDEL/05 - E5.007161 - Modifica O&U - SAE346/SAE346 - IO from Electrical Diagram.md", - "01-Documentation/Dispositivos - Manuales/ADAM/ADAM 4021 - 485 to 4..20ma - Commissioning & Firmware update.md", - "01-Documentation/Dispositivos - Manuales/ADAM/Maselli Sensor to Siemens PLC Communication Implementation.md", "01-Documentation/Dispositivos - Manuales/adjuntos/Pasted image 20250522183148.png", - "01-Documentation/Dispositivos - Manuales/COM - Virtual COM com0com/adjuntos/Pasted image 20250522171402.png", - "01-Documentation/Dispositivos - Manuales/COM - Virtual COM com0com/adjuntos/Pasted image 20250522170556.png", "01-Documentation/Dispositivos - Manuales/COM - Virtual COM com0com/adjuntos", "01-Documentation/Dispositivos - Manuales/COM - Virtual COM com0com/Untitled", "01-Documentation/Dispositivos - Manuales/COM - Virtual COM com0com", - "01-Documentation/Siemens/Openness/Openness Python Library - siemens_tia_scripting.md", - "04-SIDEL/13 - E5.007560 - Modifica O&U - SAE235/Untitled.md", - "01-Documentation/Dispositivos - Manuales/adjuntos/Pasted image 20250521100106.png", - "01-Documentation/Dispositivos - Manuales/adjuntos/Pasted image 20250521100002.png", - "01-Documentation/Dispositivos - Manuales/adjuntos/Pasted image 20250521095735.png", "01-Documentation/Python/Scripts Python/XML to SCL Siemens", "04-SIDEL/13 - E5.007560 - Modifica O&U - SAE235", - "04-SIDEL/00 - MASTER/MIXER/Procedimientos/adjuntos", - "04-SIDEL/00 - MASTER/MIXER/Procedimientos", - "HTML import/Attachments", "03-Revised/93789 Sipa Italia - Tinny - HSCounters - Piattaforma/Divider/Untitled.canvas", "04-InLavoro/9..... MASTER Transport/Standard Transport/FB500 Logic.canvas", "04-InLavoro/HENKEL/93040 - HENKEL - BowlingGreen/TL22-L25/Synoptic Change/Q3.canvas", diff --git a/01-Documentation/Dockers/Install Docker on Ubuntu.md b/01-Documentation/Dockers/Install Docker on Ubuntu.md new file mode 100644 index 0000000..866f41e --- /dev/null +++ b/01-Documentation/Dockers/Install Docker on Ubuntu.md @@ -0,0 +1,66 @@ + + +[Ubuntu \| Docker Docs](https://docs.docker.com/engine/install/ubuntu/) + +### [Install using the `apt` repository](https://docs.docker.com/engine/install/ubuntu/#install-using-the-repository) + +Before you install Docker Engine for the first time on a new host machine, you need to set up the Docker `apt` repository. Afterward, you can install and update Docker from the repository. + +1. Set up Docker's `apt` repository. + + ```bash + # Add Docker's official GPG key: + sudo apt-get update + sudo apt-get install ca-certificates curl + sudo install -m 0755 -d /etc/apt/keyrings + sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc + sudo chmod a+r /etc/apt/keyrings/docker.asc + + # Add the repository to Apt sources: + echo \ + "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \ + $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable" | \ + sudo tee /etc/apt/sources.list.d/docker.list > /dev/null + sudo apt-get update + ``` + +2. Install the Docker packages. + + Latest Specific version + + --- + + To install the latest version, run: + + ```console + $ sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin + ``` + + --- + +3. Verify that the installation is successful by running the `hello-world` image: + + ```console + $ sudo docker run hello-world + ``` + + This command downloads a test image and runs it in a container. When the container runs, it prints a confirmation message and exits. + + +You have now successfully installed and started Docker Engine. + +> **Tip** +> +> Receiving errors when trying to run without root? +> +> The `docker` user group exists but contains no users, which is why you’re required to use `sudo` to run Docker commands. Continue to [Linux postinstall](https://docs.docker.com/engine/install/linux-postinstall) to allow non-privileged users to run Docker commands and for other optional configuration steps. + +#### [Upgrade Docker Engine](https://docs.docker.com/engine/install/ubuntu/#upgrade-docker-engine) + +To upgrade Docker Engine, follow step 2 of the [installation instructions](https://docs.docker.com/engine/install/ubuntu/#install-using-the-repository), choosing the new version you want to install. + + +### Install Portainer + +[Install Portainer CE with Docker on Linux \| Portainer Documentation](https://docs.portainer.io/start/install-ce/server/docker/linux) + diff --git a/01-Documentation/GIT - GitHub/GIT commands HELP.md b/01-Documentation/GIT - GitHub/GIT commands HELP.md new file mode 100644 index 0000000..a428699 --- /dev/null +++ b/01-Documentation/GIT - GitHub/GIT commands HELP.md @@ -0,0 +1,252 @@ +*** + +### Comandos Basicos +*** +```bash + + +git add . // Agregar todos los cambios al proximo commit +git commit -m "Mensaje" +git push // Enviar el o los commit al server Remoto + +git pull // Descargar las modificaciones desde el server remoto + + +``` + + +#### Staging Changes (`git add`) + +Before you can commit your changes, you need to tell Git which specific changes you want to include in the next commit. This is called "staging." + +- **`git add `** + - Stages a specific file. For example: `git add index.html` +- **`git add .`** + - Stages all changes in the current directory and its subdirectories. This is a very common command to stage all modified and new files. +- **`git add -u`** + - Stages all modified and deleted files, but _not_ new files. Useful if you've only made changes to existing tracked files. +- **`git add -A`** + - Stages all changes (modified, new, and deleted files) in the entire repository. This is equivalent to `git add .` if you are in the root of the repository. + +**To check what's staged/unstaged:** + +- **`git status`** + - Shows the current state of your working directory and the staging area. It tells you which files are staged, unstaged, and untracked. + +--- + +#### 2. Committing Changes (`git commit`) + +Once your changes are staged, you can record them as a new snapshot in the repository's history using a commit. Each commit should represent a logical unit of work. + +- **`git commit -m "Your descriptive commit message"`** + - Creates a new commit with the staged changes. The `-m` flag allows you to provide a short, descriptive message directly in the command line. + - **Good commit messages are crucial!** They explain _what_ changes were made and _why_. + - Example: `git commit -m "Add user authentication feature"` +- **`git commit`** + - Opens your default text editor (like Vim or Nano) to allow you to write a more detailed commit message. This is useful for longer explanations or when following a specific commit message convention. + +--- + +#### 3. Pushing Changes (`git push`) + +After committing your changes locally, you'll often want to share them with a remote repository (e.g., GitHub, GitLab, Bitbucket). This is done using `git push`. + +- **`git push `** + - Pushes your committed changes from your local branch to a specific remote branch. + - **Common usage:** `git push origin main` (where `origin` is the default name for your remote and `main` is the primary development branch). +- **`git push -u `** (or `git push --set-upstream`) + - This is typically used the _first time_ you push a new local branch to a remote. It sets up the "upstream" tracking relationship, meaning Git will remember that your local branch is connected to that remote branch. After this, you can often just use `git push`. + - Example: `git push -u origin feature/new-design` +- **`git push`** + - If your local branch is already tracking a remote branch (i.e., you've used `-u` before or cloned a repository), simply running `git push` will push your changes to the tracked remote branch. + +--- + +#### 4. Pulling Changes (`git pull`) + +When working with others, or even on different machines, you'll need to get the latest changes from the remote repository to your local machine. This is done using `git pull`. + +- **`git pull `** + - Fetches changes from the specified remote branch and then automatically merges them into your current local branch. + - **Common usage:** `git pull origin main` +- **`git pull`** + - If your current local branch is tracking a remote branch, simply running `git pull` will fetch and merge changes from its tracked upstream branch. + +**Note:** `git pull` is essentially a shortcut for two other commands: + +1. **`git fetch `**: Downloads commits, files, and refs from a remote repository into your local repository, but _doesn't_ automatically merge them. +2. **`git merge /`**: Merges the fetched changes into your current branch. + +--- + +### Basic Workflow Summary: + +1. **Modify files.** +2. **`git status`**: Check what you've changed. +3. **`git add .`**: Stage your changes. +4. **`git commit -m "Your descriptive message"`**: Commit your staged changes. +5. **`git pull origin main`**: Get the latest changes from the remote (to avoid merge conflicts later). +6. **`git push origin main`**: Share your committed changes with the remote. + + +# Essential Git Commands for Common Problems + +This guide covers basic Git commands to help you handle common challenges like merge conflicts, overwriting changes, and navigating commit history. + +## Basic Commands + +```bash +# Check status of your repository +git status + +# Check commit history +git log +git log --oneline --graph --decorate # More visual representation + +# View changes before committing +git diff +git diff --staged # View staged changes +``` + +## Handling Merge Conflicts + +When your branch falls behind and you encounter conflicts: + +```bash +# Update your local repository with remote changes +git fetch origin + +# Merge changes from origin/main to your current branch +git merge origin/main + +# If conflicts occur, Git will tell you which files are in conflict +# Edit the files manually to resolve conflicts, then: +git add +git commit -m "Resolve merge conflicts" + +# Alternative: abort the merge if needed +git merge --abort +``` + +## Force Your Version as the Latest + +When you want your version to override others: + +```bash +# Force push your changes (use with caution!) +git push --force origin + +# A safer alternative: force-with-lease checks if remote has new changes +git push --force-with-lease origin + +# Overwrite local changes with remote changes +git reset --hard origin/ + +# Overwrite a single file with the version from another branch +git checkout -- +``` + +## Going Back to a Specific Commit + +```bash +# Move back to a specific commit without changing files (detached HEAD) +git checkout + +# Reset your branch to a specific commit (will lose later commits) +git reset --hard + +# Create a new commit that undoes changes from a previous commit +git revert +``` + +## Branch Management + +```bash +# Create and switch to a new branch +git checkout -b + +# Switch to an existing branch +git checkout + +# List all branches +git branch # Local branches +git branch -r # Remote branches +git branch -a # All branches + +# Delete a branch +git branch -d # Safe delete (prevents deleting unmerged changes) +git branch -D # Force delete +``` + +## Stashing Changes + +Useful when you need to switch branches but aren't ready to commit: + +```bash +# Save changes to the stash +git stash save "Your stash message" + +# List stashes +git stash list + +# Apply the most recent stash without removing it +git stash apply + +# Apply a specific stash +git stash apply stash@{n} + +# Apply and remove the most recent stash +git stash pop + +# Remove a stash +git stash drop stash@{n} + +# Clear all stashes +git stash clear +``` + +## Fixing Mistakes + +```bash +# Amend the last commit message +git commit --amend -m "New commit message" + +# Add forgotten files to the last commit +git add +git commit --amend --no-edit + +# Undo staging of files +git reset + +# Discard changes in working directory +git checkout -- +git restore # In newer Git versions +``` + +## Advanced Techniques + +```bash +# Interactive rebase to edit, squash, or reorder commits +git rebase -i HEAD~n # Where n is the number of commits to go back + +# Cherry-pick specific commits from another branch +git cherry-pick + +# Cleanup unnecessary files +git clean -n # Dry run - shows what would be deleted +git clean -f # Actually delete the files + +# Temporarily save changes from a dirty working directory +git worktree add +``` + +## Safety Tips + +1. **Always create backups** before performing destructive operations +2. **Use `--dry-run`** when available to preview command effects +3. **Avoid force push** on shared branches (especially main/master) +4. Set up **aliases** for complex commands you use frequently +5. Configure Git to **require confirmation** for potentially harmful actions + +Remember that Git preserves history in the `.git` directory, so most "destructive" commands can be undone, but it's better to be cautious. \ No newline at end of file diff --git a/01-Documentation/GIT/Git - Start New Repository with Visual Studio Code - VS Code.md b/01-Documentation/GIT - GitHub/Git - Start New Repository with Visual Studio Code - VS Code.md similarity index 100% rename from 01-Documentation/GIT/Git - Start New Repository with Visual Studio Code - VS Code.md rename to 01-Documentation/GIT - GitHub/Git - Start New Repository with Visual Studio Code - VS Code.md diff --git a/01-Documentation/GIT - GitHub/GitHub Privacy.md b/01-Documentation/GIT - GitHub/GitHub Privacy.md new file mode 100644 index 0000000..f0b59c5 --- /dev/null +++ b/01-Documentation/GIT - GitHub/GitHub Privacy.md @@ -0,0 +1,71 @@ +*** + +[About repositories - GitHub Docs](https://docs.github.com/en/repositories/creating-and-managing-repositories/about-repositories) + + +## [About repositories](https://docs.github.com/en/repositories/creating-and-managing-repositories/about-repositories#about-repositories) + +A repository is the most basic element of GitHub. It's a place where you can store your code, your files, and each file's revision history. Repositories can have multiple collaborators and can be either public or private. + +To create a new repository, go to [https://github.com/new](https://github.com/new). For instructions, see [Quickstart for repositories](https://docs.github.com/en/repositories/creating-and-managing-repositories/quickstart-for-repositories). + +## [Repository terminology](https://docs.github.com/en/repositories/creating-and-managing-repositories/about-repositories#repository-terminology) + +Before getting started with repositories, learn these important terms. + +|Term|Definition| +|---|---| +|Branch|A parallel version of your code that is contained within the repository, but does not affect the primary or main branch.| +|Clone|To download a full copy of a repository's data from GitHub.com, including all versions of every file and folder.| +|Fork|A new repository that shares code and visibility settings with the original "upstream" repository.| +|Merge|To take the changes from one branch and apply them to another.| +|Pull request|A request to merge changes from one branch into another.| +|Remote|A repository stored on GitHub, not on your computer.| +|Upstream|The branch on an original repository that has been forked or cloned. The corresponding branch on the cloned or forked repository is called the "downstream."| + +## [About repository ownership](https://docs.github.com/en/repositories/creating-and-managing-repositories/about-repositories#about-repository-ownership) + +You can own repositories individually, or you can share ownership of repositories with other people in an organization. + +In either case, access to repositories is managed by permissions. For more information, see [Permission levels for a personal account repository](https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-personal-account-settings/permission-levels-for-a-personal-account-repository) and [Repository roles for an organization](https://docs.github.com/en/organizations/managing-user-access-to-your-organizations-repositories/managing-repository-roles/repository-roles-for-an-organization). + +## [About collaboration](https://docs.github.com/en/repositories/creating-and-managing-repositories/about-repositories#about-collaboration) + +You can use repositories to manage your work and collaborate with others. + +- You can use issues to collect user feedback, report software bugs, and organize tasks you'd like to accomplish. For more information, see [About issues](https://docs.github.com/en/issues/tracking-your-work-with-issues/about-issues). +- You can use GitHub Discussions to ask and answer questions, share information, make announcements, and conduct or participate in conversations about a project. For more information, see [About discussions](https://docs.github.com/en/discussions/collaborating-with-your-community-using-discussions/about-discussions). +- You can use pull requests to propose changes to a repository. For more information, see [About pull requests](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests). +- You can use Projects to organize and prioritize your issues and pull requests. For more information, see [About Projects](https://docs.github.com/en/issues/planning-and-tracking-with-projects/learning-about-projects/about-projects). + +With GitHub Free for personal accounts and organizations, you can work with unlimited collaborators on unlimited public repositories with a full feature set, or unlimited private repositories with a limited feature set. To get advanced tooling for private repositories, you can upgrade to GitHub Pro, GitHub Team, or GitHub Enterprise Cloud. For more information, see [GitHub’s plans](https://docs.github.com/en/get-started/learning-about-github/githubs-plans). + +## [About repository visibility](https://docs.github.com/en/repositories/creating-and-managing-repositories/about-repositories#about-repository-visibility) + +You can restrict who has access to a repository by choosing a repository's visibility: public or private. + +When you create a repository, you can choose to make the repository public or private. Repositories in organizations that use GitHub Enterprise Cloud and are owned by an enterprise account can also be created with internal visibility. For more information, see [the GitHub Enterprise Cloud documentation](https://docs.github.com/en/enterprise-cloud@latest/repositories/creating-and-managing-repositories/about-repositories). + +- Public repositories are accessible to everyone on the internet. +- Private repositories are only accessible to you, people you explicitly share access with, and, for organization repositories, certain organization members. + +### [Security considerations for repository visibility](https://docs.github.com/en/repositories/creating-and-managing-repositories/about-repositories#security-considerations-for-repository-visibility) + +Public repositories expose your codebase to everyone, increasing the risk that attackers might exploit vulnerabilities or access sensitive information. You can mitigate these risks by enabling GitHub security features such as Dependabot, secret scanning, push protection, and code scanning for the repository. Additionally, you should add a security policy (a `SECURITY.md` file) to your repository, that outlines how vulnerabilities should be reported, to ensure that potential threats are addressed efficiently. + +Although private repositories restrict access to authorized users, it's still essential to implement strong access controls, multi-factor authentication, and regular audits to mitigate risks. + +For more information, see [Quickstart for securing your repository](https://docs.github.com/en/code-security/getting-started/quickstart-for-securing-your-repository). + +Organization owners always have access to every repository created in an organization. For more information, see [Repository roles for an organization](https://docs.github.com/en/organizations/managing-user-access-to-your-organizations-repositories/managing-repository-roles/repository-roles-for-an-organization). + +People with admin permissions for a repository can change an existing repository's visibility. For more information, see [Setting repository visibility](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/managing-repository-settings/setting-repository-visibility). + +## [Next steps](https://docs.github.com/en/repositories/creating-and-managing-repositories/about-repositories#next-steps) + +Here are some helpful resources for taking your next steps with repositories. + +- [Best practices for repositories](https://docs.github.com/en/repositories/creating-and-managing-repositories/best-practices-for-repositories): Learn how to use repositories most effectively. +- [Creating a new repository](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository): Create a new repository. +- [Creating and deleting branches within your repository](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-and-deleting-branches-within-your-repository): Learn how to create and delete branches within your repository. +- [Creating a pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request): Create a pull request to propose and collaborate on changes to a repository. \ No newline at end of file diff --git a/01-Documentation/GIT/Notes - Git - Gitea.md b/01-Documentation/GIT - GitHub/Notes - Git - Gitea.md similarity index 100% rename from 01-Documentation/GIT/Notes - Git - Gitea.md rename to 01-Documentation/GIT - GitHub/Notes - Git - Gitea.md diff --git a/01-Documentation/GIT/adjuntos/Pasted image 20240422224641.png b/01-Documentation/GIT - GitHub/adjuntos/Pasted image 20240422224641.png similarity index 100% rename from 01-Documentation/GIT/adjuntos/Pasted image 20240422224641.png rename to 01-Documentation/GIT - GitHub/adjuntos/Pasted image 20240422224641.png diff --git a/01-Documentation/GIT/adjuntos/Pasted image 20240422224651.png b/01-Documentation/GIT - GitHub/adjuntos/Pasted image 20240422224651.png similarity index 100% rename from 01-Documentation/GIT/adjuntos/Pasted image 20240422224651.png rename to 01-Documentation/GIT - GitHub/adjuntos/Pasted image 20240422224651.png diff --git a/01-Documentation/GIT/adjuntos/Pasted image 20250331130643.png b/01-Documentation/GIT - GitHub/adjuntos/Pasted image 20250331130643.png similarity index 100% rename from 01-Documentation/GIT/adjuntos/Pasted image 20250331130643.png rename to 01-Documentation/GIT - GitHub/adjuntos/Pasted image 20250331130643.png diff --git a/01-Documentation/GIT/adjuntos/Pasted image 20250331130826.png b/01-Documentation/GIT - GitHub/adjuntos/Pasted image 20250331130826.png similarity index 100% rename from 01-Documentation/GIT/adjuntos/Pasted image 20250331130826.png rename to 01-Documentation/GIT - GitHub/adjuntos/Pasted image 20250331130826.png diff --git a/01-Documentation/GIT/adjuntos/Pasted image 20250331131244.png b/01-Documentation/GIT - GitHub/adjuntos/Pasted image 20250331131244.png similarity index 100% rename from 01-Documentation/GIT/adjuntos/Pasted image 20250331131244.png rename to 01-Documentation/GIT - GitHub/adjuntos/Pasted image 20250331131244.png diff --git a/01-Documentation/GIT/adjuntos/Pasted image 20250331131430.png b/01-Documentation/GIT - GitHub/adjuntos/Pasted image 20250331131430.png similarity index 100% rename from 01-Documentation/GIT/adjuntos/Pasted image 20250331131430.png rename to 01-Documentation/GIT - GitHub/adjuntos/Pasted image 20250331131430.png diff --git a/01-Documentation/GIT/GIT commands HELP.md b/01-Documentation/GIT/GIT commands HELP.md deleted file mode 100644 index a45b988..0000000 --- a/01-Documentation/GIT/GIT commands HELP.md +++ /dev/null @@ -1,161 +0,0 @@ - -# Essential Git Commands for Common Problems - -This guide covers basic Git commands to help you handle common challenges like merge conflicts, overwriting changes, and navigating commit history. - -## Basic Commands - -```bash -# Check status of your repository -git status - -# Check commit history -git log -git log --oneline --graph --decorate # More visual representation - -# View changes before committing -git diff -git diff --staged # View staged changes -``` - -## Handling Merge Conflicts - -When your branch falls behind and you encounter conflicts: - -```bash -# Update your local repository with remote changes -git fetch origin - -# Merge changes from origin/main to your current branch -git merge origin/main - -# If conflicts occur, Git will tell you which files are in conflict -# Edit the files manually to resolve conflicts, then: -git add -git commit -m "Resolve merge conflicts" - -# Alternative: abort the merge if needed -git merge --abort -``` - -## Force Your Version as the Latest - -When you want your version to override others: - -```bash -# Force push your changes (use with caution!) -git push --force origin - -# A safer alternative: force-with-lease checks if remote has new changes -git push --force-with-lease origin - -# Overwrite local changes with remote changes -git reset --hard origin/ - -# Overwrite a single file with the version from another branch -git checkout -- -``` - -## Going Back to a Specific Commit - -```bash -# Move back to a specific commit without changing files (detached HEAD) -git checkout - -# Reset your branch to a specific commit (will lose later commits) -git reset --hard - -# Create a new commit that undoes changes from a previous commit -git revert -``` - -## Branch Management - -```bash -# Create and switch to a new branch -git checkout -b - -# Switch to an existing branch -git checkout - -# List all branches -git branch # Local branches -git branch -r # Remote branches -git branch -a # All branches - -# Delete a branch -git branch -d # Safe delete (prevents deleting unmerged changes) -git branch -D # Force delete -``` - -## Stashing Changes - -Useful when you need to switch branches but aren't ready to commit: - -```bash -# Save changes to the stash -git stash save "Your stash message" - -# List stashes -git stash list - -# Apply the most recent stash without removing it -git stash apply - -# Apply a specific stash -git stash apply stash@{n} - -# Apply and remove the most recent stash -git stash pop - -# Remove a stash -git stash drop stash@{n} - -# Clear all stashes -git stash clear -``` - -## Fixing Mistakes - -```bash -# Amend the last commit message -git commit --amend -m "New commit message" - -# Add forgotten files to the last commit -git add -git commit --amend --no-edit - -# Undo staging of files -git reset - -# Discard changes in working directory -git checkout -- -git restore # In newer Git versions -``` - -## Advanced Techniques - -```bash -# Interactive rebase to edit, squash, or reorder commits -git rebase -i HEAD~n # Where n is the number of commits to go back - -# Cherry-pick specific commits from another branch -git cherry-pick - -# Cleanup unnecessary files -git clean -n # Dry run - shows what would be deleted -git clean -f # Actually delete the files - -# Temporarily save changes from a dirty working directory -git worktree add -``` - -## Safety Tips - -1. **Always create backups** before performing destructive operations -2. **Use `--dry-run`** when available to preview command effects -3. **Avoid force push** on shared branches (especially main/master) -4. Set up **aliases** for complex commands you use frequently -5. Configure Git to **require confirmation** for potentially harmful actions - -Remember that Git preserves history in the `.git` directory, so most "destructive" commands can be undone, but it's better to be cautious. \ No newline at end of file diff --git a/01-Documentation/Siemens/PLC Siemens/S7-300 - TCON - TRCV.md b/01-Documentation/Siemens/PLC Siemens/S7-300 - TCON - TRCV.md new file mode 100644 index 0000000..6f2fbdd --- /dev/null +++ b/01-Documentation/Siemens/PLC Siemens/S7-300 - TCON - TRCV.md @@ -0,0 +1,263 @@ + +[TIA Portal Information System](https://docs.tia.siemens.cloud/r/simatic_s7_1200_manual_collection_enus_20/communication/profinet/open-user-communication/legacy-tcon-tdiscon-tsend-and-trcv-instructions/legacy-tcon-tdiscon-tsend-and-trcv-tcp-communication-instructions) + +##### Legacy TCON, TDISCON, TSEND, and TRCV (TCP communication) instructions + +## Ethernet communication using TCP and ISO on TCP protocols + +**TSEND_C and TRCV_C instructions** + +To help simplify the programming of PROFINET/Ethernet communication, the TSEND_C instruction and the TRCV_C instruction combine the functionality of the TCON, TDISCON. TSEND and TRCV instructions: + +- TSEND_C combines the TCON, TDISCON and TSEND instructions. + +- TRCV_C combines the TCON, TDISCON and TRCV instructions. + + +The following instructions control the communication process: + +- TCON establishes the TCP/IP connection between the client and server (CPU) PC. + +- TSEND and TRCV send and receive data. + +- TDISCON breaks the connection. + + +The minimum size of data that you can transmit (TSEND) or receive (TRCV) is one byte; the maximum size is 8192 bytes. TSEND does not support the transmission of data from Boolean locations, and TRCV will not receive data into Boolean locations. For information transferring data with these instructions, see the section on [data consistency](https://docs.tia.siemens.cloud/r/urp2Ni2UpoHXhbA9nhgm6A/dDSAEcf_YTVb3G9mxvngEg?section=Xa82b0fd901da8408ecc0617160b6d748). + +TCON, TDISCON, TSEND, and TRCV operate asynchronously, which means that the job processing extends over multiple instruction executions. For example, you start a job for setting up and establishing a connection by executing an instruction TCON with parameter REQ = 1. Then you use additional TCON executions to monitor the job progress and test for job completion with parameter DONE. + +The following table shows the relationships between BUSY, DONE, and ERROR. Use the table to determine the current job status: + +Table 1. Interactions between the BUSY, DONE, and ERROR parameters + +|**BUSY**|**DONE**|**ERROR**|**Description**| +|---|---|---|---| +|TRUE|irrelevant|irrelevant|The job is being processed.| +|FALSE|TRUE|FALSE|The job successfully completed.| +|FALSE|FALSE|TRUE|The job was ended with an error. The cause of the error can be found in the STATUS parameter.| +|FALSE|FALSE|FALSE|A new job was not assigned.| + +## TCON and TDISCON + +**Initializing the communication parameters** + +After you insert the TCON instruction, use the "Properties" [of the instruction](https://docs.tia.siemens.cloud/r/urp2Ni2UpoHXhbA9nhgm6A/CLsx~nNktyNdibGD2_lT0Q?section=Xeaa36c725c70d540b0a193594ac50844) to configure the [communication parameters](https://docs.tia.siemens.cloud/r/urp2Ni2UpoHXhbA9nhgm6A/4KPJfLxRtqynTXLM0pgSaQ?section=X868ef9f6da288ebcc92dd27a15c9077b). As you enter the parameters for the communication partners in the inspector window, STEP 7 enters the corresponding data in the instance DB for the instruction. + +If you want to use a multi-instance DB, you must configure the DB on both CPUs. + +Table 2. TCON and TDISCON instructions + +|**LAD / FBD**||**Description**| +|---|---|---| +|![](https://docs.tia.siemens.cloud/api/khub/maps/urp2Ni2UpoHXhbA9nhgm6A/resources/WFBN5NeTJc072Q9jyl~KQw-urp2Ni2UpoHXhbA9nhgm6A/content?v=372c22d8e2aefdab&Ft-Calling-App=ft/turnkey-portal)|**"TCON_DB"(    req:=_bool_in_,    ID:=_undef_in_,    done=>_bool_out_,    busy=>_bool_out_,    error=>_bool_out_,    status=>_word_out_,    connect:=_struct_inout_);**|TCP and ISO on TCP: TCON initiates a communications connection from the CPU to a communication partner.| +|![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEkAAABpCAIAAAD5vZm9AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH2QIUEBMy6UDHjQAAAAd0RVh0QXV0aG9yAKmuzEgAAAAMdEVYdERlc2NyaXB0aW9uABMJISMAAAAKdEVYdENvcHlyaWdodACsD8w6AAAADnRFWHRDcmVhdGlvbiB0aW1lADX3DwkAAAAJdEVYdFNvZnR3YXJlAF1w/zoAAAALdEVYdERpc2NsYWltZXIAt8C0jwAAAAh0RVh0V2FybmluZwDAG+aHAAAAB3RFWHRTb3VyY2UA9f+D6wAAAAh0RVh0Q29tbWVudAD2zJa/AAAABnRFWHRUaXRsZQCo7tInAAABAElEQVR4nO18eXgVRdb3qeq975IdxCQISUD2EBZDWEQQQRTRF3AEVBSQVRYVcUNHnMEFFEUQBBTRUXFD4HVEVETEAQHZiRCSQEAgkIUsd+u+vVTV90cndzBcILJ83/fO856Hh9Stru6q01V1zu8s1YgxBv+hhP9fD+Aq0n8yb3x9Gvn9/lAo1LBhw9LSUtM0jx075nK5AoFAVlZWbGzs2S0LCgpOnTrFGOvVqxcAMMaOHz+ekpLCcdzu3bt9Pl/nzp3dbjcAHD169NixYwCQnZ2tqmpVVdXevXsBoEWLFo0aNaqqqgKAuLg4ACgpKVEUJSYm5s/yxs2cOfOijdatW7dixYqb3H+kIwAAAQBJREFUbrppypQpDRs2XLZs2euvv65pWmZmZmJi4tktBw8efOTIkby8vGPHjmVnZ9u2PWrUqEGDBm3dunXZsmW5ubl79uzJysoqKipauHDh7t27c3NzDx065HK5VqxYsXnz5tzc3H379mVkZBw8eHDChAm33HKL1+udOXOmpmlt2rT5s7zVa944jhMEAQDC4fBtt93WtWvXiRMnvvPOO3WaMcYSEhKWLVsmiuLSpUvfeOONRx99FABkWZ4/f/5f//rXtm3bbtu2DWO8evXqjIyMyZMnA8DWrVv3799/6tQp54EzZszYvn17u3btfv755127dqWkpCCE/ixXDtVrv918881PP5J79lcAAAEASURBVP20LMuLFi0CgOrqatu2z9e4uroaAHr27LllyxYAwBhTStu3b79p06b169dnZ2fHxsZyHEcpddrn5OSkpqZGxDVCSBTFioqK8ePHf/vtt5RSWZYvjb168aaqalxcHEIoKSmpns81DEOWZaccCARmzJhRXV29atWqWbNmVVdXS5J0dmNKaZ3RE0Li4+NzcnK++uqrOo3rT1dYTiKEHFERDAZFUYzUh0KhZ5999u23387NzS0uLkYIcRznXAqHw7qun61mbdtGCOm6PmLEiOLi4mXLltWRWPWkeu23OkQI8fv9US+VlpauWbMmNjZ248aNM2fOdFoqirJ8+XLGWOPGjWO2TZfwAAABAElEQVRjYz0eT0pKyq5du7755hsA2LFjR/PmzUVRdH4GAoGkpKRQKOR0ceONNz766KOWZV3COOslJ88lSZIyMzPrVCKEAoHA/v37CwsLH3/88dTUVGdTtWnT5oYbbvjuu+/27Nnz0EMPtWzZsnXr1iUlJRs3biwsLBw6dGjfvn09Hs/q1asLCwv79evXr1+/cDjcoEGDFi1aNGzYsFOnTsnJyddcc82fHSS6HMwVDAanTp2q67rzc/jw4QMGDLjkp12ALMuaOHFiKBRyfg4dO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Kr7pyxSefYYwoZcAAc4hSxhjjOMwYYxQwB5QCY4zjao7D4H8XsBNR4DgEzDlNhxhATQ0AIQxjhGoO2iFAtTUIUUIRRggBJcwpnHMJUUIBIYwRJQwQ8Dx3/MTpoUNuP5eRKPuNMWaaFiF27TcS6jcX/zcLZw8JmJPbWC/e/mPoP/kbH//L2/9M+j+oUXCaNS7hRwAAAABJRU5ErkJggg==)|**"TDISCON_DB"(    req:=_bool_in_,    ID:=_word_in_,    done=>_bool_out_,    busy=>_bool_out_,    error=>_bool_out_,    status=>_word_out_);**|TCP and ISO on TCP: TDISCON terminates a communications connection from the CPU to a communication partner.| + +1 STEP 7 automatically creates the DB when you insert the instruction. + +Table 3. Data types for the parameters of TCON and TDISCON + +|**Parameter and type**| |**Data type**|**Description**| +|---|---|---|---| +|REQ|IN|Bool|Control parameter REQ starts the job by establishing the connection specified by ID. The job starts at rising edge.| +|ID|IN|CONN_OUC (Word)|Reference to the connection to be established (TCON) or terminated (TDISCON) to the remote partner, or between the user program and the communication layer of the operating system. The ID must be identical to the associated parameter ID in the local connection description.

Value range: W#16#0001 to W#16#0FFF| +|CONNECT

(TCON)|IN_OUT|TCON_Param|Pointer to the [connection description](https://docs.tia.siemens.cloud/r/urp2Ni2UpoHXhbA9nhgm6A/4KPJfLxRtqynTXLM0pgSaQ?section=X868ef9f6da288ebcc92dd27a15c9077b)| +|DONE|OUT|Bool|- 0: Job is not yet started or still running.

- 1: Job completed without error.| +|BUSY|OUT|Bool|- 0: Job is completed.

- 1: Job is not yet completed. A new job cannot be triggered.| +|ERROR|OUT|Bool|Status parameters with the following values:

- 0: No error

- 1: Error occurred during processing. STATUS provides detailed information on the type of error.| +|STATUS|OUT|Word|Status information including error information. (Refer to the Error and Status condition codes in the table below.)| + +Both communication partners execute the TCON instruction to set up and establish the communication connection. You use parameters to specify the active and passive communication end point partners. After the connection is set up and established, it is automatically maintained and monitored by the CPU. + +If the connection is terminated due to a line break or due to the remote communications partner, for example, the active partner attempts to re-establish the configured connection. You do not have to execute TCON again. + +An existing connection is terminated and the set-up connection is removed when the TDISCON instruction is executed or when the CPU has gone into STOP mode. To set up and re-establish the connection, you must execute TCON again. + +Table 4. ERROR and STATUS condition codes for TCON and TDISCON + +|**ERROR**|**STATUS**|**Description**| +|---|---|---| +|0|0000|Connection was established successfully.| +|0|7000|No job processing active| +|0|7001|Start job processing; establishing connection (TCON) or terminating connection (TDISCON)| +|0|7002|Follow-on call (REQ irrelevant); establishing connection (TCON) or terminating connection (TDISCON)| +|1|8086|The ID parameter is outside the permitted address range.| +|1|8087|TCON: Maximum number of connections reached; no additional connection possible.| +|1|809B|TCON: The local_device_id in the connection description does not match the CPU.| +|1|80A1|TCON: Connection or port is already occupied by user.| +|1|80A2|TCON: Local or remote port is occupied by the system.| +|1|80A3|Attempt being made to re-establish an existing connection (TCON) or terminate a non-existent connection (TDISCON).| +|1|80A4|TCON: IP address of the remote connection end point is invalid; it matches the local partner IP address.| +|1|80A5|TCON: [Connection ID](https://docs.tia.siemens.cloud/r/urp2Ni2UpoHXhbA9nhgm6A/AiaqbJ3fPz_2I_Z5TqS7_A?section=X165441a807731573ccb8da0261c2da70) is already in use.| +|1|80A7|TCON: Communications error: You executed a TDISCON before the TCON completed. The TDISCON must first completely terminate the connection referenced by the ID.| +|1|80B2|TCON: The CONNECT parameter points to a data block that was generated with the attribute "Only store in load memory".| +|1|80B4|TCON: When using the ISO on TCP (connection_type = B#16#12) to establish a passive connection, condition code 80B4 alerts you that the TSAP entered did not conform to one of the following address requirements:

- For a local TSAP length of 2 and a TSAP ID value of either E0 or E1 (hexadecimal) for the first byte, the second byte must be either 00 or 01.

- For a local TSAP length of 3 or greater and a TSAP ID value of either E0 or E1 (hexadecimal) for the first byte, the second byte must be either 00 or 01 and all other bytes must be valid ASCII characters.

- For a local TSAP length of 3 or greater and the first byte of the TSAP ID does not have a value of either E0 or E1 (hexadecimal), then all bytes of the TSAP ID must be valid ASCII characters.


Valid ASCII characters are byte values from 20 to 7E (hexadecimal).| +|1|80B5|TCON: Connection type "13 = UDP" permits only passive connection establishment.| +|1|80B6|TCON: Parameter assignment error in CONNECTION_TYPE parameter of the SDT TCON_Param.| +|1|80B7|TCON: Error in one of the following parameters of the data block for connection description:

- block_length

- local_tsap_id_len

- rem_subnet_id_len

- rem_staddr_len

- rem_tsap_id_len

- next_staddr_len


Note: When operating TCON in TCP passive mode, the LOCAL_TSAP_ID_LEN must be "2" and the REM_TSAP_ID_LEN must be "0".| +|1|80B8|TCON: Parameter in the local connection description and Parameter ID are different.| +|1|80C3|TCON: All connection resources are in use.| +|1|80C4|Temporary communications error:

- The connection cannot be established at this time (TCON).

- The configured connection is currently being removed by TDISCON (TCON).

- The connection is currently being established (TDISCON).

- The interface is receiving new parameters (TCON and TDISCON).| + +## TSEND and TRCV + +When using PROFINET Open User communication, if you execute a TSEND instruction without a corresponding TRCV instruction executing on the remote device, then the TSEND instruction may reside indefinitely in a "Busy State", waiting for the TRCV instruction to receive the data. In this state, the TSEND instruction "Busy" output is set, and the "Status" output has a value of "0x7002". This condition may occur if you are transferring more than 4096 bytes of data. The issue is resolved at the next execution of the TRCV instruction. + +Table 5. TSEND and TRCV instructions + +|**LAD / FBD**|**SCL**|**Description**| +|---|---|---| +|![](https://docs.tia.siemens.cloud/api/khub/maps/urp2Ni2UpoHXhbA9nhgm6A/resources/fd269UI1wp7RH_m5ICwCTw-urp2Ni2UpoHXhbA9nhgm6A/content?v=21e92f0324020930&Ft-Calling-App=ft/turnkey-portal)|**"TSEND_DB"(    req:=_bool_in_,    ID:=_word_in_,    len:=_udint_in_,    done=>_bool_out_,    busy=>_bool_out_,    error=>_bool_out_,    status=>_word_out_,    data:=_variant_inout_);**|TCP and ISO on TCP: TSEND sends data through a communication connection from the CPU to a partner station.| +|![](https://docs.tia.siemens.cloud/api/khub/maps/urp2Ni2UpoHXhbA9nhgm6A/resources/wwjoDJ0uf3nNj4NnGpnPvQ-urp2Ni2UpoHXhbA9nhgm6A/content?v=a3cb3a30427a5b33&Ft-Calling-App=ft/turnkey-portal)|**"TRCV_DB"(     en_r:=_bool_in_,    ID:=_word_in_,    len:=_udint_in_,    ndr=>_bool_out_,    busy=>_bool_out_,    error=>_bool_out_,    status=>_word_out_,    rcvd_len=>_udint_out_,    data:=_variant_inout_);**|TCP and ISO on TCP: TRCV receives data through a communication connection from a partner station to the CPU.| + +1 STEP 7 automatically creates the DB when you insert the instruction. + +Table 6. Data types for the parameters of TSEND and TRCV + +|**Parameter and type**| |**Data type**|**Description**| +|---|---|---|---| +|REQ|IN|Bool|TSEND: Starts the send job on a rising edge. The data is transferred from the area specified by DATA and LEN.| +|EN_R|IN|Bool|TRCV: Enables the CPU to receive; with EN_R = 1, the TRCV is ready to receive. The receive job is processed.| +|ID|IN|CONN_OUC (Word)|Reference to the associated connection. ID must be identical to the associated parameter ID in the local connection description.

Value range: W#16#0001 to W#16#0FFF| +|LEN|IN|UInt|Maximum number of bytes to be sent (TSEND) or received (TRCV):

- Default = 0: The DATA parameter determines the length of the data to be sent (TSEND) or received (TRCV).

- Ad hoc mode = 65535: A variable length of data is set for reception (TRCV).| +|DATA|IN_OUT|Variant|Pointer to send (TSEND) or receive (TRCV) data area; data area contains the address and length. The address refers to I memory, Q memory, M memory, or a DB.| +|DONE|OUT|Bool|TSEND:

- 0: Job not yet started or still running.

- 1: Job executed without error.| +|NDR|OUT|Bool|TRCV:

- NDR = 0: Job not yet started or still running.

- NDR = 1: Job successfully completed.| +|BUSY|OUT|Bool|- BUSY = 1: The job is not yet complete. A new job cannot be triggered.

- BUSY = 0: Job is complete.| +|ERROR|OUT|Bool|ERROR = 1: Error occurred during processing. STATUS provides detailed information on the type of error| +|STATUS|OUT|Word|Status information including error information. (Refer to the Error and Status condition codes in the table below.)| +|RCVD_LEN|OUT|Int|TRCV: Amount of data actually received in bytes| + +The TSEND instruction requires a low-to-high transition at the REQ input parameter to start a send job. The BUSY parameter is then set to 1 during processing. Completion of the send job is indicated by either the DONE or ERROR parameters being set to 1 for one scan. During this time, any low-to-high transition at the REQ input parameter is ignored. + +## TRCV Operations + +The TRCV instruction writes the received data to a receive area that is specified by the following two variables: + +- Pointer to the start of the area + +- Length of the area or the value supplied at the LEN input if not 0 + + The default setting of the LEN parameter (LEN = 0) uses the DATA parameter to determine the length of the data being transmitted. It is recommended that the data transmitted by the TSEND instruction be the same size as the DATA parameter of the TRCV instruction. + + If using the default setting of the LEN parameter and it is necessary to send the data in segments smaller than the DATA parameter size, the following applies. It is recommended to keep the EN_R bit high until the corresponding TSEND transfers the appropriate amount of data to fill the TRCV DATA parameter. If the size of the data transmitted from TSEND does not equal the TRCV DATA parameter size, TRCV remains in a busy status (status code: 7002) while the EN_R bit is high until the overall size of the data transmitted from TSEND equals the TRCV DATA parameter size. If the EN_R bit of TRCV is pulsed, it needs to be pulsed the same number of times as TSEND is executed to receive the data. + + The TRCV DATA parameter buffer does not display the new data received until the data size equals the DATA parameter buffer size. + + +As soon as all the job data has been received, TRCV transfers it to the receive area and sets NDR to 1. + +Table 7. Entering the data into the receive area + +|**Protocol variant**|**Entering the data in the receive area**|**Parameter 
"connection_type"**|**Value of the LEN parameter**|**Value of the RCVD_LEN parameter (bytes)**| +|---|---|---|---|---| +|TCP|Ad hoc mode|B#16#11|65535|1 to 1460| +|TCP|Data reception with specified length|B#16#11|0 (recommended) or 1 to 8192, except 65535|1 to 8192| +|ISO on TCP|Ad hoc mode|B#16#12|65535|1 to 1460| +|ISO on TCP|protocol-controlled|B#16#12|0 (recommended) or 1 to 8192, except 65535|1 to 8192| + +**Ad hoc mode** + +The "ad hoc mode" exists with the TCP and ISO on TCP protocol variants. You set "ad hoc mode" by assigning "65535" to the LEN parameter. The receive area is identical to the area formed by DATA. The length of the received data will be output to the parameter RCVD_LEN. Immediately after receiving a block of data, TRCV enters the data in the receive area and sets NDR to 1. + +If you store the data in an "optimized" DB (symbolic only), you can receive data only in arrays of Byte, Char, USInt, and SInt data types. + +**Importing of S7-300/400 STEP 7 projects containing "ad hoc mode" into the S7-1200** + +In S7-300/400 STEP 7 projects, "ad hoc mode" is selected by assigning "0" to the LEN parameter. In the S7-1200, you set "ad hoc mode" by assigning "65535" to the LEN parameter. + +If you import an S7-300/400 STEP 7 project containing "ad hoc mode" into the S7-1200, you must change the LEN parameter to "65535". + +## TSEND and TRCV Error and Status condition codes + +|**ERROR**|**STATUS**|**Description**| +|---|---|---| +|0|0000|- Send job completed without error (TSEND)

- New data accepted: The current length of the received data is shown in RCVD_LEN (TRCV).| +|0|7000|- No job processing active (TSEND)

- Block not ready to receive (TRCV)| +|0|7001|- Start of job processing, data being sent: During this processing the operating system accesses the data in the DATA send area (TSEND).

- Block is ready to receive, receive job was activated (TRCV).| +|0|7002|- Follow-on instruction execution (REQ irrelevant), job being processed: The operating system accesses the data in the DATA send area during this processing (TSEND).

- Follow-on instruction execution, receive job being processed: Data is written to the receive area during this processing. For this reason, an error could result in inconsistent data in the receive area (TRCV).| +|1|8085|- LEN parameter is greater than the largest permitted value (TSEND) and (TRCV).

- LEN or DATA parameter changed since the first instruction execution (TRCV).| +|1|8086|The ID parameter is not in the permitted address range.| +|1|8088|The LEN parameter is larger than the memory area specified in DATA.| +|1|80A1|Communications error:

- The specified connection has not yet established (TSEND and TRCV).

- The specified connection is currently being terminated. Transmission or a receive job over this connection is not possible (TSEND and TRCV).

- The interface is being reinitialized (TSEND).

- The interface is receiving new parameters (TRCV).| +|1|80C3|Internal lack of resources: A block with this ID is already being processed in a different priority class.| +|1|80C4|Temporary communications error:

- The connection to the communications partner cannot be established at this time.

- The interface is receiving new parameter settings, or the connection is currently being established.| + +## Connection Ethernet protocols + +Every CPU has an integrated PROFINET port, which supports standard PROFINET communications. The TSEND_C, TRCV_C, TSEND and TRCV instructions all support the TCP and ISO on TCP Ethernet protocols. + +Refer to "Device Configuration: [Configuring the Local/Partner connection path](https://docs.tia.siemens.cloud/r/urp2Ni2UpoHXhbA9nhgm6A/CLsx~nNktyNdibGD2_lT0Q?section=Xeaa36c725c70d540b0a193594ac50844)" for more information. + + +# Terminating a Connection with FB 66 "TDISCON" + +Use with TCP and ISO on TCP + +FB 66 "TDISCON" terminates a communications connection from the CPU to a communications partner. + +Use with UDP + +The FB 66 "TDISCON" closes the local communications access point. The connection between the user program and the communications level of the operating system is terminated. + +Function + +FB 66 "TDISCON" is an asynchronously functioning FB, which means that its job processing extends over several FB calls. To start the job for terminating a connection, call FB 66 with REQ = 1. + +After FB 66 "TDISCON" has been successfully called, the ID specified for FB 65"TCON" is no longer valid and thus cannot be used for sending or receiving. + +The job status is indicated at the output parameters RET_VAL and BUSY. STATUS corresponds to the RET_VAL output parameter of asynchronously functioning SFCs (see also [Meaning of REQ, RET_VAL and BUSY with asynchronously operating SFCs](REQ_RET_VAL_BUSY.htm)). + +The following table shows the relationships between BUSY, DONE and ERROR. Using this table, you can determine the current status of FB 66 or when the establishment of the connection is complete. + +| | | | | +|---|---|---|---| +|BUSY|DONE|ERROR|Description| +|TRUE|irrelevant|irrelevant|The job is being processed.| +|FALSE|TRUE|FALSE|The job was completed successfully.| +|FALSE|FALSE|TRUE|The job was ended with an error. The cause of the error can be found in the STATUS parameter.| +|FALSE|FALSE|FALSE|The FB was not assigned a (new) job.| + +Parameters + +| | | | | | +|---|---|---|---|---| +|Parameter|Declaration|Data Type|Memory Area|Description| +|REQ|INPUT|BOOL|I, Q, M, D, L|Control parameter REQUEST, starts the job for terminating the connection specified by the ID. The job is initiated on a rising edge.| +|ID|INPUT|WORD|M, D, constant|Reference to the connection to be terminated to the remote partner or between the user program and the communications level of the operating system. ID must be identical to the associated parameter ID in the local connection description.
Range of values: W#16#0001 to W#16#0FFF| +|DONE|OUTPUT|BOOL|I, Q, M, D, L|DONE status parameter:

- 0: Job not yet started or still running.

- 1: Job executed without error.| +|BUSY|OUTPUT|BOOL|I, Q, M, D, L|- BUSY = 1: Job is not yet completed.

- BUSY = 0: Job is completed.| +|ERROR|OUTPUT|BOOL|I, Q, M, D, L|ERROR status parameter:

- ERROR=1: Error occurred during processing. STATUS provides detailed information on the type of error| +|STATUS|OUTPUT|WORD|M, D|STATUS status parameter: Error information| + +Error Information + +| | | | +|---|---|---| +|ERROR|STATUS
(W#16#...)|Explanation| +|0|0000|Connection terminated successfully| +|0|7000|No job processing active| +|0|7001|Start of job processing, connection being terminated| +|0|7002|Follow-on call (REQ irrelevant ), connection being terminated| +|1|8086|The ID parameter is not in the permitted address range| +|1|80A3|Attempt being made to terminate a non-existent connection| +|1|80C4|Temporary communications error: The interface is receiving new parameters or the connection is currently being established or the H system is being connected and updated..| + +See also: + +[Assigning Parameters for Open Communications Connections with TCP and ISO on TCP](Projektierung_der_offenen_Kommunikationsverbindungen.htm) + +[Assigning Parameters for the Local Communications Access Point with UDP](Parametrierung_des_Kommunikationszugangspunkts_bei_UDP.htm) + +[Establishing a Connection with FB 65 "TCON"](FB_65.htm) + +[Sending Data via TCP and ISO on TCP with FB 63 "TSEND"](FB_63.htm) + +[Receiving Data via TCP and ISO on TCP with FB 64 "TRCV"](FB_64.htm) + +[Sending Data via UDP with FB 67 "TUSEND"](FB_67.htm) + +[Receiving Data via UDP with FB 68 "TURCV"](FB_68.htm) + + + diff --git a/03-VM/44 - 98050 - Fiera/Progetto 98050 Fiera - Tavolo di accumulo.md b/03-VM/44 - 98050 - Fiera/Progetto 98050 Fiera - Tavolo di accumulo.md new file mode 100644 index 0000000..95009ff --- /dev/null +++ b/03-VM/44 - 98050 - Fiera/Progetto 98050 Fiera - Tavolo di accumulo.md @@ -0,0 +1,57 @@ +*** + +Il progetto coinvolge un trasporto di bottiglie ad anello con i seguenti elementi: +* divider ad alta velocità +* combiner per unificare i canali all'uscita del divider +* trasporto con guide motorizzate per cambio di formato +* tavolo di accumulo che permette di immagazzinare il formato non utilizzato. + * Il tavolo di accumulo conta con 4 file a destra e 4 a sinistra oltre alla fila centrale usata solo come bypass. + * Il tavolo può immagazzinare 2 formati, uno a destra e l'altro a sinistra. Quando si richiede un cambio di formato si carica il formato in corso e si scarica il nuovo formato. Una volta scaricato il formato in corso si attiva la modalità bypass. + * Per effettuare il cambio di formato, il tavolo ha 2 motori di cambio formato delle guide che aprono o chiudono le sponde e i dosatori. + * Per selezionare il canale di carico o scarico si utilizzano 2 motori minimotori, uno all'ingresso e l'altro all'uscita che permettono di modificare l'angolo delle sponde. Questo angolo deve essere caricato come parametro e ci sono 9 canali possibili. + + +### Tavolo di accumulo +*** +L'obiettivo del tavolo di accumulo è di immagazzinare il formato che non si sta usando. + + +Il lavoro avrà i seguenti obiettivi: +- Logica del tavolo di carico, scarico e bypass: gestione del cambio formato per il minimotor. Per semplicità, il tavolo è diviso in destra/sinistra e i formati possono essere solo su un lato. +- Logica dei motori ad anello e logica standard VM. +- L'HMI non sarà sviluppato in questa fase mi hai detto che se fa separatamente, ma verrà creato un simulatore per noi. +- Gestione delle ricette sull'HMI: inizialmente, si seguirà il piano concordato. Verranno create righe nel ricettario per ogni motore ad anello e per i dati del tavolo. Il cambio formato del tavolo inizierà solo dopo aver verificato che non ci siano più bottiglie sull'anello e che il modo carico sia attivo, con il divider e l'anello in automatico. +- Velocità: + - Velocità di bypass: dipende dal divider e dall'anello, non limitata dal tavolo. + - Velocità di carico/scarico: deve essere lenta per chiudere i buchi tra i cambi di canale del tavolo. Durante il carico, lo scarico è fermo e viceversa. + +Per ora, prevedo al tavolo como un Device con i seguenti segnali in/out: + +#### Segnali di Ingresso (Input) +*** + +| Segnale | Descrizione | Funzione | +| ------- | ----------------------------------------------- | ---------------------------------------------------------- | +| i1 | Uscita anello richiesta prodotto | Uscita libera | +| i2 | Richiesta da carico | Per cambio formato | +| i3 | Anello vuoto + divider in auto + anello in auto | Per generare consenso a cambio formato | +| i4 | Velocità motore bypass richiesta | Velocità desiderata per bypass | +| i5 | Cambio formato eseguito dall'HMI | Comando di esecuzione | +| i6 | Abilitazione scarico | Inibisce scarico automatico una volta completato il carico | + +#### Segnali di Uscita (Output) +*** + +| Segnale | Descrizione | Funzione | +| ------- | -------------------------- | ---------------------------------------------------- | +| o1 | Ingresso richiede prodotto | Tavolo pronto e in marcia | +| o2 | Cambio formato consentito | Finito il carico e anello vuoto | +| o3 | Velocità motore uscita | Per interfacciare 1 motore uscita tavolo sull'anello | +| o4 | Tavolo in Bypass | Stato bypass attivo | + +Cambio di stati sul tavolo: +- Il carico inizia su richiesta esterna i2 ( da operatore o timer ). +- Lo scarico avviene automaticamente dopo un cambio formato (i5). Il tavolo si scarica completamente prima di iniziare il modo bypass. +- Una volta scaricato, si attiva il modo bypass. (o4) + + diff --git a/03-VM/9..... MASTER Transport/Standard Transport/FB Scan Time - FB1.md b/03-VM/9..... MASTER Transport/Standard Transport/FB Scan Time - FB1.md index 2ccb041..77fa0ce 100644 --- a/03-VM/9..... MASTER Transport/Standard Transport/FB Scan Time - FB1.md +++ b/03-VM/9..... MASTER Transport/Standard Transport/FB Scan Time - FB1.md @@ -24,4 +24,71 @@ Then on the DB the FB will calculate this: The Reset bit on the DB resets all memory's. Also there is a auto reset the first 10 seconds the CPU goes from STOP to START. +```pascal +//FB Scan Time +//************* +//Calculate the execution time for the PLC of the code between the two call to this function. Normally this Function is used on a OB30 like this: +// +// Example: OB32 - Intterrupt of 5.0 ms +// ----------------------------------------- +// "FB Scan Time_DBx"(CalculateRuntime := false, +// CycleTime := 5.0); +// ... +// PROGRAM ..... +// ... +// "FB Scan Time_DBx"(CalculateRuntime:=true,CycleTime:=5.0); +//Max / Min / Average : of the runtime +//CallLost% : When the cycletime input > 0, CallLost% calculates the percentage OF cycles lost every second. This is useful for timing and monitoring Interrupt OB3x and to commision the right time for the interrupt. +// +//Reset: when TRUE resets all values. There is an autoreset also the first 10s of the PLC startup. + + CALL RUNTIME + Ret_Val :=#ElapsedRuntime_s + MEM :=#Internal.TimeRecorded + + IF NOT #CalculateRuntime THEN + RETURN; + ELSE + #CalculateRuntime := FALSE; + END_IF; + #ElapsedRuntime_ms := LREAL_TO_REAL(#ElapsedRuntime_s * 1000.0); + #TimeFromRUN := TIME_TO_DINT(TIME_TCK()); + + IF (#TimeFromRUN / 1000) < 10 THEN + #First10sCycle := true; + END_IF; + IF #Internal.CyclesForAverageCalc < 2 THEN + #Internal.CyclesForAverageCalc := 2; + END_IF; + + IF #ElapsedRuntime_ms > #Max THEN + #Max := #ElapsedRuntime_ms; + END_IF; + + IF #ElapsedRuntime_ms < #Min OR #Reset OR #First10sCycle THEN + #Min := #ElapsedRuntime_ms; + END_IF; + + #Average := (#Average * (#Internal.CyclesForAverageCalc - 1) + (#ElapsedRuntime_ms)) / #Internal.CyclesForAverageCalc ; + #Internal.CounterOfCallsEachSecond := #Internal.CounterOfCallsEachSecond + 1; + + IF (#TimeFromRUN / 1000) <> #Internal.LastCycleSeconds THEN + #Internal.CallCountLastSecond := #Internal.CounterOfCallsEachSecond; + #Internal.CounterOfCallsEachSecond := 0; + END_IF; + + #Internal.LastCycleSeconds := (#TimeFromRUN / 1000); + IF #CycleTime > 0.5 THEN + #"CallLost%" := (((1000.0 / #CycleTime) - #Internal.CallCountLastSecond) / (1000.0 / #CycleTime)) * 100.0; + END_IF; + IF NOT #First10sCycle AND #Internal.CalculatedCycleStartTime = 0 OR #Reset THEN + #Internal.CalculatedCycleStartTime := #TimeFromRUN; + #Internal.CyclesForAverageCalc := 0.0; + END_IF; + + IF (#TimeFromRUN - #Internal.CalculatedCycleStartTime) < #AverageTimeForCalc THEN + #Internal.CyclesForAverageCalc := #Internal.CyclesForAverageCalc + 1; + END_IF; + IF #RESET .. reset all counters +``` \ No newline at end of file diff --git a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Visit to Maselli 06-05-2025.md b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Visit to Maselli 06-05-2025.md index fcd91bd..fc5cb27 100644 --- a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Visit to Maselli 06-05-2025.md +++ b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/Documentation/Visit to Maselli 06-05-2025.md @@ -72,16 +72,16 @@ knick --> plc : "4-20mA" # Comparative Table: UR62 vs UR24 Refractometers by Maselli -|Feature|UR62|UR24| -|---|---|---| -|**Classification**|Basic (THE BASIC)|Advanced (THE ULTIMATE)| -|**Measurement range**|1.3229 … 1.505 nD (0…85 Bx)|1.3163 … 1.5318 nD (0…95 Bx)| -|**Accuracy**|• +/- 0.0004 nD (+/-0.2 Bx) alone
• +/- 0.0002 nD (+/-0.1 Bx) with RC24|• +/- 0.00003 nD (+/-0.02 Bx) SA version
• +/- 0.00007 nD (+/-0.05 Bx) HA version
• +/- 0.0002 nD (+/-0.15 Bx) STD version| -|**Repeatability**|• +/- 0.2 alone
• +/- 0.03 with RC24|Not specified| -|**Product temperature**|-25…+90°C (-13…194°F)|• -5…+105°C (23…221°F)
• -5…+140°C (23…284°F) for LP version| -|**Max sterilization temperature**|Hot water at 95°C x 30 min
Steam (0.5 bar) at 110°C x 30 min|• 125°C x 30 min
• 145°C x 30 min for LP version| -|**Line pressure**|• Max. 10 bar at 20°C
• Max. 8 bar at 90°C|• Max. 10 bar at 20°C
• Max. 8 bar at 100°C
• Special version up to 40 bar at 20°C| -|**Power supply**|• AC 24V ±10%, 50-60Hz, 80mA
• DC 24V ±10%, 80mA|• AC 24V ±10%, 50-60Hz, 0.6A
• DC 24V ±10%, 0.6A
• AC 115/230V ±10%, 50-60Hz, 25VA (with transformer)| -|**Interfaces**|Analog, Analog/Digital, PROFIBUS DP, Ethernet/IP|Analog, Analog/Digital, PROFIBUS DP, Ethernet/IP, PROFINET, Modbus/TCP| -|**Protection**|IP67 to EN60529|IP67 to EN60529| -|**Main benefits**|• Optical Technology
• Basic accuracy
• 100% in-line installation
• No need of adjustments
• No maintenance|• Optical Technology
• High accuracy
• 100% in-line installation
• No need of adjustments
• No maintenance| \ No newline at end of file +| Feature | UR62 | UR24 | +| --------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| **Classification** | Basic (THE BASIC) | Advanced (THE ULTIMATE) | +| **Measurement range** | 1.3229 … 1.505 nD (0…85 Bx) | 1.3163 … 1.5318 nD (0…95 Bx) | +| **Accuracy** | • +/- 0.0004 nD (+/-0.2 Bx) alone
• +/- 0.0002 nD (+/-0.1 Bx) with RC24 | • +/- 0.00003 nD (+/-0.02 Bx) SA version
• +/- 0.00007 nD (+/-0.05 Bx) HA version
• +/- 0.0002 nD (+/-0.15 Bx) STD version | +| **Repeatability** | • +/- 0.2 alone
• +/- 0.03 with RC24 | Not specified | +| **Product temperature** | -25…+90°C (-13…194°F) | • -5…+105°C (23…221°F)
• -5…+140°C (23…284°F) for LP version | +| **Max sterilization temperature** | Hot water at 95°C x 30 min
Steam (0.5 bar) at 110°C x 30 min | • 125°C x 30 min
• 145°C x 30 min for LP version | +| **Line pressure** | • Max. 10 bar at 20°C
• Max. 8 bar at 90°C | • Max. 10 bar at 20°C
• Max. 8 bar at 100°C
• Special version up to 40 bar at 20°C | +| **Power supply** | • AC 24V ±10%, 50-60Hz, 80mA
• DC 24V ±10%, 80mA | • AC 24V ±10%, 50-60Hz, 0.6A
• DC 24V ±10%, 0.6A
• AC 115/230V ±10%, 50-60Hz, 25VA (with transformer) | +| **Interfaces** | Analog, Analog/Digital, PROFIBUS DP, Ethernet/IP | Analog, Analog/Digital, PROFIBUS DP, Ethernet/IP, PROFINET, Modbus/TCP | +| **Protection** | IP67 to EN60529 | IP67 to EN60529 | +| **Main benefits** | • Optical Technology
• Basic accuracy
• 100% in-line installation
• No need of adjustments
• No maintenance | • Optical Technology
• High accuracy
• 100% in-line installation
• No need of adjustments
• No maintenance | \ No newline at end of file diff --git a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - Descrizzione Software - v1.8.md b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - Descrizzione Software - v1.8.md new file mode 100644 index 0000000..0a2b952 --- /dev/null +++ b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - Descrizzione Software - v1.8.md @@ -0,0 +1,810 @@ +*** +## Panoramica del Sistema + +Il Function Block **FB2120 MaselliTCP** è stato sviluppato per leggere direttamente i valori inviati dai sensori Maselli UR62 o UR29 utilizzando il protocollo ADAM tramite un gateway 485-Ethernet. Il sistema utilizza TCP per migliorare la resilienza dei dati, sfruttando la gestione automatica delle ritrasmissioni e il mantenimento dell'ordine dei frame. + +### Vantaggi del Sistema + +- **Comunicazione digitale diretta**: Evita la doppia conversione DAC-ADC, mantenendo la piena risoluzione +- **Resilienza TCP**: Gestione automatica delle ritrasmissioni e mantenimento dell'ordine dei dati +- **Sistema di riconnessione intelligente**: Gestisce diversi timeout per ristabilire la connessione +- **Monitoraggio avanzato**: Contatori per diversi tipi di errori e metriche di affidabilità +- **Compatibilità parallela**: Può funzionare in parallelo al sistema ADAM esistente + +## Architettura del Sistema + +```plantuml +@startuml +!define RECTANGLE class +!theme plain + +package "Sensore Maselli" #E8F4F8 { + [UR62/UR29] as sensor #4A90A4 +} + +package "Gateway 485-Ethernet" #E8F5E8 { + [Waveshare RS485-TCP] as gateway #2E7D32 +} + +package "PLC Siemens S7-300" #E3F2FD { + [FB2120 MaselliTCP] as fb #1565C0 + [TCON] as tcon #42A5F5 + [TRCV] as trcv #42A5F5 + [TDISCON] as tdiscon #42A5F5 +} + +package "Rete Ethernet" #FFF3E0 { + [TCP Connection] as tcp #FF8F00 +} + +sensor -right-> gateway : RS485\nProtocollo ADAM +gateway -right-> tcp : TCP Trasparente +tcp -right-> fb : Frame #XX12.345CKCR +fb -down-> tcon : Connessione +fb -down-> trcv : Ricezione +fb -down-> tdiscon : Disconnessione + +note right of gateway #E8F5E8 + **Gateway trasparente 485-Ethernet** + • Converte RS485 in TCP + • Server TCP sulla porta 8899 + • Comunicazione bidirezionale +end note + +note right of fb #E3F2FD + **FB2120 gestisce:** + • State machine TCP + • Buffer circolare ottimizzato + • Parsing frame ADAM + • Calcolo Brix digitale + • Gestione errori avanzata +end note +@enduml +``` + + +```plantuml +@startuml + +skinparam cloud { + BackgroundColor Gold + BorderColor Orange +} + +' Definición de los componentes con colores +component "🔌 UR29" as Meter <> #LightBlue { + [RS485] as MeterRS485 #SkyBlue +} + +component "🌐 Gateway RS485-Ethernet" as Gateway <> #LightGreen { + [RS485] as GatewayRS485 #SkyBlue + [Ethernet] as GatewayEth #LightYellow +} + +component "🖥️ PLC 315F 2PN/DP" as PLC <> #LightBlue { + [PN] as PLCEth #LightYellow + [FB2120] as FB2120 #LightPink + [DB2120] as DB2120 #LightPink +} + +' Fuente de alimentación con estilo +cloud "⚡ Alimentatore\n24V DC" as PowerSupply #Gold + +' Conexiones de datos con colores y etiquetas mejoradas +MeterRS485 -[#Blue,thickness=3]-> GatewayRS485 : "📡 RS485\nADAM Protocol" +GatewayEth -[#Green,thickness=3]-> PLCEth : "🌐 Ethernet\nTCP Trasparente" + +' Conexión interna del PLC +PLCEth -[#Purple,thickness=2]-> FB2120 : "Comm TCP" +FB2120 -[#Purple,thickness=2]-> DB2120 : "Dati" + +' Conexiones de alimentación +PowerSupply -[#Red,dashed,thickness=2]-> Meter : "24V DC" +PowerSupply -[#Red,dashed,thickness=2]-> Gateway : "24V DC" +PowerSupply -[#Red,dashed,thickness=2]-> PLC : "24V DC" + +' Notas explicativas con colores +note right of Meter #LightBlue + **Reflectometer** + • Protocollo: Transparent TCP + • Interfaccia: RS485 + • Velocità: 115200 bps +end note + +note top of Gateway #LightGreen + **Gateway di Comunicazione** + • Conversione RS485 ↔ Ethernet + • Protocollo: TCP Trasparente + • IP: 10.1.33.18 +end note + +note left of PLC #LightBlue + **PLC Siemens 315** + • CPU 315-2DP + • Interfaccia Ethernet + • FB2120: Function Block comunicazione + • DB2120: Data Block instanza + • IP: 10.1.33.11 +end note + +' Título del diagrama +title **Sistema di Comunicazione Industriale**\n//Contatore → Gateway → PLC// + +@enduml +``` + +```plantuml +@startuml +!theme toy + +' Layout horizontal para enfatizar flujo de datos +left to right direction + +skinparam cloud { + BackgroundColor Gold + BorderColor Orange +} + +' Definición de los componentes con colores +component "🔌 UR29" as Meter <> #LightBlue { + [RS485] as MeterRS485 #SkyBlue +} + +component "🌐 Gateway RS485-Ethernet" as Gateway <> #LightGreen { + [RS485] as GatewayRS485 #SkyBlue + [Ethernet] as GatewayEth #LightYellow +} + +component "🖥️ PLC 315F 2PN/DP" as PLC <> #LightBlue { + [PN] as PLCEth #LightYellow + [FB2120] as FB2120 #LightPink + [DB2120] as DB2120 #LightPink +} + +' Alimentación minimalista en la parte superior +note top #Gold : **⚡ Alimentazione 24V DC**\n//Tutti i componenti// + +' CONEXIONES DE DATOS PRINCIPALES - MUY VISIBLES +MeterRS485 -[#Blue,thickness=5]-> GatewayRS485 : "📡 **RS485**\n//ADAM Protocol//\n**115200 bps**" +GatewayEth -[#Green,thickness=5]-> PLCEth : "🌐 **ETHERNET**\n//TCP Trasparente//\n**10.1.33.18 → 10.1.33.11**" + +' Conexiones internas del PLC con flujo claro +PLCEth -[#Purple,thickness=4]-> FB2120 : "**TCP Data**" +FB2120 -[#Purple,thickness=4]-> DB2120 : "**Memory**" + +' Indicadores de dirección de flujo +note bottom of Meter #LightCyan : **📤 TX Data** +note bottom of PLC #LightCyan : **📥 RX Data** + +' Notas técnicas compactas +note right of Gateway #LightGreen + **Gateway Configuration** + • RS485 ↔ Ethernet Bridge + • Transparent TCP Protocol + • IP: 10.1.33.18 + • Port: Configurable +end note + +' Título enfocado en comunicación +title **🔗 Flusso Dati di Comunicazione Industriale**\n//UR29 Reflectometer → TCP Gateway → Siemens PLC// + +@enduml +``` + + +## State Machine Principale + +Il FB2120 utilizza una state machine principale per gestire la connessione TCP: + +```plantuml +@startuml +!theme plain + +[*] --> IDLE : Sistema avviato + +IDLE : Entry: xConnected = FALSE +IDLE : Do: Retry delay attivo +IDLE --> CONNECT : xEnable = TRUE AND tonRetryDelay.Q + +CONNECT : Entry: Preparazione connessione +CONNECT : Do: iCyclesToWait + 1 +CONNECT --> WAIT_CONNECT : iCyclesToWait >= 2 + +WAIT_CONNECT : Entry: xTconReq = TRUE +WAIT_CONNECT : Do: TCON attivo, tonConnTimeout attivo +WAIT_CONNECT --> READING : TCON.DONE +WAIT_CONNECT --> DISCONNECT : TCON.ERROR OR tonConnTimeout.Q +WAIT_CONNECT --> DISCONNECT : NOT xEnable + +READING : Entry: xConnected = TRUE +READING : Do: TRCV attivo, lettura frame +READING : Do: Reading state machine attiva +READING --> DISCONNECT : TRCV.ERROR OR tonNoDataTimeout.Q +READING --> DISCONNECT : NOT xEnable + +DISCONNECT : Entry: xTdisconReq = TRUE +DISCONNECT : Do: TDISCON attivo +DISCONNECT --> IDLE : TDISCON.DONE OR TDISCON.ERROR + +note right of READING + Stato più complesso con + sub-state machine per + la gestione della lettura +end note +@enduml +``` + +## Reading State Machine + +Durante lo stato READING, una sub-state machine gestisce la lettura ottimizzata dei frame: + +```plantuml +@startuml +!theme plain + +[*] --> ACTIVE_READING : Ingresso in READING + +state "Fase Inizializzazione" as INIT { + ACTIVE_READING : Entry: xTrcvTimeToCall = TRUE + ACTIVE_READING : Do: Lettura intensiva ogni ciclo + ACTIVE_READING : Do: Accumulo diAccumCycleMs + ACTIVE_READING --> COMPLETED : Frame valido ricevuto + + COMPLETED : Entry: xTrcvTimeToCall = FALSE + COMPLETED : Do: Calcolo intervallo frame + COMPLETED : Do: Reset diAccumCycleMs = 0 + COMPLETED --> ACTIVE_READING : xInitPhaseFinish = FALSE +} + +state "Fase Normale" as NORMAL { + ACTIVE_READING2 : Entry: xTrcvTimeToCall = TRUE + ACTIVE_READING2 : Do: Lettura intensiva + ACTIVE_READING2 --> PAUSED : Troppo tempo al prossimo frame + ACTIVE_READING2 --> COMPLETED2 : Frame valido ricevuto + + PAUSED : Entry: xTrcvTimeToCall = FALSE + PAUSED : Do: Attesa finestra frame + PAUSED --> ACTIVE_READING2 : Vicino al prossimo frame + + COMPLETED2 : Entry: Elaborazione frame + COMPLETED2 : Do: Aggiornamento statistiche + COMPLETED2 --> PAUSED : Completato +} + +INIT --> NORMAL : xInitPhaseFinish = TRUE + +note right of INIT + Durante l'inizializzazione + legge continuamente per + sincronizzarsi con il flusso +end note + +note right of NORMAL + In funzionamento normale + ottimizza la lettura con + finestre temporali +end note +@enduml +``` + +## Formato Frame ADAM + +Il protocollo ADAM utilizza frame di 12 byte fissi: + +```plantuml +@startuml +!theme plain + +package "Frame ADAM - 12 Bytes" { + rectangle "Byte 0\n#" as b0 + rectangle "Byte 1-2\nAdam ID" as b12 + rectangle "Byte 3-4\nXX" as b34 + rectangle "Byte 5\n." as b5 + rectangle "Byte 6-8\nYYY" as b678 + rectangle "Byte 9-10\nChecksum" as b910 + rectangle "Byte 11\nCR" as b11 +} + +b0 -right-> b12 +b12 -right-> b34 +b34 -right-> b5 +b5 -right-> b678 +b678 -right-> b910 +b910 -right-> b11 + +note bottom of b0 + Start marker '#' + (0x23) +end note + +note bottom of b12 + Device ID + "01" = Dispositivo 1 + "02" = Dispositivo 2 +end note + +note bottom of b34 + Parte intera + corrente mA + "02" = 2mA +end note + +note bottom of b5 + Separatore decimale + '.' (0x2E) +end note + +note bottom of b678 + Parte decimale + corrente mA + "145" = 0.145mA +end note + +note bottom of b910 + Checksum esadecimale + Somma bytes 0-8 + modulo 256 +end note + +note bottom of b11 + Carriage Return + (0x0D) +end note +@enduml +``` + +**Esempio Frame**: `#0102.145CkCr` + +- `#`: Start marker +- `01`: Device ID = 1 +- `02.145`: Corrente = 2.145 mA +- `Ck`: Checksum calcolato +- `Cr`: Carriage return + +## Sequenza di Comunicazione TCP + +```plantuml +@startuml +!theme plain + +participant "FB2120" as fb +participant "TCON" as tcon +participant "Gateway" as gw +participant "TRCV" as trcv +participant "Sensore" as sensor + +== Fase Connessione == +fb -> tcon : REQ=TRUE, ID=W#16#10 +tcon -> gw : TCP SYN a IP:porta +gw -> tcon : TCP SYN-ACK +tcon -> fb : DONE=TRUE + +== Fase Lettura == +loop Lettura Continua + sensor -> gw : Frame ADAM via RS485 + gw -> fb : Frame TCP trasparente + fb -> trcv : EN_R=TRUE (se xTrcvTimeToCall) + trcv -> fb : NDR=TRUE + dati + fb -> fb : Parsing frame, validazione + fb -> fb : Calcolo Brix, aggiornamento FIFO +end + +== Gestione Errori == +alt Errore di comunicazione + trcv -> fb : ERROR=TRUE + fb -> fb : Analisi errore, riconnessione +end + +== Disconnessione == +fb -> tdiscon : REQ=TRUE +tdiscon -> gw : TCP FIN +gw -> tdiscon : TCP FIN-ACK +tdiscon -> fb : DONE=TRUE +@enduml +``` + +## Gestione Buffer Circolare + +Il sistema utilizza un buffer circolare per gestire efficacemente i frame ricevuti: + +```plantuml +@startuml +!theme plain + +package "Buffer Circolare - 256 Bytes" { + rectangle "Circular Buffer\naCircBuffer[0..255]" as buffer + rectangle "Write Pointer\niWritePtr" as wptr + rectangle "Read Pointer\niReadPtr" as rptr + rectangle "Data Count\niDataInBuffer" as count +} + +package "Frame Processing" { + rectangle "Ricerca '#'" as search + rectangle "Validazione Formato" as validate + rectangle "Parsing Dati" as parse + rectangle "Calcolo Checksum" as checksum +} + +buffer -down-> search : Scan per start marker +search -right-> validate : Frame trovato +validate -right-> parse : Formato OK +parse -right-> checksum : Dati estratti +checksum -up-> buffer : Frame processato, avanzamento puntatori + +note right of buffer + Buffer di 256 byte per gestire + ricezione asincrona e parsing + efficiente dei frame +end note + +note bottom of search + Ricerca sequenziale del + carattere '#' per inizio frame +end note +@enduml +``` + +## Codici di Errore + +Il sistema utilizza codici di errore gerarchici (priorità crescente): + +|Codice|Priorità|Descrizione| +|---|---|---| +|0|-|Nessun errore| +|1|Bassa|Errore checksum| +|2|Bassa|Formato frame non valido| +|3|Bassa|Caratteri non numerici| +|4|Media|Dati fuori range (4-20mA)| +|5|Media|Frame consecutivi errati| +|6|Media|Frame persi rilevati| +|7|Alta|Buffer TRCV troppo piccolo| +|8|Alta|Errore comunicazione TRCV| +|9|Critica|Timeout ricezione dati| +|10|Critica|Timeout connessione| +|11|Critica|Connessione TCP fallita| +|12|Critica|Connessione TCP terminata| + +## Parametri di Configurazione + +### Input Parameters + +- **xEnable**: Abilitazione comunicazione +- **aRemoteIP**: IP del gateway [10,1,33,100] +- **iRemotePort**: Porta TCP (default: 8899) +- **rBrixMax**: Valore Brix massimo a 20mA (default: 80.0) +- **wConnectionID**: ID connessione TCP +- **xEnableChecksum**: Abilitazione validazione checksum +- **rFramesPerSecond**: Frame attesi per secondo (default: 3.0) +- **iDeviceID**: ID dispositivo da validare (0=disabilitato) + +### Output Parameters + +- **xConnected**: Stato connessione +- **xDataValid**: Pulse per nuovo dato valido +- **xError**: Errore attivo +- **iErrorCode**: Codice errore strutturato +- **rCurrentMA**: Valore corrente in mA +- **rBrixValue**: Valore Brix calcolato +- **diTimeBetweenFramesMs**: Tempo tra frame consecutivi + +## Calcolo Brix + +La conversione dalla corrente 4-20mA al valore Brix segue la formula: + +``` +rBrixValue = (rCurrentMA - 4.0) * rBrixMax / 16.0 +``` + +**Esempio**: + +- Corrente ricevuta: 12.0 mA +- Brix Max configurato: 80.0 +- Calcolo: (12.0 - 4.0) * 80.0 / 16.0 = 40.0 Brix + +## Sistema FIFO (Debug Mode) + +Quando `xEnableFifoDebug = TRUE`, il sistema mantiene le ultime 10 letture: + +- **arBrixHistory[0..9]**: Valori Brix (newest → oldest) +- **auiTimeHistory[0..9]**: Timestamp (newest → oldest) + +I dati vengono spostati ad ogni nuovo valore valido, con il più recente sempre in posizione [0]. + +## Vantaggi Implementativi + +### Ottimizzazioni v1.8 + +- **Buffer ottimizzato**: Ridotto da 128 a 23 byte +- **State machine migliorata**: Fase di inizializzazione separata +- **Lettura adattiva**: Finestre temporali ottimizzate +- **Gestione errori avanzata**: Codici gerarchici strutturati +- **Sincronizzazione migliorata**: Flag xInitPhaseFinish + +### Resilienza del Sistema + +- **Riconnessione automatica**: Gestione intelligente dei timeout +- **Buffer circolare**: Gestione efficace dei dati asincroni +- **Validazione multipla**: Formato, checksum, range dati +- **Statistiche dettagliate**: Monitoraggio prestazioni e affidabilità + +## Configurazione Hardware Richiesta + +### Gateway Suggerito + +- **Waveshare Industrial Grade Serial Server RS232/485 to WiFi And Ethernet** +- Configurazione: Server TCP trasparente +- Porta: 8899 (configurabile) +- Modalità: Trasparente RS485 → TCP + +### PLC Requirements + +- **Siemens S7-300** con supporto TCP/IP +- **Function Blocks**: TCON, TRCV, TDISCON (standard Siemens) +- **Memoria**: ~2KB per istanza FB +- **Nessuna configurazione NetPro richiesta** + +## Utilizzo Pratico + +1. **Istanziare FB2120** con parametri specifici del sensore +2. **Configurare IP/Porta** del gateway nel codice +3. **Impostare xEnable = TRUE** per avviare la comunicazione +4. **Monitorare xDataValid** per nuovi dati +5. **Verificare iErrorCode** per diagnostica +6. **Leggere rBrixValue** e rCurrentMA** per i valori processati + +Il sistema è progettato per funzionare in parallelo ai sistemi ADAM esistenti, offrendo una soluzione digitale più precisa e affidabile per la lettura dei sensori Maselli. + +## Reading State Machine e Burst-Reading + +Durante lo stato READING, una sub-state machine gestisce la lettura ottimizzata dei frame con la tecnica del **burst-reading** per ottimizzare le risorse del PLC: + +```plantuml +@startuml +!theme plain + +[*] --> ACTIVE_READING : Ingresso in READING + +state "Fase Inizializzazione" as INIT { + ACTIVE_READING : Entry: xTrcvTimeToCall = TRUE + ACTIVE_READING : Do: Lettura intensiva ogni ciclo + ACTIVE_READING : Do: Accumulo diAccumCycleMs + ACTIVE_READING : Do: Ricerca sincronizzazione frame + ACTIVE_READING --> COMPLETED : Frame valido ricevuto + + COMPLETED : Entry: xTrcvTimeToCall = FALSE + COMPLETED : Do: Calcolo intervallo frame iniziale + COMPLETED : Do: Aggiornamento stTiming.diEstFrameMs + COMPLETED : Do: Reset diAccumCycleMs = 0 + COMPLETED --> ACTIVE_READING : xInitPhaseFinish = FALSE + COMPLETED --> INIT_COMPLETE : Buffer sincronizzato E tempo > 2*intervallo + + INIT_COMPLETE : Entry: xInitPhaseFinish = TRUE + INIT_COMPLETE : Do: Transizione a funzionamento normale +} + +state "Fase Funzionamento Normale" as NORMAL { + ACTIVE_READING_BURST : Entry: xTrcvTimeToCall = TRUE + ACTIVE_READING_BURST : Do: Lettura burst intensiva + ACTIVE_READING_BURST : Do: diReadingStartMs = diAccumCycleMs + ACTIVE_READING_BURST --> PAUSED : (diNextFrameMs - diAccumCycleMs) > iMaxActiveReadingMs + ACTIVE_READING_BURST --> COMPLETED_NORMAL : Frame valido ricevuto + + PAUSED : Entry: xTrcvTimeToCall = FALSE + PAUSED : Do: Risparmio risorse CPU + PAUSED : Do: Attesa finestra frame calcolata + PAUSED --> ACTIVE_READING_BURST : (diNextFrameMs - diAccumCycleMs) <= iPreReadOffsetMs + + COMPLETED_NORMAL : Entry: xTrcvTimeToCall = FALSE + COMPLETED_NORMAL : Do: Elaborazione frame completa + COMPLETED_NORMAL : Do: Aggiornamento statistiche avanzate + COMPLETED_NORMAL : Do: Smoothing diEstFrameMs + COMPLETED_NORMAL : Do: Rilevamento frame persi + COMPLETED_NORMAL --> PAUSED : Sempre +} + +INIT --> NORMAL : xInitPhaseFinish = TRUE + +note right of INIT + **Fase Inizializzazione:** + - Lettura continua per sincronizzazione + - Apprendimento timing frame + - Pulizia buffer da dati residui + - Stima intervallo frame iniziale +end note + +note right of NORMAL + **Burst-Reading Ottimizzato:** + - Lettura intensiva solo quando necessario + - Pausa durante attese lunghe + - Risparmio risorse CPU del 60-80% + - Finestre temporali adattive +end note + +note bottom of PAUSED + **Ottimizzazione Risorse:** + - TRCV non chiamato + - CPU dedicata ad altri task + - Calcolo dinamico finestra lettura +end note +@enduml +``` + +## Sequenza Dettagliata Burst-Reading + +```plantuml +@startuml +!theme plain +title Sequenza Burst-Reading - Ottimizzazione Risorse PLC + +actor "Ciclo PLC" as plc +participant "iReadingState\nMachine" as rsm +participant "TRCV" as trcv +participant "Buffer\nCircolare" as buffer +participant "Gateway\nTCP" as gateway +participant "Sensore\nMaselli" as sensor + +== Fase Inizializzazione (xInitPhaseFinish = FALSE) == + +loop Sincronizzazione Iniziale + plc -> rsm : Ciclo PLC (ogni 10-50ms) + rsm -> rsm : iReadingState = 0 (ACTIVE_READING) + rsm -> rsm : xTrcvTimeToCall = TRUE + rsm -> trcv : TRCV(EN_R=TRUE) - **Lettura Intensiva** + + alt Frame disponibile + sensor -> gateway : Frame ADAM #01XX.YYYCKHR + gateway -> trcv : TCP Data + trcv -> rsm : NDR=TRUE + 12 bytes + rsm -> buffer : Copia in buffer circolare + rsm -> rsm : Parsing e validazione frame + + alt Frame valido + rsm -> rsm : iReadingState = 1 (COMPLETED) + rsm -> rsm : Calcolo primo intervallo + rsm -> rsm : diAccumCycleMs = 0 (reset timer) + rsm -> rsm : iConsecutiveGoodFrames++ + + alt Sincronizzazione completa + rsm -> rsm : xInitPhaseFinish = TRUE + rsm -> rsm : **Transizione a Burst-Reading** + end + end + else Nessun frame + rsm -> rsm : Continua accumulo diAccumCycleMs + end +end + +== Fase Funzionamento Normale (Burst-Reading) == + +loop Ciclo Ottimizzato + plc -> rsm : Ciclo PLC + rsm -> rsm : Calcolo finestra frame + + alt Finestra Attiva (vicino al frame atteso) + rsm -> rsm : iReadingState = 0 (ACTIVE_READING_BURST) + rsm -> rsm : xTrcvTimeToCall = TRUE + rsm -> trcv : **TRCV(EN_R=TRUE) - Burst Intensivo** + + note right : **Lettura Burst:**\nTRCV chiamato ogni ciclo\nper massima reattività + + alt Frame ricevuto + trcv -> rsm : NDR=TRUE + frame data + rsm -> rsm : iReadingState = 1 (COMPLETED_NORMAL) + rsm -> rsm : Elaborazione completa frame + rsm -> rsm : Aggiornamento statistiche + rsm -> rsm : Smoothing diEstFrameMs + rsm -> rsm : diNextFrameMs = nuovo calcolo + rsm -> rsm : iReadingState = 2 (PAUSED) + else Timeout burst + rsm -> rsm : iReadingState = 2 (PAUSED) + note right : Evita lettura continua\neccessiva + end + + else Finestra Inattiva (troppo presto per il prossimo frame) + rsm -> rsm : iReadingState = 2 (PAUSED) + rsm -> rsm : xTrcvTimeToCall = FALSE + rsm -> trcv : **TRCV(EN_R=FALSE) - Risparmio CPU** + + note right : **Modalità Pausa:**\nTRCV non chiamato\nCPU disponibile per altri task\nRisparmio energetico + + rsm -> rsm : Calcolo: (diNextFrameMs - diAccumCycleMs) + rsm -> rsm : Se <= iPreReadOffsetMs → Attiva burst + end +end + +note over plc, sensor + **Vantaggi Burst-Reading:** + • Risparmio CPU: 60-80% in modalità PAUSED + • Reattività massima durante burst + • Sincronizzazione automatica con sensore + • Adattamento dinamico agli intervalli frame + • Riduzione interferenze con altri task PLC +end note +@enduml +``` + +## Fase di Inizializzazione Dettagliata + +La fase di inizializzazione è critica per sincronizzare il PLC con il flusso dati del sensore Maselli: + +```plantuml +@startuml +!theme plain +title Sequenza Fase di Inizializzazione - Sincronizzazione con Sensore + +participant "FB2120" as fb +participant "Buffer\nCircolare" as buffer +participant "Frame\nParser" as parser +participant "Timing\nEngine" as timing +participant "Statistiche" as stats + +== Avvio Inizializzazione == +fb -> fb : xInitPhaseFinish = FALSE +fb -> fb : iReadingState = 0 (ACTIVE_READING) +fb -> fb : diAccumCycleMs = 0 +fb -> fb : iConsecutiveGoodFrames = 0 +fb -> timing : diInitPhaseStartMs = diAccumCycleMs + +== Raccolta Dati Iniziale == +loop Lettura Continua (xTrcvTimeToCall = TRUE) + fb -> buffer : Ricezione dati TCP asincroni + buffer -> buffer : Accumulo bytes in buffer circolare + buffer -> parser : Ricerca pattern #XX.YYY + + alt Buffer contiene dati residui/parziali + parser -> buffer : Pulizia dati non validi + parser -> buffer : Allineamento a boundary frame + note right : Rimozione garbage data\nda precedenti connessioni + end + + alt Frame completo trovato + parser -> parser : Validazione formato + alt Frame strutturalmente valido + parser -> fb : Frame OK + dati estratti + fb -> fb : iConsecutiveGoodFrames++ + fb -> fb : Calcolo intervallo grezzo + fb -> timing : Aggiornamento diEstFrameMs iniziale + fb -> stats : Incremento contatori successo + + alt Prima sincronizzazione (frames >= 2) + fb -> timing : diEstFrameMs = intervallo_misurato + fb -> timing : Calcolo finestre ottimizzate + note right : **Parametri Calcolati:**\ndiFrameIntervalMs = 1000/rFramesPerSecond\niPreReadOffsetMs = intervallo/6\niMaxActiveReadingMs = intervallo/3 + end + else Frame non valido + parser -> stats : Incremento errori formato + parser -> buffer : Scarta frame e continua + end + end + + alt Condizioni per completamento inizializzazione + fb -> fb : Verifica: diAccumCycleMs > (diFrameIntervalMs * 2) + fb -> fb : Verifica: stBuffer.iRxLength = 12 (buffer pulito) + fb -> fb : Verifica: iConsecutiveGoodFrames >= 2 + + alt Tutte le condizioni soddisfatte + fb -> fb : **xInitPhaseFinish = TRUE** + fb -> timing : Finalizzazione parametri timing + fb -> fb : Transizione a funzionamento normale + + note over fb : **Inizializzazione Completata:**\n• Buffer sincronizzato con frame\n• Timing affidabile stabilito\n• Sistema pronto per burst-reading + end + end +end + +== Parametri Calcolati Automaticamente == +timing -> timing : diFrameIntervalMs = 1000.0 / rFramesPerSecond +timing -> timing : iPreReadOffsetMs = MAX(20, diFrameIntervalMs/6) +timing -> timing : iMaxActiveReadingMs = MAX(50, diFrameIntervalMs/3) +timing -> timing : diNextFrameMs = diEstFrameMs + +note over timing + **Calcoli Adattivi:** + • Intervallo teorico da configurazione + • Intervallo reale da misurazione + • Finestre dinamiche per ottimizzazione + • Sicurezza con valori minimi +end note +@enduml +``` + diff --git a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - v1.8.md b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - v1.8.md new file mode 100644 index 0000000..ee41ecc --- /dev/null +++ b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/FB2120 - MasseliTCP Read - v1.8.md @@ -0,0 +1,1088 @@ +*** + +Ho creato l'FB2120 per leggere direttamente i valori inviati dai masselli UR62 o UR29 utilizzando il protocollo ADAM tramite un gateway 485 a Ethernet. Ho scelto TCP sul gateway trasparente 485-Ethernet per migliorare la resilienza dei dati. Il protocollo TCP gestisce automaticamente le ritrasmissioni in caso di perdita di un frame, mantenendo l'ordine dei dati. Questa gestione è ideale per la velocità richiesta, poiché Ethernet opera a velocità molto superiori e permette di evitare la perdita di trame in caso di collisioni. + +Il sistema di riconnessione gestisce diversi timeout per ristabilire la connessione in varie situazioni. Il valore di TimeBetweenFramesMs è stato creato per misurare la velocità con cui i Masselli inviano i dati. Altri contatori monitorano diversi tipi di errori per valutare l'affidabilità del sistema. + +Per potere testare il sistema ho creato un simulatore che riesce a creare via 485 attraverso il gateway le stesse protocollo ADAM e ho testato sul ADAM che ci ha prestato Masselli e funziona correttamente. Una volta collaudata la simulazione dei dati digitali ho creato un server TCP che permette simulare il funzionamento e dal PLC prendere i valori como se ci fosse il Masseli colegato. Con questo setup ho potuto simulare diversi problemi che possono accadere nella comunicazione tra il PLC e il Gateway. Quando arrivi il misuratore dorerebbe essere funzionante. + +Ho utilizzato un Gateway Waveshare WIFI 485/Ethernet ([Waveshare Industrial Grade Serial Server RS232/485 to WiFi And Ethernet, Modbus Gateway, MQTT Gateway, Metal Case, Wail-Mount and Rail-Mount Support : Amazon.it: Informatica](https://www.amazon.it/dp/B0CFXX5SKS?ref=ppx_yo2ov_dt_b_fed_asin_title) ), ma in realtà si può usare qualsiasi gateway 485 a Ethernet che diventa un server TCP trasparente. Sul lato PLC, è sufficiente un'istanza di FB/DB per misuratore, utilizzando solo le FB Siemens TCON e TRCV, già impiegate per la FB1. Non è stato necessario utilizzare SFC extra o modificare la configurazione hardware, poiché TCON gestisce la comunicazione senza bisogno di creare il link con NetPro. Per semplicità, ho inserito l'IP del server direttamente nel codice per rendere la chiamata alla FB più pulita. + +La FB fornisce stati per gestire problemi di comunicazione e calcola il Brix e la corrente ricevuta digitalmente. Utilizzando questo sistema, si evita la doppia conversione DAC-ADC, riducendo la perdita di risoluzione; questo include la perdita del 25% di risoluzione per il discorso che il ADAM lavora a 0..20mA e solo se utilizzano 4..20mA. La FB legge i valori digitali direttamente dall'uscita del Masselli, senza perdite, e può essere usata in parallelo al ADAM come opzione. Il flusso via 485 può essere letto sia dal ADAM che dal Gateway contemporaneamente, sfruttando la comunicazione unidirezionale. + +Video da i test: [Microsoft OneDrive](https://1drv.ms/v/c/129c0e590bbc3a9e/EedcDsWnAwFKkzfMdsEloHoBJoapLe0CjJq9dpG5ch6qzw?e=UpMASB) +Link dal software S7 utlizato per Test: [Microsoft OneDrive](https://1drv.ms/u/c/129c0e590bbc3a9e/ETpiLUQCwNRLn4rQFx8ygkcBDFsQ6HRxXy7o0FGd15FBcA?e=5fld6z) + +*** + +#### La chiamata della FB sarebbe: + +![[Pasted image 20250530095053.png]] + +![[Pasted image 20250530095111.png]] +# Documentazione del Blocco Funzione: MaselliTCP + +--- + +**Versione:** 1.8 **Descrizione:** Questa FB è progettata per leggere dati da un sensore Maselli tramite una connessione TCP/IP in modo continuo e ottimizzato. Il sensore invia frame di dati con un formato fisso di 12 byte: `#XX12.345CKCR` via RS485, questi dati vengono catturati con un gateway Waveshare che funziona da server TCP trasparente. L'FB gestisce la connessione, la ricezione ottimizzata tramite **burst reading**, il parsing dei dati con validazione ID e checksum, e il calcolo del valore Brix. + +## Principali Miglioramenti v1.8 verso v1.3 + +- **Burst Reading**: Sistema di lettura ottimizzato che riduce il carico di ciclo PLC alternando fasi di lettura intensiva e pause +- **Controllo ID Dispositivo**: Validazione opzionale dell'ID del dispositivo Adam (posizioni 1-2 del frame) +- **Validazione Checksum**: Controllo checksum configurabile per garantire l'integrità dei dati +- **Buffer Ottimizzato**: Buffer di ricezione ridotto da 128 a 23 byte per maggiore efficienza +- **Organizzazione Dati Strutturata**: Uso di strutture per configurazione, statistiche, timing e diagnostica +- **Gestione Errori Avanzata**: Sistema di codici errore con priorità (0-12, maggiore = più critico) +- **Tabelle FIFO**: Storia opzionale degli ultimi 10 valori per debug (newest=[0], oldest=[9]) + +## Funzionamento di Base + +L'FB opera attraverso una macchina a stati principale e una macchina a stati di lettura ottimizzata: + +### Stati Principali (iState): + +1. **IDLE (0):** Attesa abilitazione con ritardo anti-riconnessione rapida +2. **CONNECT (1):** Preparazione richiesta connessione TCP +3. **WAIT CONNECT (2):** Tentativo di connessione con timeout configurabile +4. **READING (3):** Lettura continua con sistema burst reading ottimizzato +5. **DISCONNECT (4):** Chiusura controllata della connessione + +### Stati di Lettura Ottimizzata (iReadingState): + +- **ACTIVE_READING (0):** Lettura intensiva durante finestra di ricezione dati +- **COMPLETED (1):** Frame valido processato, calcolo timing per frame successivo +- **PAUSED (2):** Pausa calcolata tra frame per ridurre carico ciclo PLC + +Il sistema **burst reading** ottimizza i tempi di ciclo alternando: + +- Fasi di lettura intensiva quando sono attesi i dati +- Pause calcolate per ridurre il carico computazionale +- Fase di inizializzazione per sincronizzazione con il sensore + +## Parametri di Ingresso (VAR_INPUT) + +|Nome|Tipo|Valore Predefinito|Descrizione| +|---|---|---|---| +|`xEnable`|`BOOL`||Abilita (`TRUE`) o disabilita (`FALSE`) la comunicazione con il sensore| +|`aRemoteIP`|`ARRAY[1..4] OF BYTE`|`[10,1,33,100]`|Indirizzo IP del server Gateway Maselli| +|`iRemotePort`|`INT`|`8899`|Porta TCP del server Gateway Maselli| +|`rBrixMax`|`REAL`|`80.0`|Valore Brix massimo che corrisponde a 20mA del segnale| +|`wConnectionID`|`WORD`|`W#16#10`|ID univoco per la connessione TCP (configurato nell'hardware del PLC)| +|`xEnableChecksum`|`BOOL`|`TRUE`|**NUOVO**: Abilita validazione checksum dei frame ricevuti| +|`rFramesPerSecond`|`REAL`|`3.0`|**NUOVO**: Frame attesi per secondo (per calcolo timing ottimizzato)| +|`iConnTimeoutSec`|`INT`|`10`|**NUOVO**: Timeout connessione in secondi| +|`iDataTimeoutSec`|`INT`|`30`|**NUOVO**: Timeout ricezione dati in secondi| +|`iRetryDelaySec`|`INT`|`2`|**NUOVO**: Ritardo tra tentativi di riconnessione| +|`xEnableFifoDebug`|`BOOL`|`FALSE`|**NUOVO**: Abilita tabelle FIFO per debug (ultimi 10 valori)| +|`xDisableBurstRead`|`BOOL`|`FALSE`|**NUOVO**: Disabilita burst reading (TRCV sempre attivo)| +|`iDeviceID`|`INT`|`0`|**NUOVO**: ID dispositivo da validare (0=disabilitato, 1-99=abilitato)| + +## Parametri di Uscita (VAR_OUTPUT) + +|Nome|Tipo|Descrizione| +|---|---|---| +|`xConnected`|`BOOL`|Indica lo stato della connessione TCP| +|`xDataValid`|`BOOL`|Impulso quando un nuovo set di dati validi è stato ricevuto e parsato| +|`xError`|`BOOL`|`TRUE` se si è verificato un errore| +|`wErrorCode`|`WORD`|Codice di errore legacy (per compatibilità)| +|`iErrorCode`|`INT`|**NUOVO**: Codice errore strutturato (0=OK, maggiore=più critico)| +|`rCurrentMA`|`REAL`|Valore di corrente in milliampere letto dal sensore| +|`rBrixValue`|`REAL`|Valore Brix calcolato| +|`xInitPhaseFinish`|`BOOL`|**NUOVO**: Flag completamento fase inizializzazione| +|`diTimeBetweenFramesMs`|`DINT`|Tempo trascorso tra gli ultimi due frame validi| +|`diReadingState`|`INT`|**NUOVO**: Stato corrente del sistema di lettura (0=Attivo, 1=Completato, 2=Pausa)| + +## Strutture Dati Organizzate + +### Configurazione (stConfig) + +Parametri di configurazione consolidati per migliore organizzazione dei dati del DB. + +### Statistiche (stStats) + +- `diFrameCount`: Frame totali ricevuti +- `diErrorFrameCount`: Frame con errori di formato +- `diSuccessfulReconCount`: Riconnessioni riuscite +- `diChecksumErrorCount`: **NUOVO**: Errori checksum +- `diLostFramesCount`: **NUOVO**: Frame persi stimati +- `iConsecutiveBadFrames`: **NUOVO**: Frame consecutivi errati + +### Timing (stTiming) + +- Calcolo automatico intervalli frame basato su `rFramesPerSecond` +- Ottimizzazione dinamica del timing di lettura +- Rilevamento jitter e variazioni timing + +### Diagnostica (stDiag) + +Stati e informazioni di debug consolidate per facilitare la manutenzione. + +## Codici Errore Strutturati (iErrorCode) + +**Priorità crescente (0 = nessun errore, 12 = più critico):** + +|Codice|Descrizione| +|---|---| +|0|Nessun errore| +|1|Errore checksum| +|2|Formato frame non valido| +|3|Caratteri non numerici| +|4|Dati fuori range (4-20mA)| +|5|Frame errati consecutivi multipli| +|6|Frame persi rilevati| +|7|Buffer ricezione TRCV troppo piccolo| +|8|Errore comunicazione TRCV| +|9|Timeout ricezione dati| +|10|Timeout connessione| +|11|Connessione TCP fallita| +|12|Connessione TCP terminata| + +## Tabelle FIFO (Debug Opzionale) + +Quando `xEnableFifoDebug = TRUE`: + +- `arBrixHistory[0..9]`: Ultimi 10 valori Brix ([0]=più recente, [9]=più vecchio) +- `auiTimeHistory[0..9]`: Ultimi 10 timestamp ([0]=più recente, [9]=più vecchio) + +## Note Aggiuntive + +--- + +- **Buffer Ottimizzato**: Buffer di ricezione ridotto da 128 a 23 byte per maggiore efficienza memoria +- **Burst Reading**: Riduce significativamente il carico di ciclo PLC alternando lettura intensiva e pause calcolate +- **Validazione ID**: Controllo opzionale dell'ID dispositivo Adam nelle posizioni 1-2 del frame +- **Checksum**: Validazione hex checksum configurabile per garantire integrità dati +- **Timing Adattivo**: Calcolo automatico degli intervalli di lettura basato sulla frequenza frame configurata +- **Rilevamento Frame Persi**: Stima automatica dei frame persi basata su analisi timing +- **Fase Inizializzazione**: Gestione ottimizzata della sincronizzazione iniziale con il sensore +- **Reset Contatori**: I contatori si resettano automaticamente per prevenire overflow + +### Source: +*** +```pascal +//****************************************************************************** +// Function Block: FB_MaselliTCP +// Description: Enhanced Maselli sensor TCP reader with optimized buffer and FIFO data +// Frame format: #XX12.345CKCR (12 fixed bytes) +// +// | Field | Start (1 char) | Adam address (2 chars) | Brix or Temperature value in mA (XX.YYY: 6 chars) | Checksum (2 chars) | Carriage return (1 char) | +// | :-----: | :------------: | :--------------------: | :-----------------------------------------------: | :----------------: | :----------------------: | +// | Example | # | 01 | 02.145 | CkCk | Cr | +// +// Version: 1.8 - Enhanced with structured data and optimized buffer management +// Platform: Siemens S7-300 +// +// IMPROVEMENTS v1.8: +// - Structured data organization for better DB readability +// - Optimized buffer size (23 bytes instead of 128) +// - Enhanced reading state machine with initialization phase +// - Ordered FIFO tables for last 10 readings (newest at [0], oldest at [9]) +// - Optional FIFO debug mode (disabled by default) +// - Improved synchronization logic with xInitPhaseFinish flag +// - Limited diAccumCycleMs accumulation only during iState = 3 +// +// READING STATES: +// 0 = ACTIVE_READING - Receiving data burst, read intensively +// 1 = COMPLETED - Finished reading a valid frame, return to paused +// 2 = PAUSED - Not reading, waiting for next frame window +// +// FIFO TABLES (when xEnableFifoDebug = TRUE): +// arBrixHistory[0] = newest Brix value, arBrixHistory[9] = oldest +// auiTimeHistory[0] = newest timestamp, auiTimeHistory[9] = oldest +// +// ERROR CODES (iErrorCode) - Higher numbers = Higher priority: +// 0 = No error, 1 = Checksum error, 2 = Invalid frame format +// 3 = Invalid digit characters, 4 = Data out of range (4-20mA) +// 5 = Multiple consecutive bad frames, 6 = Lost frames detected +// 7 = TRCV receive buffer too small, 8 = TRCV communication error +// 9 = Data reception timeout, 10 = Connection timeout +// 11 = TCP connection failed, 12 = TCP connection terminated +//****************************************************************************** + +FUNCTION_BLOCK MaselliTCP +TITLE = 'Maselli TCP Reader - Enhanced Buffer Management' +VERSION : '1.8' + +VAR_INPUT + xEnable : BOOL; // Enable communication + aRemoteIP : ARRAY[1..4] OF BYTE := [10,1,33,100]; // Remote server IP + iRemotePort : INT := 8899; // Server port + rBrixMax : REAL := 80.0; // Maximum Brix value at 20mA + wConnectionID : WORD := W#16#10; // TCP Connection ID + xEnableChecksum : BOOL := TRUE; // Enable checksum validation + rFramesPerSecond : REAL := 3.0; // Expected frames per second + iConnTimeoutSec : INT := 10; // Connection timeout in seconds + iDataTimeoutSec : INT := 30; // Data reception timeout in seconds + iRetryDelaySec : INT := 2; // Delay between reconnection attempts + xEnableFifoDebug : BOOL := FALSE; // Enable FIFO tables update (debug only) + xDisableBurstRead : BOOL := FALSE; // Disable burst reading (TRCV always active in reading state if TRUE) + iDeviceID : INT := 0; // Device ID to validate (0 = disabled, 1-99 = enabled). Checks aFrame[1] and aFrame[2]. +END_VAR + +VAR_OUTPUT + xConnected : BOOL; // Connection status + xDataValid : BOOL; // Pulse when valid data is available + xError : BOOL; // Active error + wErrorCode : WORD; // Legacy error code (for compatibility) + iErrorCode : INT; // Structured error code (0=OK, higher=more critical) + rCurrentMA : REAL; // Current mA value + rBrixValue : REAL; // Current Brix value + xInitPhaseFinish : BOOL; // Initialization phase completed flag + + // Current frame timing + diTimeBetweenFramesMs : DINT; // Time elapsed between last two valid frames + diReadingState : INT; // Current reading state for diagnostics +END_VAR + +// ============================================================================ +// CONTROL VARIABLES +// ============================================================================ + +VAR // State Machine Control + iState : INT := 0; // Main state: 0=Idle, 1=Connect, 2=WaitConnect, 3=Reading, 4=Disconnect + iReadingState : INT := 0; // Reading state: 0=Active, 1=Completed, 2=Paused + iCurrentErrorCode : INT := 0; // Current error being evaluated + diAccumCycleMs : DINT := 0; // Accumulated cycle time (only in iState=3) + iConsecutiveGoodFrames : INT := 0; // Counter for consecutive structurally good frames + xFirstScan : BOOL := TRUE; + diInitPhaseTimerMs : DINT := 0; // Timer for initialization phase duration +END_VAR + +VAR // Timing Control + tCurrentTime : TIME; // Current system time + tLastTime : TIME; // Previous time + diElapsedMs : DINT; // Elapsed time in ms + xTrcvTimeToCall : BOOL := TRUE; // TRCV call control +END_VAR + +VAR // FIFO Tables - Last 10 readings (ordered: [0]=newest, [9]=oldest) + arBrixHistory : ARRAY[0..9] OF REAL; // Last 10 Brix values (newest first) + auiTimeHistory : ARRAY[0..9] OF INT; // Last 10 timestamps in ms (newest first) +END_VAR + +// ============================================================================ +// STRUCTURED DATA ORGANIZATION +// ============================================================================ + +VAR // Configuration Structure + stConfig : STRUCT + rFramesPerSecond : REAL := 3.0; // Expected frames per second + iConnTimeoutSec : INT := 10; // Connection timeout + iDataTimeoutSec : INT := 30; // Data timeout + iRetryDelaySec : INT := 2; // Retry delay + rBrixMax : REAL := 80.0; // Maximum Brix at 20mA + xEnableChecksum : BOOL := TRUE; // Checksum validation + iDeviceID : INT := 0; // Device ID to validate + xDisableBurstRead : BOOL; // Disable burst reading + END_STRUCT; +END_VAR + +VAR // Statistics Structure + stStats : STRUCT + diFrameCount : DINT; // Total received frames + diErrorFrameCount : DINT; // Frames with format errors + diSuccessfulReconCount : DINT; // Successful reconnections + diChecksumErrorCount : DINT; // Checksum errors + diLostFramesCount : DINT; // Estimated lost frames + iConsecutiveBadFrames : INT; // Consecutive bad frames counter + END_STRUCT; +END_VAR + +VAR // Timing Structure + stTiming : STRUCT + diFrameIntervalMs : DINT := 333; // Auto-calculated frame interval + iPreReadOffsetMs : INT := 50; // Pre-read offset + iMaxActiveReadingMs : INT := 200; // Max active reading time + diEstFrameMs : DINT := 1000; // Estimated frame interval + diNextFrameMs : DINT := 0; // Next expected frame time + diReadingStartMs : DINT := 0; // Reading start time + diMinFrameIntervalMs : DINT := DINT#999999; // Minimum observed interval + diMaxFrameIntervalMs : DINT := 0; // Maximum observed interval + diFrameJitterMs : DINT := 0; // Frame jitter + END_STRUCT; +END_VAR + +VAR // Diagnostics Structure + stDiag : STRUCT + diState : INT; // Current state for debug + diTconStatus : WORD; // TCON status + diTrcvStatus : WORD; // TRCV status + diNextExpectedMs : DINT; // Next expected frame time + diCalcFrameIntervalMs : DINT; // Calculated frame interval + iCalcPreReadOffsetMs : INT; // Calculated pre-read offset + iCalcMaxActiveMs : INT; // Calculated max active time + rAvgCurrentMA : REAL; // Moving average of current + END_STRUCT; +END_VAR + +// ============================================================================ +// CONNECTION PARAMETERS +// ============================================================================ + +VAR // TCP Connection Parameters + stConnParams : STRUCT + block_length : WORD := W#16#40; + id : WORD; + connection_type : BYTE := B#16#11; // TCP + active_est : BOOL := TRUE; // Active client + local_device_id : BYTE := B#16#2; // Integrated PN + local_tsap_id_len : BYTE := B#16#0; + rem_subnet_id_len : BYTE := B#16#0; + rem_staddr_len : BYTE := B#16#4; + rem_tsap_id_len : BYTE := B#16#2; + next_staddr_len : BYTE := B#16#0; + local_tsap_id : ARRAY[1..16] OF BYTE; + rem_subnet_id : ARRAY[1..6] OF BYTE; + rem_staddr : ARRAY[1..6] OF BYTE; + rem_tsap_id : ARRAY[1..16] OF BYTE; + next_staddr : ARRAY[1..6] OF BYTE; + spare : WORD := W#16#0; + END_STRUCT; +END_VAR + +// ============================================================================ +// FUNCTION BLOCK INSTANCES AND INTERNAL DATA (Bottom of DB) +// ============================================================================ + +VAR // Frame Processing + i : INT; + j : INT; + iStartPos : INT; + aFrame : ARRAY[0..11] OF BYTE; // Current frame + iChecksumSum : INT; + bCalculatedChecksum : BYTE; + bReceivedChecksum : BYTE; +END_VAR + +VAR // Connection Control + xTdisconReq : BOOL; + xTconReq : BOOL; + xTconReqOld : BOOL; + xTconPulse : BOOL; + iCyclesToWait : INT; +END_VAR + +VAR // Timer Instances + tonConnTimeout : TON; // Connection timeout + tonRetryDelay : TON; // Retry delay + tonNoDataTimeout: TON; // No data timeout + tonDisconTimeout: TON; // Disconnect timeout +END_VAR + +VAR // Communication Block Instances + TCON_DB : TCON; // TCP connection + TRCV_DB : TRCV; // TCP receive + TDISCON_DB : TDISCON; // TCP disconnect +END_VAR + +VAR // Optimized Reception Buffer (23 bytes instead of 128) + aRxBuffer : ARRAY[0..22] OF BYTE; // Optimized buffer size +END_VAR + +VAR // Buffer Management Structure + stBuffer : STRUCT + aCircBuffer : ARRAY[0..255] OF BYTE; // Circular buffer + iWritePtr : INT := 0; // Write pointer + iReadPtr : INT := 0; // Read pointer + iDataInBuffer : INT := 0; // Data in buffer + iRxLength : INT; // Last received length + END_STRUCT; +END_VAR + + +VAR_TEMP + tempByte : BYTE; + tempInt : INT; + tempIntValue : INT; + tempWord : WORD; + tempReal : REAL; + tempTime : TIME; + iAvailable : INT; + iBytesToRead : INT; + tempActualIntervalMs : DINT; // Stores actual interval for current frame processing cycle + tempReceivedID_Char1 : BYTE; + tempDiffDint : DINT; // Temporary DINT for offset adjustment calculation + tempReceivedID_Char2 : BYTE; + tempReceivedID_Val : INT; +END_VAR + +BEGIN + + // --- Read system time --- + tCurrentTime := TIME_TCK(); + + // --- Initialization on first scan --- + IF xFirstScan THEN + xFirstScan := FALSE; + tLastTime := tCurrentTime; + + // Initialize configuration from inputs + stConfig.rFramesPerSecond := rFramesPerSecond; + stConfig.iConnTimeoutSec := iConnTimeoutSec; + stConfig.iDataTimeoutSec := iDataTimeoutSec; + stConfig.iRetryDelaySec := iRetryDelaySec; + stConfig.rBrixMax := rBrixMax; + stConfig.xEnableChecksum := xEnableChecksum; + stConfig.iDeviceID := iDeviceID; + stConfig.xDisableBurstRead := xDisableBurstRead; + + // Clear connection parameters arrays + FOR i := 1 TO 16 DO + stConnParams.local_tsap_id[i] := B#16#00; + stConnParams.rem_tsap_id[i] := B#16#00; + END_FOR; + FOR i := 1 TO 6 DO + stConnParams.rem_subnet_id[i] := B#16#00; + stConnParams.rem_staddr[i] := B#16#00; + stConnParams.next_staddr[i] := B#16#00; + END_FOR; + + // Configure connection parameters + stConnParams.id := wConnectionID; + stConnParams.rem_staddr[1] := aRemoteIP[1]; + stConnParams.rem_staddr[2] := aRemoteIP[2]; + stConnParams.rem_staddr[3] := aRemoteIP[3]; + stConnParams.rem_staddr[4] := aRemoteIP[4]; + + // Remote port configuration + tempWord := INT_TO_WORD(iRemotePort); + stConnParams.rem_tsap_id[1] := WORD_TO_BYTE(SHR(IN:= tempWord, N:= 8)); + stConnParams.rem_tsap_id[2] := WORD_TO_BYTE(tempWord AND W#16#FF); + + // Reset all control variables + xTconReq := FALSE; + xTconReqOld := FALSE; + iCyclesToWait := 0; + stBuffer.iWritePtr := 0; + stBuffer.iReadPtr := 0; + stBuffer.iDataInBuffer := 0; + + // Reset statistics + stStats.diFrameCount := 0; + stStats.diErrorFrameCount := 0; + stStats.diSuccessfulReconCount := 0; + stStats.diChecksumErrorCount := 0; + stStats.diLostFramesCount := 0; + stStats.iConsecutiveBadFrames := 0; + + // Initialize timing parameters + IF stConfig.rFramesPerSecond > 0.1 THEN + stTiming.diFrameIntervalMs := REAL_TO_DINT(1000.0 / stConfig.rFramesPerSecond); + stTiming.iPreReadOffsetMs := DINT_TO_INT(stTiming.diFrameIntervalMs / 6); + stTiming.iMaxActiveReadingMs := DINT_TO_INT(stTiming.diFrameIntervalMs / 3); + IF stTiming.iPreReadOffsetMs < 20 THEN stTiming.iPreReadOffsetMs := 20; END_IF; + IF stTiming.iMaxActiveReadingMs < 50 THEN stTiming.iMaxActiveReadingMs := 50; END_IF; + ELSE + stTiming.diFrameIntervalMs := 1000; + stTiming.iPreReadOffsetMs := 50; + stTiming.iMaxActiveReadingMs := 200; + END_IF; + + stTiming.diEstFrameMs := stTiming.diFrameIntervalMs; + stTiming.diNextFrameMs := 0; + stTiming.diReadingStartMs := 0; + + // Initialize FIFO tables (ordered arrays) + FOR i := 0 TO 9 DO + arBrixHistory[i] := 0.0; + auiTimeHistory[i] := 0; + END_FOR; + + // Initialize other variables + diTimeBetweenFramesMs := 0; + diAccumCycleMs := 0; + iReadingState := 0; // Start in ACTIVE_READING + xTrcvTimeToCall := TRUE; + iCurrentErrorCode := 0; + iConsecutiveGoodFrames := 0; + diInitPhaseTimerMs := 0; + xInitPhaseFinish := FALSE; + END_IF; + + // Calculate elapsed time since last call + IF tCurrentTime >= tLastTime THEN + diElapsedMs := TIME_TO_DINT(tCurrentTime - tLastTime); + if diElapsedMs > 1000 THEN + diElapsedMs := 1000; // Cap at 1 second + END_IF; + ELSE + diElapsedMs := 1; // Handle wrap-around + END_IF; + tLastTime := tCurrentTime; + + // --- Diagnostic outputs --- + stDiag.diState := iState; + stDiag.diTconStatus := TCON_DB.STATUS; + stDiag.diTrcvStatus := TRCV_DB.STATUS; + diReadingState := iReadingState; + stDiag.diNextExpectedMs := stTiming.diNextFrameMs; + stDiag.diCalcFrameIntervalMs := stTiming.diFrameIntervalMs; + stDiag.iCalcPreReadOffsetMs := stTiming.iPreReadOffsetMs; + stDiag.iCalcMaxActiveMs := stTiming.iMaxActiveReadingMs; + + // --- Error code evaluation (higher number = higher priority) --- + iCurrentErrorCode := 0; + + // Priority 1: Checksum errors + IF stStats.diChecksumErrorCount > 0 AND diAccumCycleMs < 5000 THEN + iCurrentErrorCode := 1; + END_IF; + + // Priority 2: Frame format errors + IF stStats.diErrorFrameCount > 0 AND diAccumCycleMs < 5000 THEN + iCurrentErrorCode := 2; + END_IF; + + // Priority 4: Data out of range + IF rCurrentMA > 0.0 AND (rCurrentMA < 4.0 OR rCurrentMA > 20.0) AND + diAccumCycleMs < 2000 THEN + iCurrentErrorCode := 4; + END_IF; + + // Priority 5: Multiple consecutive bad frames + IF stStats.iConsecutiveBadFrames >= 5 THEN + iCurrentErrorCode := 5; + END_IF; + + // Priority 6: Lost frames + IF stStats.diLostFramesCount > 0 AND stTiming.diEstFrameMs > 0 AND + diAccumCycleMs > (stTiming.diEstFrameMs * 2) THEN + iCurrentErrorCode := 6; + END_IF; + + // Priority 7-8: TRCV errors + IF TRCV_DB.ERROR THEN + IF TRCV_DB.STATUS = W#16#8088 THEN + iCurrentErrorCode := 7; + ELSE + iCurrentErrorCode := 8; + END_IF; + END_IF; + + // Priority 9: Data timeout + IF tonNoDataTimeout.Q THEN + iCurrentErrorCode := 9; + END_IF; + + // Priority 10: Connection timeout + IF tonConnTimeout.Q THEN + iCurrentErrorCode := 10; + END_IF; + + // Priority 11: Connection failed + IF TCON_DB.ERROR THEN + iCurrentErrorCode := 11; + END_IF; + + // Priority 12: Connection terminated + IF (TRCV_DB.STATUS = W#16#80A3) OR (TRCV_DB.STATUS = W#16#80C4) THEN + iCurrentErrorCode := 12; + END_IF; + + // Set final error outputs + iErrorCode := iCurrentErrorCode; + xError := (iCurrentErrorCode > 0); + + // --- Reset pulse outputs --- + xDataValid := FALSE; + + // --- Pulse control for TCON --- + xTconPulse := xTconReq AND NOT xTconReqOld; + xTconReqOld := xTconReq; + + // Enhanced Reading State Machine with Initialization Phase + IF iState <> 3 THEN // Only run reading states when in READING main state + iReadingState := 0; // Reset reading state + xInitPhaseFinish := FALSE; // Reset initialization phase finish + diAccumCycleMs := 0; // Reset cycle accumulator + diInitPhaseTimerMs := 0; // Reset init phase timer + iConsecutiveGoodFrames := 0; // Reset counter when not in active reading cycle + stTiming.diEstFrameMs := stTiming.diFrameIntervalMs; + ELSE // iState = 3: READING + + IF stStats.iConsecutiveBadFrames <= 5 THEN + diAccumCycleMs := diAccumCycleMs + diElapsedMs; + END_IF; + + IF NOT xInitPhaseFinish THEN + diInitPhaseTimerMs := diInitPhaseTimerMs + diElapsedMs; + END_IF; + + CASE iReadingState OF + 0: // ACTIVE_READING - Receiving data burst, read intensively + xTrcvTimeToCall := TRUE; // Read every cycle + + // During initialization phase, skip PAUSED state + IF xInitPhaseFinish THEN + // Normal operation - can transition to PAUSED + IF (stTiming.diNextFrameMs - diAccumCycleMs) > INT_TO_DINT(stTiming.iMaxActiveReadingMs) THEN + iReadingState := 2; // Go to PAUSED + xTrcvTimeToCall := FALSE; + END_IF; + END_IF; + + 1: // COMPLETED - Finished reading a valid frame + xTrcvTimeToCall := FALSE; + + // Capture the actual time elapsed for this frame cycle before resetting diAccumCycleMs + tempActualIntervalMs := diAccumCycleMs; + + // --- Time Between Frames Calculation --- + // Only update diTimeBetweenFramesMs if the current and previous frames were good. + IF iConsecutiveGoodFrames >= 2 THEN + diTimeBetweenFramesMs := tempActualIntervalMs; + END_IF; + // Always reset diAccumCycleMs for the next interval measurement. + diAccumCycleMs := 0; + + // Update estimated frame interval (stTiming.diEstFrameMs) + IF NOT xInitPhaseFinish THEN + // During initialization, if we have a fresh reliable interval, use it directly. + IF iConsecutiveGoodFrames >= 2 AND diTimeBetweenFramesMs > 0 THEN + stTiming.diEstFrameMs := diTimeBetweenFramesMs; + END_IF; + // ELSE stTiming.diEstFrameMs remains its initial value (from config) + ELSE + // After initialization, smooth the estimate if diTimeBetweenFramesMs is valid. + IF diTimeBetweenFramesMs > 0 THEN + stTiming.diEstFrameMs := (stTiming.diEstFrameMs * 3 + diTimeBetweenFramesMs) / 4; // Smoothing + ELSE + // If diTimeBetweenFramesMs is not positive (e.g. never set, or problem), revert to default. + stTiming.diEstFrameMs := stTiming.diFrameIntervalMs; + END_IF; + END_IF; + + // Set next expected frame time + stTiming.diNextFrameMs := stTiming.diEstFrameMs; + + // --- Dynamically adjust iPreReadOffsetMs (User Optimization) --- + // Adjust only after initialization and with stable timing data. + // Limits for iPreReadOffsetMs: 5ms to 50ms. + IF xInitPhaseFinish AND (iConsecutiveGoodFrames >= 2) THEN + // tempDiffDint = Estimated Interval for Next Frame - Actual Interval of Last Frame + tempDiffDint := stTiming.diNextFrameMs - diTimeBetweenFramesMs; + + IF tempDiffDint < INT_TO_DINT(stTiming.iPreReadOffsetMs) THEN + IF stTiming.iPreReadOffsetMs > 5 THEN + stTiming.iPreReadOffsetMs := stTiming.iPreReadOffsetMs - 1; + END_IF; + ELSIF tempDiffDint > INT_TO_DINT(stTiming.iPreReadOffsetMs) THEN + IF stTiming.iPreReadOffsetMs < 50 THEN + stTiming.iPreReadOffsetMs := stTiming.iPreReadOffsetMs + 1; + END_IF; + END_IF; + END_IF; + + // Detect lost frames based on the *actual* interval for the just-completed frame cycle + // compared to the current estimate of frame interval. + IF stTiming.diEstFrameMs > 0 AND tempActualIntervalMs > (stTiming.diEstFrameMs * 3 / 2) THEN + tempInt := DINT_TO_INT(tempActualIntervalMs / stTiming.diEstFrameMs) - 1; + IF tempInt > 0 THEN + stStats.diLostFramesCount := stStats.diLostFramesCount + INT_TO_DINT(tempInt); + END_IF; + END_IF; + iReadingState := 2; + + 2: // PAUSED - Not reading, waiting for next frame window + // Ensure iConsecutiveGoodFrames is reset if we are paused for a long time or before starting a new read attempt. + // This is mainly handled by the iState <> 3 check, but can be reinforced if needed. + IF NOT xInitPhaseFinish OR stConfig.xDisableBurstRead THEN + iReadingState := 0; + ELSE // Only used when xInitPhaseFinish = TRUE + IF (stTiming.diNextFrameMs - diAccumCycleMs) <= INT_TO_DINT(stTiming.iPreReadOffsetMs) THEN + iReadingState := 0; // Go to ACTIVE_READING + stTiming.diReadingStartMs := diAccumCycleMs; + ELSE + xTrcvTimeToCall := FALSE; + END_IF; + END_IF; + + END_CASE; + END_IF; + + // --- Main State Machine --- + CASE iState OF + 0: // IDLE + xConnected := FALSE; + wErrorCode := W#16#0000; + + // Retry delay + tempTime := DINT_TO_TIME(INT_TO_DINT(stConfig.iRetryDelaySec) * 1000); + tonRetryDelay(IN := TRUE, PT := tempTime); + + IF xEnable AND tonRetryDelay.Q THEN + tonRetryDelay(IN := FALSE); + + // Intentar desconectar primero por seguridad + xTdisconReq := TRUE; + TDISCON_DB(REQ := xTdisconReq, ID := wConnectionID); + + // Resetear variables de control + xTconReq := FALSE; + xTconReqOld := FALSE; + iCyclesToWait := 0; + stBuffer.iWritePtr := 0; + stBuffer.iReadPtr := 0; + stBuffer.iDataInBuffer := 0; + iState := 1; + ELSIF NOT xEnable THEN + tonRetryDelay(IN := FALSE); + xTdisconReq := FALSE; + TDISCON_DB(REQ := FALSE, ID := wConnectionID); + END_IF; + + 1: // CONNECT - Prepare connection + iCyclesToWait := iCyclesToWait + 1; + IF iCyclesToWait >= 2 THEN + iCyclesToWait := 0; + xTconReq := TRUE; + xTconReqOld := FALSE; // ← AGREGAR ESTA LÍNEA + iState := 2; + END_IF; + + 2: // WAIT CONNECT - Wait for connection + TCON_DB( + REQ := xTconReq, // xTconPulse, + ID := wConnectionID, + CONNECT := stConnParams + ); + + tempTime := DINT_TO_TIME(INT_TO_DINT(stConfig.iConnTimeoutSec) * 1000); + tonConnTimeout(IN := TRUE, PT := tempTime); + tonNoDataTimeout(IN := FALSE); + + IF TCON_DB.DONE THEN + xTconReq := FALSE; + xConnected := TRUE; + tonConnTimeout(IN := FALSE); + stStats.diSuccessfulReconCount := stStats.diSuccessfulReconCount + 1; + + // Start initialization phase + diAccumCycleMs := 0; // Reset cycle accumulator when entering reading state + iReadingState := 0; // Start in ACTIVE_READING + diInitPhaseTimerMs := 0; // Reset init phase timer + stTiming.diReadingStartMs := 0; + + iState := 3; // Go to continuous reading + ELSIF TCON_DB.ERROR THEN + IF TCON_DB.STATUS = W#16#80A3 THEN + // Conexión ya existe - ir a disconnect primero + xTconReq := FALSE; + xTconReqOld := FALSE; + iState := 4; + ELSE + xTconReq := FALSE; + xTconReqOld := FALSE; + wErrorCode := TCON_DB.STATUS; + tonConnTimeout(IN := FALSE); + iState := 4; + END_IF; + ELSIF tonConnTimeout.Q THEN + xTconReq := FALSE; + xTconReqOld := FALSE; + wErrorCode := W#16#8001; + tonConnTimeout(IN := FALSE); + iState := 4; + END_IF; + + IF NOT xEnable THEN + xTconReq := FALSE; + tonConnTimeout(IN := FALSE); + iState := 4; + END_IF; + + 3: // READING - Enhanced reading with initialization phase + + // Call TRCV based on reading state + IF xTrcvTimeToCall THEN + TRCV_DB( + EN_R := TRUE, + ID := wConnectionID, + LEN := 0, // Ad-hoc mode + DATA := aRxBuffer // Optimized 23-byte buffer + ); + ELSE + TRCV_DB( + EN_R := FALSE, + ID := wConnectionID, + LEN := 0, + DATA := aRxBuffer + ); + END_IF; + + // Process TRCV result + IF TRCV_DB.NDR THEN + stBuffer.iRxLength := TRCV_DB.RCVD_LEN; + tonNoDataTimeout(IN := FALSE); + + // Copy data to circular buffer + FOR i := 0 TO (stBuffer.iRxLength - 1) DO + stBuffer.aCircBuffer[stBuffer.iWritePtr] := aRxBuffer[i]; + stBuffer.iWritePtr := (stBuffer.iWritePtr + 1) MOD 256; + stBuffer.iDataInBuffer := stBuffer.iDataInBuffer + 1; + IF stBuffer.iDataInBuffer > 256 THEN + stBuffer.iDataInBuffer := 256; + stBuffer.iReadPtr := (stBuffer.iReadPtr + 1) MOD 256; + END_IF; + END_FOR; + + // --- Process frames in circular buffer --- + WHILE stBuffer.iDataInBuffer >= 12 DO + // Find first '#' + iStartPos := -1; + FOR j := 0 TO (stBuffer.iDataInBuffer - 1) DO + tempInt := (stBuffer.iReadPtr + j) MOD 256; + IF stBuffer.aCircBuffer[tempInt] = B#16#23 THEN + iStartPos := j; + EXIT; + END_IF; + END_FOR; + + IF iStartPos >= 0 THEN + // Discard bytes before '#' + IF iStartPos > 0 THEN + stBuffer.iReadPtr := (stBuffer.iReadPtr + iStartPos) MOD 256; + stBuffer.iDataInBuffer := stBuffer.iDataInBuffer - iStartPos; + END_IF; + + IF stBuffer.iDataInBuffer >= 12 THEN + // Check format: '.' at position 5 + IF stBuffer.aCircBuffer[(stBuffer.iReadPtr + 5) MOD 256] = B#16#2E THEN + // Copy frame + FOR i := 0 TO 11 DO + aFrame[i] := stBuffer.aCircBuffer[(stBuffer.iReadPtr + i) MOD 256]; + END_FOR; + + // --- Validate Device ID (if enabled) --- + // Adam address is in aFrame[1] and aFrame[2] + IF stConfig.iDeviceID > 0 AND stConfig.iDeviceID <= 99 THEN + tempReceivedID_Char1 := aFrame[1]; + tempReceivedID_Char2 := aFrame[2]; + + // Check if ID characters are digits + IF (BYTE_TO_INT(tempReceivedID_Char1) >= 16#30 AND BYTE_TO_INT(tempReceivedID_Char1) <= 16#39) AND + (BYTE_TO_INT(tempReceivedID_Char2) >= 16#30 AND BYTE_TO_INT(tempReceivedID_Char2) <= 16#39) THEN + + tempReceivedID_Val := (BYTE_TO_INT(tempReceivedID_Char1) - 16#30) * 10 + + (BYTE_TO_INT(tempReceivedID_Char2) - 16#30); + + IF tempReceivedID_Val <> stConfig.iDeviceID THEN + // ID Mismatch + stStats.diErrorFrameCount := stStats.diErrorFrameCount + 1; + stStats.iConsecutiveBadFrames := stStats.iConsecutiveBadFrames + 1; + iConsecutiveGoodFrames := 0; + stBuffer.iReadPtr := (stBuffer.iReadPtr + 12) MOD 256; + stBuffer.iDataInBuffer := stBuffer.iDataInBuffer - 12; + CONTINUE; + END_IF; + ELSE + // Invalid characters for ID in frame + stStats.diErrorFrameCount := stStats.diErrorFrameCount + 1; + stStats.iConsecutiveBadFrames := stStats.iConsecutiveBadFrames + 1; + iConsecutiveGoodFrames := 0; + stBuffer.iReadPtr := (stBuffer.iReadPtr + 12) MOD 256; + stBuffer.iDataInBuffer := stBuffer.iDataInBuffer - 12; + CONTINUE; + END_IF; + END_IF; + + // Validate digit characters + IF (BYTE_TO_INT(aFrame[3]) >= 16#30 AND BYTE_TO_INT(aFrame[3]) <= 16#39) AND + (BYTE_TO_INT(aFrame[4]) >= 16#30 AND BYTE_TO_INT(aFrame[4]) <= 16#39) AND + (BYTE_TO_INT(aFrame[6]) >= 16#30 AND BYTE_TO_INT(aFrame[6]) <= 16#39) AND + (BYTE_TO_INT(aFrame[7]) >= 16#30 AND BYTE_TO_INT(aFrame[7]) <= 16#39) AND + (BYTE_TO_INT(aFrame[8]) >= 16#30 AND BYTE_TO_INT(aFrame[8]) <= 16#39) THEN + + // Checksum validation + IF stConfig.xEnableChecksum THEN + iChecksumSum := 0; + FOR i := 0 TO 8 DO + iChecksumSum := iChecksumSum + BYTE_TO_INT(aFrame[i]); + END_FOR; + bCalculatedChecksum := INT_TO_BYTE(iChecksumSum MOD 256); + + // Extract received checksum + tempInt := BYTE_TO_INT(aFrame[9]); + IF tempInt >= 16#30 AND tempInt <= 16#39 THEN + tempInt := tempInt - 16#30; + ELSIF tempInt >= 16#41 AND tempInt <= 16#46 THEN + tempInt := tempInt - 16#37; + ELSIF tempInt >= 16#61 AND tempInt <= 16#66 THEN + tempInt := tempInt - 16#57; + ELSE + tempInt := 0; + END_IF; + bReceivedChecksum := INT_TO_BYTE(tempInt * 16); + + tempInt := BYTE_TO_INT(aFrame[10]); + IF tempInt >= 16#30 AND tempInt <= 16#39 THEN + tempInt := tempInt - 16#30; + ELSIF tempInt >= 16#41 AND tempInt <= 16#46 THEN + tempInt := tempInt - 16#37; + ELSIF tempInt >= 16#61 AND tempInt <= 16#66 THEN + tempInt := tempInt - 16#57; + ELSE + tempInt := 0; + END_IF; + bReceivedChecksum := bReceivedChecksum OR INT_TO_BYTE(tempInt); + + IF bCalculatedChecksum <> bReceivedChecksum THEN + stStats.diChecksumErrorCount := stStats.diChecksumErrorCount + 1; + stStats.iConsecutiveBadFrames := stStats.iConsecutiveBadFrames + 1; + iConsecutiveGoodFrames := 0; // Reset consecutive good frames counter + stBuffer.iReadPtr := (stBuffer.iReadPtr + 12) MOD 256; + stBuffer.iDataInBuffer := stBuffer.iDataInBuffer - 12; + CONTINUE; + END_IF; + END_IF; + + // Parse valid frame + // At this point, frame is structurally good (format, digits, checksum OK or disabled) + iConsecutiveGoodFrames := iConsecutiveGoodFrames + 1; + IF iConsecutiveGoodFrames > 2 THEN // Cap at 2 for "last two frames" logic + iConsecutiveGoodFrames := 2; + END_IF; + stStats.iConsecutiveBadFrames := 0; // Reset consecutive bad *structural* frames counter + tempIntValue := 0; + tempInt := BYTE_TO_INT(aFrame[3]); + tempIntValue := (tempInt - 16#30) * 10; + tempInt := BYTE_TO_INT(aFrame[4]); + tempIntValue := tempIntValue + (tempInt - 16#30); + rCurrentMA := INT_TO_REAL(tempIntValue); + + tempInt := BYTE_TO_INT(aFrame[6]); + rCurrentMA := rCurrentMA + INT_TO_REAL(tempInt - 16#30) / 10.0; + tempInt := BYTE_TO_INT(aFrame[7]); + rCurrentMA := rCurrentMA + INT_TO_REAL(tempInt - 16#30) / 100.0; + tempInt := BYTE_TO_INT(aFrame[8]); + rCurrentMA := rCurrentMA + INT_TO_REAL(tempInt - 16#30) / 1000.0; + + // Calculate Brix + IF (rCurrentMA >= 4.0) AND (rCurrentMA <= 20.0) THEN + rBrixValue := (rCurrentMA - 4.0) * stConfig.rBrixMax / 16.0; + + // *** UPDATE FIFO TABLES (if enabled) *** + IF xEnableFifoDebug THEN + // Shift all elements up (newest at [0], oldest discarded at [9]) + FOR tempInt := 9 TO 1 BY -1 DO + arBrixHistory[tempInt] := arBrixHistory[tempInt - 1]; + auiTimeHistory[tempInt] := auiTimeHistory[tempInt - 1]; + END_FOR; + // Insert new values at [0] + arBrixHistory[0] := rBrixValue; + auiTimeHistory[0] := DINT_TO_INT(diAccumCycleMs MOD 32767); // Convert to UINT + END_IF; + + // Set data valid pulse + xDataValid := TRUE; + + // Check if initialization phase should finish + IF NOT xInitPhaseFinish AND diInitPhaseTimerMs > (stTiming.diFrameIntervalMs * 2) THEN + IF stBuffer.iRxLength = 12 THEN + xInitPhaseFinish := TRUE; // Synchronized and clean buffer + END_IF; + END_IF; + + // Update moving average + IF stDiag.rAvgCurrentMA = 0.0 THEN + stDiag.rAvgCurrentMA := rCurrentMA; + ELSE + stDiag.rAvgCurrentMA := stDiag.rAvgCurrentMA * 0.9 + rCurrentMA * 0.1; + END_IF; + + // stStats.iConsecutiveBadFrames already reset as frame is structurally good + END_IF; + + // Frame processing complete - transition to COMPLETED + iReadingState := 1; + + // Increment frame counter + stStats.diFrameCount := stStats.diFrameCount + 1; + IF stStats.diFrameCount >= DINT#2000000000 THEN + stStats.diFrameCount := 0; + END_IF; + + ELSE // Invalid digits + stStats.diErrorFrameCount := stStats.diErrorFrameCount + 1; + stStats.iConsecutiveBadFrames := stStats.iConsecutiveBadFrames + 1; + iConsecutiveGoodFrames := 0; // Reset consecutive good frames counter + END_IF; + + ELSE // Invalid format (no '.' at position 5) + stStats.diErrorFrameCount := stStats.diErrorFrameCount + 1; + stStats.iConsecutiveBadFrames := stStats.iConsecutiveBadFrames + 1; + iConsecutiveGoodFrames := 0; // Reset consecutive good frames counter + END_IF; + + // Discard processed frame + stBuffer.iReadPtr := (stBuffer.iReadPtr + 12) MOD 256; + stBuffer.iDataInBuffer := stBuffer.iDataInBuffer - 12; + + ELSE // Not enough bytes for full frame + EXIT; + END_IF; + + ELSE // No '#' found + stBuffer.iReadPtr := (stBuffer.iReadPtr + stBuffer.iDataInBuffer) MOD 256; + stBuffer.iDataInBuffer := 0; + EXIT; + END_IF; + END_WHILE; + + ELSIF TRCV_DB.ERROR THEN + IF (TRCV_DB.STATUS = W#16#80A3) OR (TRCV_DB.STATUS = W#16#80C4) THEN + xConnected := FALSE; + TCON_DB(REQ := FALSE, ID := wConnectionID, CONNECT := stConnParams); + TRCV_DB(EN_R := FALSE, ID := wConnectionID, LEN := 0, DATA := aRxBuffer); + IF xTdisconReq THEN + xTdisconReq := FALSE; + TDISCON_DB(REQ := FALSE, ID := wConnectionID); + END_IF; + tonNoDataTimeout(IN := FALSE); + iState := 0; + ELSIF TRCV_DB.STATUS = W#16#8088 THEN + tonNoDataTimeout(IN := FALSE); + ELSE + wErrorCode := TRCV_DB.STATUS; + xConnected := FALSE; + iState := 4; + END_IF; + END_IF; + + // Data timeout check - limited by diAccumCycleMs max = iDataTimeoutSec + tempTime := DINT_TO_TIME(INT_TO_DINT(stConfig.iDataTimeoutSec) * 1000); + tonNoDataTimeout(IN := TRUE, PT := tempTime); + IF tonNoDataTimeout.Q THEN + wErrorCode := W#16#8002; + iState := 4; + END_IF; + + IF NOT xEnable THEN + iState := 4; + END_IF; + + 4: // DISCONNECT + xTdisconReq := TRUE; + TDISCON_DB( + REQ := xTdisconReq, + ID := wConnectionID + ); + + tonDisconTimeout(IN := xTdisconReq, PT := T#2S); + + IF TDISCON_DB.DONE OR TDISCON_DB.ERROR OR tonDisconTimeout.Q THEN + xTdisconReq := FALSE; + TDISCON_DB(REQ := xTdisconReq, ID := wConnectionID); + xConnected := FALSE; + tonDisconTimeout(IN := FALSE); + TCON_DB(REQ := FALSE, ID := wConnectionID, CONNECT := stConnParams); + TRCV_DB(EN_R := FALSE, ID := wConnectionID, LEN := 0, DATA := aRxBuffer); + iState := 0; + END_IF; + + END_CASE; + +END_FUNCTION_BLOCK + +``` \ No newline at end of file diff --git a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Hardware used for 485-TCP.md b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Hardware used for 485-TCP.md new file mode 100644 index 0000000..9ec616f --- /dev/null +++ b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Hardware used for 485-TCP.md @@ -0,0 +1,12 @@ + + +### Gateways: +*** +* Phoenix: [FL COMSERVER UNI 232/422/485 - Interface converters - 2313452 \| Phoenix Contact](https://www.phoenixcontact.com/en-pc/products/interface-converters-fl-comserver-uni-232-422-485-2313452) +* Waveshare: [Waveshare 4-Ch RS485 to RJ45 Ethernet Serial Server, 4 Channels RS485 Independent Operation, Rail-Mount Industrial Isolated Serial Module, Modbus Gateway, PoE Ethernet Port : Amazon.it: Informatica](https://www.amazon.it/Waveshare-Independent-Operation-Rail-Mount-Industrial/dp/B0CQYGDMDK/ref=sr_1_9?__mk_it_IT=%C3%85M%C3%85%C5%BD%C3%95%C3%91&crid=2XU08FRZO930E&dib=eyJ2IjoiMSJ9.lZgZ_MD-K6Zaz6mtlp9b5bUbCBRkGA0GE4U4zHPabq6YKvG_WrwkzwIiUpUOYrHCb4jZetzrol1ZPaPPx1JzaT31o6kyr9wVZgIStLHTld2jvutCFal_gAXLT8oO3DxChmyCC5WLLi23Km1jf_E26TPjmR0R1Bn0-kBDhsexPWVs2CTxtAdjq-PFtdh0RarBaPfgrdDnyH4WxbnOh_xZ00Ur1v1HJ7ewmwO7xpTwDoc.6bYrjn09M8M-tMlbvo0Nt6HRykvnWILBmoJl_F3eKfs&dib_tag=se&keywords=485+ethernet&qid=1748331701&sprefix=485+ethernet%2Cspecialty-aps%2C91&sr=8-9&srs=19998714031) +* MOXA: [NPort 5230A Moxa](https://it.wiautomation.com/moxa/comunicazione-industriale/comunicazione-industriale/nport5230a?utm_source=google&utm_medium=cpc&utm_campaign=IT_pmax_new_insert_3&gad_source=1&gad_campaignid=17337730689&gclid=Cj0KCQjwxdXBBhDEARIsAAUkP6hF-BZL17vGTrIQF4l8JuAAtxR-JJX3OxC5akIyDTQDlPZjL0wtNZsaArO8EALw_wcB) + + + +[[Waveshare RS232-485 Ethernet - Wifi - ADAM 4021 - Using Serial200]] + diff --git a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Versiones.md b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Versiones.md new file mode 100644 index 0000000..78069ab --- /dev/null +++ b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/Versiones.md @@ -0,0 +1,38 @@ +*** + + + +### Ver 1.7 a 1.8: + +```pascal +Quisiera implementar los siguientes cambios: + +# Datos: + + 1) Mejora de los datos estaticos, no los in o out o temp, usando struct para poder leer mejor desde la DB. Los struct se pueden dividir por conceptos + 2) Dejar en la parte inferior de la DB las instancias de otras FB o datos internos del script + 3) Crear y gestionar una nueva tabla FIFO con los ultimas 10 lecturas en Brix y otra tabla con el tiempo diAccumCycleMs en cada lectura + +# Logica: + +1) Optimización del Buffer +Cambiar tamaño del buffer de recepción: +aRxBuffer : ARRAY[0..22] OF BYTE; // De 128 a 23 bytes +Esto descarta automáticamente tramas antiguas manteniendo solo la más reciente + +2) iReadingState + + 0: // ACTIVE_READING - Receiving data burst, read intensively + 1: // COMPLETED - Finished reading a valid frame, return to paused + 2: // PAUSED - Not reading, waiting for next frame window + +Cuando se comienza una secuencia de lectura luego de iState n a 3 el flag xInitPhaseFinish es False y se resetan los calculos de tiempo de ciclo a dafault +Mientras este flag esta en false iReadingState salta el estado 2 de Paused. Esto permite limpiar el buffer y sincronizar las lecturas con la velocidad de lectura del server +Duración: (diFrameIntervalMs*2) después de conectar. Timer independiente +Luego de terminado el timer y se cumplen las condiciones de xDataValid = TRUE y iRxLength = 12 significa que estamos sincronizados y sin buffer. Se hace xInitPhaseFinish := True y el iReadingState = 2 comienza a funcionar. + +Durante la fase de xInitPhaseFinish = false cada ciclo de iReadingState = 1 ( completed ) fue calculando los tiempos como en el script actual + + +3) diAccumCycleMs solo se incrementa con el iState = 3. Al hacer reset de los calculos de tiempo en iState = 2 se pone a 0 diAccumCycleMs, esto deberia limitar diAccumCycleMs a iDataTimeoutSec ya que si no hay datos por mas de iDataTimeoutSec se pasa a iState := 4 +``` \ No newline at end of file diff --git a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250526165501.png b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250526165501.png new file mode 100644 index 0000000..077753a Binary files /dev/null and b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250526165501.png differ diff --git a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250529221334.png b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250529221334.png new file mode 100644 index 0000000..39182b2 Binary files /dev/null and b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250529221334.png differ diff --git a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250529221344.png b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250529221344.png new file mode 100644 index 0000000..e61451b Binary files /dev/null and b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250529221344.png differ diff --git a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250530095053.png b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250530095053.png new file mode 100644 index 0000000..01835b1 Binary files /dev/null and b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250530095053.png differ diff --git a/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250530095111.png b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250530095111.png new file mode 100644 index 0000000..fe7edbf Binary files /dev/null and b/04-SIDEL/09 - SAE452 - Diet as Regular - San Giovanni in Bosco/FB2120 - MasseliTCP/adjuntos/Pasted image 20250530095111.png differ