1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
| using Dapper; using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Configuration; using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Serilog; using System.Collections.Concurrent;
IConfiguration configuration = null;
configuration = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build();
Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .Enrich.FromLogContext() .CreateLogger();
var application = new ApplicationInstance { ApplicationName = "OPC UA Client Demo", ApplicationType = ApplicationType.Client };
await application.LoadApplicationConfiguration("Test.Config.xml", false);
application.ApplicationConfiguration.SecurityConfiguration.AutoAcceptUntrustedCertificates = false;
bool haveCert = await application.CheckApplicationInstanceCertificate(false, 0); if (!haveCert) { Console.WriteLine("無法建立憑證,請檢查寫入權限或路徑設定。"); return; } Console.WriteLine("憑證已確認或自動生成。");
var opcServerUrl = configuration["OPCServerUrl"]; var endpointURL = opcServerUrl;
var endpoint = CoreClientUtils.SelectEndpoint(endpointURL, false); var config = EndpointConfiguration.Create(application.ApplicationConfiguration); var endpointConfig = new ConfiguredEndpoint(null, endpoint, config);
using var session = await Session.Create( application.ApplicationConfiguration, endpointConfig, false, "MySession", 60000, null, null );
Console.WriteLine("已連線到 OPC UA Server");
NodeId simulationFolderId = null; ReferenceDescriptionCollection references; byte[] continuationPoint;
session.Browse( null, null, ObjectIds.ObjectsFolder, 0u, BrowseDirection.Forward, ReferenceTypeIds.Organizes, true, (uint)NodeClass.Object, out continuationPoint, out references );
foreach (var rd in references) { if (rd.DisplayName.Text == "Simulation") { simulationFolderId = (NodeId)rd.NodeId; Console.WriteLine("找到 Simulation Folder: " + simulationFolderId); break; } }
if (simulationFolderId == null) { Console.WriteLine("找不到 Simulation Folder"); return; }
var latestValues = new ConcurrentDictionary<string, object>();
var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 1000, PublishingEnabled = true };
var variableNodes = new List<NodeId>(); FindVariables(session, simulationFolderId, variableNodes);
foreach (var nodeId in variableNodes) { var node = session.ReadNode(nodeId); string displayName = node.DisplayName.Text;
var item = new MonitoredItem(subscription.DefaultItem) { StartNodeId = nodeId, AttributeId = Attributes.Value, DisplayName = nodeId.Identifier.ToString(), SamplingInterval = 500 };
item.Notification += (monItem, args) => { foreach (var value in monItem.DequeueValues()) latestValues[displayName] = value.Value; };
subscription.AddItem(item); }
session.AddSubscription(subscription); subscription.Create();
Console.WriteLine("開始監控 Simulation Folder 下所有數值...");
_ = Task.Run(async () => { while (true) { await Task.Delay(1000);
if (latestValues.IsEmpty) continue;
var sim = new Simulation { Timestamp = DateTime.Now, Counter = latestValues.ContainsKey("Counter") ? Convert.ToInt32(latestValues["Counter"]) : 0, Random = latestValues.ContainsKey("Random") ? Convert.ToDouble(latestValues["Random"]) : (double?)null, Sawtooth = latestValues.ContainsKey("Sawtooth") ? Convert.ToDouble(latestValues["Sawtooth"]) : (double?)null, Sinusoid = latestValues.ContainsKey("Sinusoid") ? Convert.ToDouble(latestValues["Sinusoid"]) : (double?)null, Square = latestValues.ContainsKey("Square") ? Convert.ToDouble(latestValues["Square"]) : (double?)null, Triangle = latestValues.ContainsKey("Triangle") ? Convert.ToDouble(latestValues["Triangle"]) : (double?)null };
using var connection = new SqlConnection(configuration.GetConnectionString("SimulationDatabase")); string sql = @" INSERT INTO Simulation (Timestamp, Counter, Random, Sawtooth, Sinusoid, Square, Triangle) VALUES (@Timestamp, @Counter, @Random, @Sawtooth, @Sinusoid, @Square, @Triangle)"; connection.Execute(sql, sim);
Log.Information("寫入資料 {@Simulation}", sim); } });
var cts = new CancellationTokenSource(); Console.CancelKeyPress += (s, e) => { e.Cancel = true; cts.Cancel(); };
try { await Task.Delay(-1, cts.Token); } catch (TaskCanceledException) { }
Console.WriteLine("程式已結束。");
void FindVariables(Session session, NodeId nodeId, List<NodeId> variableNodes) { session.Browse( null, null, nodeId, 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Object | (uint)NodeClass.Variable, out byte[] cp, out ReferenceDescriptionCollection refs );
foreach (var rd in refs) { var childId = (NodeId)rd.NodeId; if (rd.NodeClass == NodeClass.Variable) { variableNodes.Add(childId); } else if (rd.NodeClass == NodeClass.Object) { FindVariables(session, childId, variableNodes); } } }
|