Now, I have decided to use ModbusTCP server running on the PLC side, Golang as the…
- User
Now, I have decided to use ModbusTCP server running on the PLC side, Golang as the development environment on the linux PC with the InfluxDB. On the STM32 side still undecded.
Assistant
Industrial Data Collection System with ModbusTCP and Golang
Given your updated technology choices, I'll outline a solution using ModbusTCP for PLC communication and Golang for the Linux PC side.
System Architecture
- ControlLogix PLC running ModbusTCP server → Data source
- Debian Linux PC with Golang and InfluxDB → Data storage and processing
- NUCLEO-H755ZI-Q + X-NUCLEO-NFC07A1 → NFC data transmission
- Smartphone → NFC tag reading and data display
PLC to InfluxDB Data Flow (Golang Implementation)
1. ModbusTCP Client in Golang
package main import ( "context" "log" "time" "github.com/goburrow/modbus" influxdb2 "github.com/influxdata/influxdb-client-go/v2" ) func main() { // ModbusTCP client setup handler := modbus.NewTCPClientHandler("192.168.1.10:502") // PLC IP and Modbus port handler.Timeout = 10 * time.Second handler.SlaveId = 1 err := handler.Connect() if err != nil { log.Fatal("ModbusTCP connection error:", err) } defer handler.Close() client := modbus.NewClient(handler) // InfluxDB client setup influx := influxdb2.NewClient("http://localhost:8086", "your-influxdb-token") defer influx.Close() writeAPI := influx.WriteAPI("your-org", "your-bucket") // Poll data from PLC for { // Read holding registers (adjust register address and count as needed) registers, err := client.ReadHoldingRegisters(0, 10) if err != nil { log.Println("Failed to read from PLC:", err) time.Sleep(5 * time.Second) continue } // Create data point with tag and field p := influxdb2.NewPoint( "plc_data", map[string]string{"device": "controllogix"}, map[string]interface{}{ "value1": uint16(registers[0])<<8 | uint16(registers[1]), "value2": uint16(registers[2])<<8 | uint16(registers[3]), }, time.Now(), ) // Write to InfluxDB writeAPI.WritePoint(p) writeAPI.Flush() time.Sleep(1 * time.Second) } }2. InfluxDB Data Retrieval for NFC (Golang HTTP Server)
package main import ( "context" "encoding/json" "log" "net/http" "time" influxdb2 "github.com/influxdata/influxdb-client-go/v2" ) type DataPoint struct { Timestamp time.Time Value float64 } func main() { // InfluxDB client client := influxdb2.NewClient("http://localhost:8086", "your-influxdb-token") defer client.Close() queryAPI := client.QueryAPI("your-org") // HTTP server to provide data to the STM32 http.HandleFunc("/latest-data", func(w http.ResponseWriter, r *http.Request) { // Query the latest data point query := `from(bucket:"your-bucket") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "plc_data") |> last()` result, err := queryAPI.Query(context.Background(), query) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } var dataPoints []DataPoint for result.Next() { record := result.Record() dp := DataPoint{ Timestamp: record.Time(), Value: record.Value().(float64), } dataPoints = append(dataPoints, dp) } // Convert to JSON and send response w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(dataPoints) }) log.Println("Server starting on :8000") log.Fatal(http.ListenAndServe(":8000", nil)) }STM32 Options for Data Retrieval and NFC Transmission
Since you're undecided on the STM32 approach, here are the best options:
Option 1: STM32CubeIDE with C (Most Control and Performance)
/* Network and HTTP client setup to query the Golang server */ #include "stm32h7xx_hal.h" #include "lwip.h" #include "http_client.h" #include "st25dv_driver.h" #define SERVER_IP "192.168.1.100" #define SERVER_PORT 8000 #define ENDPOINT "/latest-data" uint8_t nfc_buffer[256]; char http_response[1024]; void fetch_and_transmit_data(void) { // HTTP GET request to Golang server if (http_get(SERVER_IP, SERVER_PORT, ENDPOINT, http_response, sizeof(http_response)) > 0) { // Parse JSON response // Simplified - in real implementation use a JSON parser sprintf((char*)nfc_buffer, "PLC Data: %s", http_response); // Write to NFC tag ST25DV_WriteData(0, nfc_buffer, strlen((char*)nfc_buffer)); } } int main(void) { // Initialize HAL, network, NFC module HAL_Init(); MX_LWIP_Init(); ST25DV_Init(); while (1) { fetch_and_transmit_data(); HAL_Delay(5000); // Update every 5 seconds } }Option 2: Arduino Framework on STM32 (Easier Development)
#include <SPI.h> #include <Ethernet.h> #include <ArduinoJson.h> #include <ST25DVLibrary.h> byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress server(192, 168, 1, 100); EthernetClient client; ST25DV st25dv; void setup() { Serial.begin(115200); Ethernet.begin(mac); st25dv.begin(); // Wait for network delay(1000); } void loop() { StaticJsonDocument<512> doc; char nfcData[256]; // Connect to server if (client.connect(server, 8000)) { // Make HTTP request client.println("GET /latest-data HTTP/1.1"); client.println("Host: 192.168.1.100"); client.println("Connection: close"); client.println(); // Skip HTTP headers while (client.connected()) { String line = client.readStringUntil('\n'); if (line == "\r") break; } // Parse JSON response DeserializationError error = deserializeJson(doc, client); client.stop(); if (!error) { // Format data for NFC float value = doc[0]["Value"]; sprintf(nfcData, "PLC Value: %.2f", value); // Write to NFC tag st25dv.writeText(nfcData); Serial.println("Updated NFC tag"); } } delay(5000); }Smartphone NFC Reading
For the smartphone side, you can either use a standard NFC app like NFC Tools or develop a custom app. Here's a simple Android Kotlin example for a custom app:
class MainActivity : AppCompatActivity() { private lateinit var nfcAdapter: NfcAdapter private lateinit var pendingIntent: PendingIntent private lateinit var dataTextView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) dataTextView = findViewById(R.id.dataTextView) // Initialize NFC nfcAdapter = NfcAdapter.getDefaultAdapter(this) pendingIntent = PendingIntent.getActivity(this, 0, Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE) } override fun onResume() { super.onResume() nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null) } override fun onPause() { super.onPause() nfcAdapter.disableForegroundDispatch(this) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action) { intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)?.also { rawMessages -> val message = (rawMessages[0] as NdefMessage) val record = message.records[0] val payload = record.payload // Skip language code (first byte) val text = String(payload, 1, payload.size - 1, Charset.forName("UTF-8")) dataTextView.text = text } } } }Integration Notes
-
Network Configuration: Ensure all devices are on the same network or can route to each other.
-
Data Format: Keep the NFC data compact (NDEF format is recommended).
-
Security Considerations:
- Add authentication to the Golang HTTP server
- Consider encrypting sensitive industrial data
-
STM32 Decision Factors:
- If you need maximum performance: Use STM32CubeIDE with C/C++
- If you want faster development: Use Arduino framework
- Consider available libraries for HTTP, JSON parsing, and NFC
Would you like more specific details on any part of this implementation, or do you have a preference for the STM32 approach?
- User
Will use the mongoose tcp library on the STM development board because it has robust support for modbus, mqtt, and http plus it has a built in dashboard.
Assistant
Industrial Data Solution with Mongoose Library on STM32
Excellent choice using Mongoose TCP library on the STM32 board! Mongoose provides robust networking capabilities with built-in support for the protocols you need, plus a dashboard for monitoring.
System Architecture with Mongoose
- ControlLogix PLC (ModbusTCP Server) → Data source
- Debian Linux PC (Golang + InfluxDB) → Data aggregation and storage
- NUCLEO-H755ZI-Q + Mongoose + X-NUCLEO-NFC07A1 → Networking, dashboard, and NFC transmission
- Smartphone → NFC data consumer
STM32 Implementation with Mongoose
Core Implementation
#include "mongoose.h" #include "st25dv_driver.h" // Configuration #define DASHBOARD_PORT 80 #define MODBUS_SERVER "192.168.1.10:502" // PLC address #define INFLUX_SERVER "192.168.1.100:8000" // Your Golang server #define POLL_INTERVAL_MS 5000 // Global variables static struct mg_mgr mgr; static struct mg_connection *modbus_conn = NULL; static char latest_data[256] = {0}; // Initialize NFC module static void init_nfc(void) { ST25DV_Init(); } // Update NFC tag with latest data static void update_nfc_tag(void) { ST25DV_WriteData(0, (uint8_t*)latest_data, strlen(latest_data)); } // ModbusTCP client handler static void modbus_handler(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { if (ev == MG_EV_CONNECT) { // Connection established, send Modbus request uint8_t request[] = { 0x00, 0x01, // Transaction ID 0x00, 0x00, // Protocol ID (0 for Modbus TCP) 0x00, 0x06, // Length 0x01, // Unit ID 0x03, // Function code (Read Holding Registers) 0x00, 0x00, // Starting address 0x00, 0x0A // Quantity of registers }; mg_send(c, request, sizeof(request)); } else if (ev == MG_EV_READ) { // Process Modbus response struct mg_iobuf *io = &c->recv; if (io->len >= 9) { // Minimum Modbus TCP response length uint8_t function_code = io->buf[7]; uint8_t byte_count = io->buf[8]; if (function_code == 0x03 && io->len >= 9 + byte_count) { // Extract values from Modbus response uint16_t value1 = (io->buf[9] << 8) | io->buf[10]; uint16_t value2 = (io->buf[11] << 8) | io->buf[12]; // Format data for NFC snprintf(latest_data, sizeof(latest_data), "PLC Data: Reg1=%u, Reg2=%u, Time=%lu", value1, value2, (unsigned long)mg_millis()); // Update NFC tag update_nfc_tag(); // Clean up response mg_iobuf_delete(io, io->len); } } } } // HTTP dashboard handler static void http_handler(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { if (ev == MG_EV_HTTP_MSG) { struct mg_http_message *hm = (struct mg_http_message *) ev_data; // Serve dashboard if (mg_http_match_uri(hm, "/")) { // HTML dashboard with latest data mg_http_reply(c, 200, "Content-Type: text/html\r\n", "<!DOCTYPE html>" "<html><head><title>PLC Data Monitor</title>" "<meta http-equiv='refresh' content='5'>" "<style>body{font-family:Arial;margin:20px;}</style>" "</head><body>" "<h1>Industrial Data Monitor</h1>" "<div>%s</div>" "<p>NFC Tag Updated: %lu ms ago</p>" "</body></html>", latest_data, mg_millis()); } else if (mg_http_match_uri(hm, "/api/data")) { // JSON API endpoint mg_http_reply(c, 200, "Content-Type: application/json\r\n", "{\"data\":\"%s\",\"timestamp\":%lu}", latest_data, (unsigned long)mg_millis()); } else { mg_http_reply(c, 404, "", "Not found"); } } } // Timer function to poll ModbusTCP periodically static void timer_fn(void *arg) { // Close previous connection if exists if (modbus_conn != NULL) { modbus_conn->is_closing = 1; modbus_conn = NULL; } // Create new Modbus connection modbus_conn = mg_connect(&mgr, MODBUS_SERVER, modbus_handler, NULL); // Schedule next poll mg_timer_add(&mgr, POLL_INTERVAL_MS, 0, timer_fn, NULL); } // Alternative: Get data from Golang server instead of directly from PLC static void influx_handler(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { if (ev == MG_EV_HTTP_MSG) { struct mg_http_message *hm = (struct mg_http_message *) ev_data; // Process JSON response from Golang server // This is a simplified parser - in production use a proper JSON parser mg_http_get_var(&hm->body, "value", latest_data, sizeof(latest_data)); // Update NFC tag with new data update_nfc_tag(); } } // Entry point int main(void) { // Initialize hardware SystemClock_Config(); HAL_Init(); // Initialize networking mg_mgr_init(&mgr); // Initialize NFC init_nfc(); // Start HTTP server for dashboard mg_http_listen(&mgr, "http://0.0.0.0:80", http_handler, NULL); // Set up periodic timer for Modbus polling mg_timer_add(&mgr, 100, 0, timer_fn, NULL); // Optional: HTTP client to get data from Golang server instead of direct Modbus // mg_http_connect(&mgr, INFLUX_SERVER, influx_handler, NULL); // Main event loop while (1) { mg_mgr_poll(&mgr, 50); // 50ms timeout HAL_Delay(10); // Give time for other system tasks } // Cleanup mg_mgr_free(&mgr); return 0; }Project Setup and Integration
1. Setting up Mongoose on STM32
// In your STM32CubeIDE project 1. Download Mongoose library from https://github.com/cesanta/mongoose 2. Add mongoose.c and mongoose.h to your project 3. Configure project with network support (ETH/LWIP) 4. Configure heap size (at least 32KB recommended for Mongoose)2. Connecting the NFC Module
The X-NUCLEO-NFC07A1 connects to Arduino-compatible headers on your NUCLEO board:
- Uses I2C for communication (default pins: PB8/PB9 for I2C1)
- Ensure ST25DV driver is properly initialized
3. Mongoose Dashboard Configuration
The built-in dashboard can be customized with:
- Real-time data visualization
- System status monitoring
- Manual NFC tag update controls
// Advanced dashboard with more features static const char *dashboard_html = "<!DOCTYPE html>" "<html><head>" "<title>Industrial IoT Dashboard</title>" "<meta name='viewport' content='width=device-width, initial-scale=1'>" "<script>" "function updateData() {" " fetch('/api/data').then(r=>r.json()).then(data=>{" " document.getElementById('plcData').innerText = data.data;" " document.getElementById('timestamp').innerText = new Date().toLocaleTimeString();" " });" " setTimeout(updateData, 5000);" "}" "document.addEventListener('DOMContentLoaded', updateData);" "</script>" "<style>body{font-family:Arial;margin:20px;} .card{border:1px solid #ddd;padding:15px;margin:10px 0;}</style>" "</head><body>" "<h1>Industrial Data Monitor</h1>" "<div class='card'>" "<h2>Current PLC Data</h2>" "<div id='plcData'>Loading...</div>" "<p>Last update: <span id='timestamp'>-</span></p>" "</div>" "<div class='card'>" "<h2>NFC Status</h2>" "<p>Tag data updated with latest values</p>" "<button onclick='fetch(\"/api/update-nfc\")'>Force NFC Update</button>" "</div>" "</body></html>";Data Flow Architecture
-
Option A: Direct PLC Access
- STM32 + Mongoose directly polls ModbusTCP server on PLC
- Advantages: Lower latency, simpler architecture
- Disadvantages: No historical data, higher load on PLC
-
Option B: Through Golang Server
- STM32 gets data from Golang HTTP/MQTT API
- Advantages: Access to historical data, filtered/processed data
- Disadvantages: Additional latency, dependency on Linux server
I recommend implementing both options with a configuration switch, so you can choose the best approach based on your specific requirements.
Performance Considerations
- Memory Usage: Mongoose requires about 30-40KB RAM for basic operation
- Network Traffic: ModbusTCP polling generates constant network traffic
- NFC Updates: Limit NFC tag updates to meaningful data changes to extend tag life
Would you like more details on any specific aspect of this implementation, such as customizing the dashboard, optimizing the NFC data format, or connecting with the Golang server?
- User
Compile all of my instructions from the past three chat requests (this window) into one combined request calling back all the elements I asked for into one request.
Assistant
Industrial Data Collection System Design Request
I need to build a data collection system for an industrial application with the following components and specifications:
Hardware Components:
- ControlLogix PLC running a ModbusTCP server
- PC running Debian Linux with InfluxDB Timeseries database
- NUCLEO-2H755ZI-Q microcontroller development board
- X-NUCLEO-NFC07A1 dynamic NFC/RFID expansion board
- NFC-enabled smartphone as the end-user interface
Software Architecture:
-
PLC Layer:
- ControlLogix PLC serving as the data source
- ModbusTCP server protocol for data access
-
Processing Layer:
- Debian Linux PC
- Golang as the development environment
- InfluxDB for time-series data storage
-
Edge Device Layer:
- NUCLEO-2H755ZI-Q with STM32H755ZI dual-core MCU
- Mongoose TCP library for network communications (selected for its robust support for ModbusTCP, MQTT, HTTP, and built-in dashboard functionality)
- X-NUCLEO-NFC07A1 for NFC/RFID communication
-
User Interface Layer:
- NFC-enabled smartphone to read the intelligent data
Data Flow Requirements:
- Industrial data originates at the PLC
- Data is collected and stored in the InfluxDB database on the Linux PC
- The STM32 microcontroller retrieves relevant data
- Data is transmitted to a smartphone via NFC
- System should support both direct PLC communication and database-sourced information
Please provide a comprehensive implementation plan addressing all hardware connections, software development, and integration points for this industrial IoT system.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.