WinCC Flexible OPC and SQL Integration with VB6/VB.NET

David Krause13 min read
HMI / SCADASiemensTechnical Reference
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

1. Overview: External Integration Paths from WinCC Flexible

Siemens WinCC Flexible (the predecessor generation of SIMATIC WinCC in the TIA Portal) exposes its runtime tag database through several well-documented mechanisms. Engineers writing supervisory clients in Microsoft Visual Basic 6.0 or .NET have four practical integration paths, each with different latency, firewall, and security characteristics:

  1. OPC DA / OPC XML DA — standard COM/DCOM-based tag access from any OPC client.
  2. SM@RT ACCESS — HTTP/SOAP service embedded in the WinCC Flexible Runtime that exposes tag read/write and screen change services.
  3. ODBC / SQL connectivity — direct access to the underlying WinCC Flexible archive database or to an external relational database for recipe and production logging.
  4. VBScript inside WinCC Flexible — using the inbuilt HMIRuntime scripting object so that VB logic executes on the HMI panel itself rather than from an external host.

The Siemens Application Examples for these integration paths are documented in the official knowledge base:

Important: WinCC Flexible 2008 SP5 is the final release line of the WinCC Flexible family. For new deployments Siemens recommends migrating to TIA Portal WinCC (Comfort/Advanced) where the equivalent functionality is delivered by the SIMATIC HMI OPC UA server and the Unified scripting interface. The interfaces below remain supported for legacy maintenance.

2. OPC Communication Architecture and DCOM Requirements

OPC (OLE for Process Control) Data Access 2.05a and 3.0 are the canonical tag-bus protocols used by WinCC Flexible. The HMI Runtime exposes itself as an OPC DA server under the ProgID OPC.SimaticHMI.HMIRuntime.1 and is registered when the WinCC Flexible Runtime is installed.

A typical VB6 or VB.NET client connects using the OPC DA Automation 2.0 wrapper (OPCDAAuto.dll) shipped with the OPC Core Components. The high-level object model is:

' VB6 / VBA-flavored OPC DA Automation
Dim server As OPCServer
Dim group As OPCGroup
Dim items As OPCItems

Set server = New OPCServer
server.Connect "OPC.SimaticHMI.HMIRRuntime.1", ""   ' remote or local node

Set group = server.OPCGroups.Add("MyGroup")
group.IsActive = True
group.IsSubscribed = True
group.UpdateRate = 250                          ' ms, minimum ~100

Set items = group.OPCItems
items.AddItem 1, "Tagname1"                     ' client handle, tag name
items.AddItem 2, "Tagname2"

Dim values() As Variant
Dim qualities() As Integer
Dim timeStamps() As Date
group.SyncRead OPCCache, 2, clientHandles, values, qualities, timeStamps

DCOM must be configured on both server and client Windows hosts. The minimum set:

  1. Enable DCOM in dcomcnfg on both sides.
  2. Add the user account running the WinCC Flexible Runtime to the Distributed COM Users group.
  3. Open TCP port 135 (RPC endpoint mapper) plus the dynamic RPC range (default 1024-5000) in Windows Firewall.
  4. Set the OPC Server's launch and access permissions to allow the remote user.
  5. If the WinCC Flexible Runtime and the VB client are on different subnets, configure WMI / OPC Enum or hard-code the server node in the client (avoiding the OPCEnum resolution step).
Latency budget: 250 ms UpdateRate + ~50 ms DCOM marshalling is typical for local LAN reads. Across WAN links, expect >1 s round-trip and intermittent OPC_E_NETWORK_ERROR events. For WAN scenarios, prefer OPC XML DA over HTTPS instead of OPC DA over DCOM.

3. SM@RT ACCESS: Native HTTP/SOAP Bridge

SM@RT ACCESS is the WinCC Flexible option that turns the runtime panel into an HTTP server, allowing remote clients to read tags, write tags, and trigger screen changes through SOAP/XML. It is licensed by part number 6AV6618-7AA01-0AA0 (WinCC Flexible SM@RT ACCESS option) and requires WinCC Flexible 2005 or later.

The runtime listens on a configurable TCP port (default 80, 443, or 8080 depending on HTTPS setting). Tag access uses the HMIRuntime tag namespace exposed over SOAP; the URL scheme is:

POST /WinCCFlexible/SmAccess HTTP/1.1
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://www.siemens.com/automation/HMI/SmAccess/GetTag"

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetTag xmlns="http://www.siemens.com/automation/HMI/SmAccess">
      <Name>RecipeNumber</Name>
    </GetTag>
  </soap:Body>
</soap:Envelope>

From .NET, the simplest implementation uses HttpWebRequest with a manually composed SOAP envelope, or an auto-generated WSDL proxy:

' VB.NET (Framework 4.x)
Dim url = "http://192.168.0.20/SmAccess"
Dim soap = $"<?xml version='1.0'?>" &
           $"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" &
           $"<soap:Body><GetTag xmlns='http://www.siemens.com/automation/HMI/SmAccess'>" &
           $"<Name>{tagName}</Name></GetTag></soap:Body></soap:Envelope>"

Dim req As HttpWebRequest = WebRequest.Create(url)
req.Method = "POST"
req.ContentType = "text/xml; charset=utf-8"
req.Headers.Add("SOAPAction", """http://www.siemens.com/automation/HMI/SmAccess/GetTag""")
req.Credentials = New NetworkCredential("smaccess", "secret")

Dim bytes = Encoding.UTF8.GetBytes(soap)
req.ContentLength = bytes.Length
Using rs = req.GetRequestStream()
    rs.Write(bytes, 0, bytes.Length)
End Using

Using resp = CType(req.GetResponse(), HttpWebResponse)
    Using sr = New StreamReader(resp.GetResponseStream())
        Dim xml As String = sr.ReadToEnd()
        ' Parse <GetTagResult> element
    End Using
End Using
SM@RT ACCESS authentication supports Basic Auth over HTTP and Digest Auth over HTTPS. The username/password are configured in the WinCC Flexible project under Runtime Settings > SM@RT ACCESS. Without HTTPS, credentials traverse the wire as Base64-cleartext — only use this on trusted networks.

4. ODBC / SQL Database Connectivity

WinCC Flexible supports two distinct ODBC models: archive ODBC for reading the internal runtime logging database (value/quality/timestamp triplets), and script-side ODBC for connecting to an external relational database (e.g. SQL Server, Oracle, MySQL) from within a VBScript.

Use case Mechanism Direction Typical driver
Recipe upload/download External SQL via VBScript / ODBC Both SQL Server Native Client, MySQL ODBC 8.0 ANSI
Production logging External SQL via VBScript / ODBC Write SQL Server, Oracle ODBC
Alarm archive read-back WinCC Flexible archive ODBC Read Internal *.ldb ODBC DSN
Process value history WinCC Flexible archive ODBC Read Internal *.ldb ODBC DSN

The archive ODBC DSN is created automatically when you enable the "Database" option in the WinCC Flexible project. Point an external VB client at that DSN to query historic values with standard SQL.

For script-side ODBC against an external SQL Server, register the SQL Server Native Client ODBC driver on the HMI panel (Windows CE only supports a subset — verify the panel OS first). Then from a WinCC Flexible VBScript use CreateObject("ADODB.Connection"):

' VBScript inside WinCC Flexible (Runtime)
Dim conn, rs
Set conn = CreateObject("ADODB.Connection")
conn.ConnectionString = _
  "Provider=MSDASQL;DRIVER={SQL Server Native Client 11.0};" & _
  "SERVER=SQLSRV;DATABASE=Production;UID=hmi;PWD=secret;"
conn.Open

Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT RecipeData FROM Recipes WHERE RecipeID=" & _
         CInt(HMIRuntime.Tags("RecipeID").Read), conn

If Not rs.EOF Then
    HMIRuntime.Tags("RecipeName").Write rs.Fields("RecipeData").Value
End If
rs.Close
conn.Close

For panels running Windows CE 6.0 or Embedded Compact 7, the supported ODBC drivers are limited to SQL Server Native Client 10.0 and the embedded Compact ODBC manager. On Windows 7/10 HMI PCs (WinCC Flexible RT 2008 SP5), the full x64 driver stack is available.

5. VBScript Inside WinCC Flexible: The HMIRuntime Object

WinCC Flexible provides an in-script object hierarchy rooted at HMIRuntime that is fully equivalent to OPC tag operations, eliminating the need for an external VB host in many cases. The hierarchy is:

Object Purpose Common methods / properties
HMIRuntime Root scripting context Tags, Screens, Alarms, Events, RaiseEvents
HMIRuntime.Tags Tag collection Item(name), Read, Write, WriteIndirect
HMIRuntime.Screens Screen control Item(index), Activate
HMIRuntime.Alarms Alarm buffer Read, Acknowledge
HMIRuntime.SmartTags Tag alias layer Used in TIA Portal (not WinCC Flexible)

Tag writes can be synchronous or asynchronous. For high-frequency writes (e.g. closed-loop setpoints) prefer WriteIndirect to coalesce to the configured tag update rate.

' Triggered by a 'Value change' event on tag "StartButton"
If HMIRuntime.Tags("StartButton").Read = 1 Then
    HMIRuntime.Tags("MotorRun").Write 1
    HMIRuntime.Tags("CycleCounter").Read + 1
    HMIRuntime.Tags("CycleCounter").Write (HMIRuntime.Tags("CycleCounter").Read + 1)
End If
VBScript inside WinCC Flexible is interpreted (not compiled) and runs in a single STA thread. Long blocking operations (network calls, ODBC round-trips) freeze the HMI screen update loop. Anything over ~100 ms should be offloaded to a background COM object or moved to a VB.NET host with proper async/await.

6. VB6 / VB.NET External Host: Tag Mapping Table

Below is the canonical mapping between a WinCC Flexible tag (named inside the project) and its representation on the wire for each transport. Names are case-sensitive on OPC XML DA and SM@RT ACCESS; case-insensitive on OPC DA.

WinCC Flexible tag (PLC:DB100.DBX0.0 INT) OPC DA item path SM@RT ACCESS SOAP VBScript HMIRuntime
RecipeNumber RecipeNumber <Name>RecipeNumber</Name> HMIRuntime.Tags("RecipeNumber")
MotorRun (BOOL) MotorRun Same as above Same as above
Setpoint (REAL) Setpoint Same as above Same as above
CycleTime (DINT) CycleTime Same as above Same as above
ConnectionState (system) @System.ConnectionState n/a (system tag) HMIRuntime.Tags("@System.ConnectionState")

The same tag name resolves through every transport; the engineer selects the transport based on latency, firewall, and authentication requirements.

7. Step-by-Step: Reading a Recipe From SQL Server Into WinCC Flexible

Prerequisites:

  • WinCC Flexible 2008 SP5 project with at least one screen and one tag named RecipeNumber.
  • SQL Server 2008 R2 or later with a database Production containing table Recipes(RecipeID INT, RecipeName NVARCHAR(64), RecipeData NVARCHAR(MAX)).
  • SQL login hmi with db_datareader rights on Production.
  • SQL Server Native Client 11.0 (or 10.0 for Windows CE panels) installed and configured as ODBC DSN ProdSQL.

Procedure:

  1. In the WinCC Flexible project, open the screen that should display the recipe. Add a numeric I/O field bound to RecipeNumber and a text field bound to RecipeName.
  2. Open Schedules → Tasks → Add New Task. Create a task "ReadRecipe" triggered by the event Value change on tag RecipeNumber.
  3. Attach the following VBScript to that task:
    Sub ReadRecipe_Trigger(ByVal Item)
        On Error Resume Next
        Dim conn, rs, id, name
        Set conn = CreateObject("ADODB.Connection")
        conn.ConnectionString = "DSN=ProdSQL;UID=hmi;PWD=secret;"
        conn.Open
        If Err.Number <> 0 Then
            HMIRuntime.Trace "DB connect failed: " & Err.Description & vbCrLf
            Exit Sub
        End If
        id = CInt(HMIRuntime.Tags("RecipeNumber").Read)
        Set rs = CreateObject("ADODB.Recordset")
        rs.Open "SELECT RecipeName FROM Recipes WHERE RecipeID=" & id, conn
        If Not rs.EOF Then
            name = CStr(rs.Fields("RecipeName").Value)
            HMIRuntime.Tags("RecipeName").Write name
            HMIRuntime.Trace "Recipe " & id & " loaded: " & name & vbCrLf
        Else
            HMIRuntime.Trace "Recipe " & id & " not found" & vbCrLf
        End If
        rs.Close
        conn.Close
    End Sub
  4. Open Runtime Settings → Device Settings and enable Database connection; point the ODBC source to ProdSQL.
  5. Compile and download the project to the HMI panel (or start Runtime locally for development).
  6. Change the value of RecipeNumber to 1, then 2, then 999 (non-existent). Verify that RecipeName updates correctly for 1 and 2 and that the trace logs "not found" for 999.

Verification checklist:

  • SQL Server Profiler shows an Audit Login + SELECT statement each time RecipeNumber changes.
  • The HMI screen redraws <500 ms after the trigger event.
  • Trace log (under Runtime → Trace) shows the expected diagnostic messages.

8. TwinCAT ADS .NET: A Cross-Vendor VB.NET Pattern

When the HMI/SCADA layer is Beckhoff TwinCAT instead of Siemens, the equivalent .NET integration path is the TwinCAT ADS router. Although the source question concerns WinCC Flexible, the VB.NET ADO pattern is widely reused across vendors, and Beckhoff's published quick-start provides a reference implementation:

The procedure documented there is:

  1. Add a reference to Beckhoff.ADS.dll (or the legacy TcAdsDll.dll COM wrapper) in the VB.NET project.
  2. Construct an AdsClient and connect to the ADS router on the target system. The default router port is 801 on the local machine and 10000+ on remote machines.
  3. For variable access by name, enable symbol loading (AdsSymbolLoader) or query the handle via AdsClient.CreateVariableHandle("MAIN.nCounter").
  4. Read or write through that handle:
' VB.NET with Beckhoff.ADS.dll
Imports TwinCAT.Ads

Dim client As New TcAdsClient()
client.Connect(801)                                 ' AMS NetId resolved automatically

Dim handle As Integer = client.CreateVariableHandle("MAIN.nCounter")

Dim value As Integer
value = client.ReadAny(handle, GetType(Integer))

value += 1
client.WriteAny(handle, value)

client.DeleteVariableHandle(handle)
client.Disconnect()

The pattern translates directly: a SCADA tag named on the Beckhoff side becomes the symbol string passed to CreateVariableHandle, exactly as a WinCC Flexible tag becomes the OPC item path. From the VB.NET host's perspective, the integration mechanism is largely the same regardless of controller family.

9. Specifications and Configuration Limits

Parameter WinCC Flexible 2008 SP5 WinCC Flexible RT on Win32 WinCC Flexible RT on Win CE
Max external tags (SM@RT ACCESS) 1 024 per project 1 024 512
OPC DA server Optional add-on (article 18797552) Yes, ProgID OPC.SimaticHMI.HMIRuntime.1 Yes (panel-specific ProgID)
OPC XML DA Yes (port 8081 default) Yes Limited
SM@RT ACCESS license (article number) 6AV6618-7AA01-0AA0 n/a n/a
SM@RT ACCESS clients (concurrent) Up to 32 Up to 32 Up to 16
VBScript max execution time 10 s (configurable) 10 s 5 s
ODBC drivers supported Full Windows driver stack Full Windows driver stack SQL Server Native Client 10.0 only
VBScript object model HMIRuntime (5 collections) HMIRuntime HMIRuntime

10. Troubleshooting Matrix

Symptom Likely root cause Diagnostic Resolution
OPC client returns OPC_E_NETWORK_ERROR DCOM ports blocked netstat -an | findstr 135 on both hosts Open TCP 135 + RPC range in Windows Firewall
OPC server not visible in browse OPCEnum service stopped Services console, OPCEnum status Start service, set startup to Automatic
SM@RT ACCESS returns HTTP 401 Credentials wrong or HTTPS mismatch Fiddler capture of negotiation Re-enter user/password, check HTTPS setting
ODBC connection fails on panel Native Client driver missing (Windows CE) ODBC Data Source Administrator on panel Install SQL Server Native Client 10.0 cab
VBScript "Object required" on HMIRuntime.Tags Tag name typo or panel compile error Check Tag list under Project → Tags Recompile and redownload project
VBScript execution blocks HMI Synchronous long ODBC call Runtime trace duration log Move DB I/O to a separate scheduled task or VB host
TwinCAT ADS.NET exception "Port not found" ADS router not running TwinCAT system tray icon Start TwinCAT in Run mode
TwinCAT ADS.NET exception "Symbol not found" Symbol loader cache empty Reload symbols Use AdsSymbolLoader or pass tcAdsSymbolServer options

11. Verification and Acceptance Tests

After commissioning any of the integration paths above, run the following acceptance sequence:

  1. Tag ping: Read @System.ConnectionState from the external client and verify it equals 1 (connected).
  2. Round-trip write/read: Write a unique test pattern (e.g. timestamp seconds) to a known tag from the external client; read back the value from inside the WinCC Flexible VBScript and confirm equality.
  3. Disconnect simulation: Stop the WinCC Flexible Runtime; confirm the external client receives OPC_E_NETWORK_ERROR or HTTP 503 within 5 s (timing parameter: DCOM ping = 5 000 ms).
  4. Database failure simulation: Take the SQL Server offline; verify the VBScript trace emits the expected error code and that the HMI screen remains responsive (i.e. the DB I/O is bounded).
  5. Security review: For SM@RT ACCESS, verify HTTPS is enforced and the credentials use a non-default username; for OPC, verify that only the hmi service account has Launch and Access permissions.
When deploying WinCC Flexible 2008 SP5 on Windows 10, verify DCOM settings survive Windows updates — Microsoft occasionally resets anonymous connection restrictions. After major upgrades (e.g. 1909 → 2004), re-run the acceptance sequence above.

What ProgID does the WinCC Flexible OPC DA server use?

The OPC DA server ProgID installed by WinCC Flexible is OPC.SimaticHMI.HMIRuntime.1. It is registered when the Runtime component is installed and appears in any OPC DA browser such as MatrikonOPC Explorer.

Can VBScript inside WinCC Flexible connect to a remote SQL Server?

Yes, on Windows 7/10 HMI Runtime PCs with the SQL Server Native Client (10.0 for Windows CE panels, 11.0 or later for full Windows). Use CreateObject("ADODB.Connection") and a DSN-based or driver-based connection string. Connection times over 100 ms should be moved off the main UI thread.

How do I authenticate SM@RT ACCESS requests?

SM@RT ACCESS supports HTTP Basic Authentication and HTTP Digest Authentication. The username and password are configured in the WinCC Flexible project under Runtime Settings → SM@RT ACCESS. Always use HTTPS in production to prevent credential exposure.

What is the difference between OPC DA and OPC XML DA for WinCC Flexible?

OPC DA uses Microsoft COM/DCOM, has the lowest latency, and is constrained to the local Windows network. OPC XML DA uses HTTP/SOAP over a configurable TCP port, traverses firewalls and NAT, and is the correct choice for WAN or DMZ scenarios at the cost of higher latency.

Is the Beckhoff TwinCAT ADS .NET API similar to the WinCC Flexible OPC DA API?

Conceptually yes — both expose process tags by name from a server to a client process running in the same LAN. The ADS router listens on TCP port 801 (local) and 10000+ (remote), and the .NET TcAdsClient class reads/writes variables by name via CreateVariableHandle("MAIN.nCounter"). Cross-vendor SCADA clients commonly reuse the same VB.NET pattern.

Back to blog