├── .dockerignore
├── .gitignore
├── Dockerfile
├── LICENSE
├── Mqtt.Publisher.Config.xml
├── MqttPublisher.csproj
├── MqttPublisher.sln
├── Program.cs
├── Properties
└── launchSettings.json
└── README.md
/.dockerignore:
--------------------------------------------------------------------------------
1 | **/.classpath
2 | **/.dockerignore
3 | **/.env
4 | **/.git
5 | **/.gitignore
6 | **/.project
7 | **/.settings
8 | **/.toolstarget
9 | **/.vs
10 | **/.vscode
11 | **/*.*proj.user
12 | **/*.dbmdl
13 | **/*.jfm
14 | **/azds.yaml
15 | **/bin
16 | **/charts
17 | **/docker-compose*
18 | **/Dockerfile*
19 | **/node_modules
20 | **/npm-debug.log
21 | **/obj
22 | **/secrets.dev.yaml
23 | **/values.dev.yaml
24 | LICENSE
25 | README.md
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
2 |
3 | FROM mcr.microsoft.com/dotnet/runtime:3.1 AS base
4 | WORKDIR /app
5 |
6 | FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
7 | WORKDIR /src
8 | COPY ["MqttPublisher.csproj", "."]
9 | RUN dotnet restore "./MqttPublisher.csproj"
10 | COPY . .
11 | WORKDIR "/src/."
12 | RUN dotnet build "MqttPublisher.csproj" -c Release -o /app/build
13 |
14 | FROM build AS publish
15 | RUN dotnet publish "MqttPublisher.csproj" -c Release -o /app/publish
16 |
17 | FROM base AS final
18 | WORKDIR /app
19 | COPY --from=publish /app/publish .
20 | ENTRYPOINT ["dotnet", "MqttPublisher.dll"]
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Erich Barnstedt
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Mqtt.Publisher.Config.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 | MQTTPublisher
8 | urn:localhost:MQTTPublisher:microsoft
9 | https://github.com/azure/iot-edge-opc-publisher
10 | Client_1
11 |
12 |
13 | Directory
14 | %LocalApplicationData%/MQTTPublisher/pki/own
15 | CN=OPC Publisher, C=US, S=Washington, O=Microsoft, DC=localhost
16 |
17 |
18 | Directory
19 | %LocalApplicationData%/MQTTPublisher/pki/issuer
20 |
21 |
22 | Directory
23 | %LocalApplicationData%/MQTTPublisher/pki/trusted
24 |
25 | 32
26 |
27 | Directory
28 | %LocalApplicationData%/MQTTPublisher/pki/rejected
29 |
30 | false
31 | 1024
32 | false
33 |
34 | Directory
35 | %LocalApplicationData%/MQTTPublisher/pki/issuerUser
36 |
37 |
38 | Directory
39 | %LocalApplicationData%/MQTTPublisher/pki/trustedUser
40 |
41 |
42 |
43 |
44 | 120000
45 | 1048576
46 | 4194304
47 | 65535
48 | 4194304
49 | 65535
50 | 300000
51 | 3600000
52 |
53 |
54 | 600000
55 |
56 | opc.tcp://{0}:4840/UADiscovery
57 | http://{0}:52601/UADiscovery
58 | http://{0}/UADiscovery/Default.svc
59 |
60 |
61 | Opc.Publisher.Endpoints.xml
62 | 10000
63 |
64 |
65 |
66 |
67 | %CommonApplicationData%\OPC Foundation\Logs\Opc.Publisher.log.txt
68 | true
69 |
70 | 645
71 |
72 | true
73 |
74 |
--------------------------------------------------------------------------------
/MqttPublisher.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net6.0
6 | MqttPublisher
7 | OpcUaPubSub
8 | OpcUaPubSub.Program
9 | MqttPublisher
10 | Linux
11 | .
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | PreserveNewest
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 | $(SolutionDir)\build\bin\NetCore\$(Configuration)\
33 |
34 |
35 |
36 | $(SolutionDir)\build\bin\NetCore\$(Configuration)\
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/MqttPublisher.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.31313.79
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MqttPublisher", "MqttPublisher.csproj", "{7CAE3BD8-3F31-46C9-BD1E-24BB8D6A31D1}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {7CAE3BD8-3F31-46C9-BD1E-24BB8D6A31D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {7CAE3BD8-3F31-46C9-BD1E-24BB8D6A31D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {7CAE3BD8-3F31-46C9-BD1E-24BB8D6A31D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {7CAE3BD8-3F31-46C9-BD1E-24BB8D6A31D1}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {7539EBCD-8666-4BCD-98CA-3E513EDB71A8}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/Program.cs:
--------------------------------------------------------------------------------
1 | using MQTTnet;
2 | using MQTTnet.Adapter;
3 | using MQTTnet.Client;
4 | using MQTTnet.Packets;
5 | using MQTTnet.Protocol;
6 | using Opc.Ua;
7 | using Opc.Ua.Client;
8 | using Opc.Ua.Client.ComplexTypes;
9 | using Opc.Ua.Configuration;
10 | using System;
11 | using System.Collections.Generic;
12 | using System.Globalization;
13 | using System.Linq;
14 | using System.Security.Cryptography;
15 | using System.Text;
16 | using System.Threading;
17 | using System.Threading.Tasks;
18 |
19 | namespace OpcUaPubSub
20 | {
21 | public class Program
22 | {
23 | private static IMqttClient _client = null;
24 |
25 | public static void Main()
26 | {
27 | // create OPC UA client app
28 | ApplicationInstance app = new ApplicationInstance
29 | {
30 | ApplicationName = "MQTTPublisher",
31 | ApplicationType = ApplicationType.Client,
32 | ConfigSectionName = "Mqtt.Publisher"
33 | };
34 |
35 | app.LoadApplicationConfiguration(false).GetAwaiter().GetResult();
36 | app.CheckApplicationInstanceCertificate(false, 0).GetAwaiter().GetResult();
37 |
38 | // create OPC UA cert validator
39 | app.ApplicationConfiguration.CertificateValidator = new CertificateValidator();
40 | app.ApplicationConfiguration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(OPCUAServerCertificateValidationCallback);
41 | app.ApplicationConfiguration.CertificateValidator.Update(app.ApplicationConfiguration.SecurityConfiguration).GetAwaiter().GetResult();
42 |
43 | string brokerName = " HandleMessageAsync(msg);
59 |
60 | var clientOptions = new MqttClientOptionsBuilder()
61 | .WithTcpServer(opt => opt.NoDelay = true)
62 | .WithClientId(clientName)
63 | .WithTcpServer(brokerName, 8883)
64 | .WithTls(new MqttClientOptionsBuilderTlsParameters { UseTls = true })
65 | .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V500)
66 | .WithUserProperty("host", brokerName) // normally it is not needed as SNI is added by most TLS implementations.
67 | .WithUserProperty("api-version", "2020-10-01-preview")
68 | .WithTimeout(TimeSpan.FromSeconds(30))
69 | .WithKeepAlivePeriod(TimeSpan.FromSeconds(300))
70 | .WithCleanSession(false) // keep existing subscriptions
71 | .WithAuthentication("SAS", sas)
72 | .WithUserProperty("sas-at", atString)
73 | .WithUserProperty("sas-expiry", expiryString);
74 |
75 | // setup disconnection handling: print out details and allow process to close
76 | bool disconnected = false;
77 | _client.DisconnectedAsync += disconnectArgs =>
78 | {
79 | Console.WriteLine($"Disconnected: {disconnectArgs.Reason}");
80 | disconnected = true;
81 |
82 | return Task.CompletedTask;
83 | };
84 |
85 | try
86 | {
87 | var connectResult = _client.ConnectAsync(clientOptions.Build(), CancellationToken.None).GetAwaiter().GetResult();
88 | if (connectResult.ResultCode != MqttClientConnectResultCode.Success)
89 | {
90 | var status = GetStatus(connectResult.UserProperties)?.ToString("x4");
91 | throw new Exception($"Connect failed. Status: {connectResult.ResultCode}; status: {status}");
92 | }
93 |
94 | var subscribeResult = _client.SubscribeAsync(
95 | new MqttTopicFilter
96 | {
97 | Topic = "$iothub/methods/+",
98 | QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
99 | }).GetAwaiter().GetResult();
100 |
101 | // make sure subscriptions were successful
102 | if (subscribeResult.Items.Count != 1 || subscribeResult.Items.ElementAt(0).ResultCode != MqttClientSubscribeResultCode.GrantedQoS0)
103 | {
104 | throw new ApplicationException("Failed to subscribe");
105 | }
106 | }
107 | catch (MqttConnectingFailedException ex)
108 | {
109 | Console.WriteLine($"Failed to connect, reason code: {ex.ResultCode}");
110 | if (ex.Result?.UserProperties != null)
111 | {
112 | foreach (var prop in ex.Result.UserProperties)
113 | {
114 | Console.WriteLine($"{prop.Name}: {prop.Value}");
115 | }
116 | }
117 | }
118 |
119 | // find endpoint on a local OPC UA server
120 | string serverEndpoint = "opc.tcp://localhost:50000"; // run this sample OPC UA server locally via: docker run -p 50000:50000 mcr.microsoft.com/iotedge/opc-plc --aa --ctb
121 | EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(serverEndpoint, false);
122 | EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(app.ApplicationConfiguration);
123 | ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
124 |
125 | // Create OPC UA session
126 | Session session = Session.Create(app.ApplicationConfiguration, endpoint, false, false, app.ApplicationConfiguration.ApplicationName, 30 * 60 * 1000, new UserIdentity(), null).GetAwaiter().GetResult();
127 | if (!session.Connected)
128 | {
129 | Console.WriteLine("Connection to OPC UA server failed!");
130 | return;
131 | }
132 |
133 | // load complex type system
134 | ComplexTypeSystem complexTypeSystem = new ComplexTypeSystem(session);
135 |
136 | // send data for a minute, every second
137 | try
138 | {
139 | int i = 0;
140 | while (!disconnected)
141 | {
142 | int publishingInterval = 1000;
143 |
144 | // read a variable node from the OPC UA server (for example a variable node based on a complex type, contained in the sample OPC PLC provided by Microsoft)
145 | ExpandedNodeId nodeID = ExpandedNodeId.Parse("nsu=http://microsoft.com/Opc/OpcPlc/Boiler;i=15013");
146 | VariableNode node = (VariableNode)session.ReadNode(ExpandedNodeId.ToNodeId(nodeID, session.NamespaceUris));
147 |
148 | ExpandedNodeId nodeTypeId = node.DataType;
149 | complexTypeSystem.LoadType(nodeTypeId).GetAwaiter().GetResult();
150 |
151 | // now that we have loaded the complex type, we can read the value
152 | DataValue value = session.ReadValue(ExpandedNodeId.ToNodeId(nodeID, session.NamespaceUris));
153 |
154 | // OPC UA PubSub JSON-encode data read
155 | JsonEncoder encoder = new JsonEncoder(session.MessageContext, true);
156 | encoder.WriteString("MessageId", i++.ToString());
157 | encoder.WriteString("MessageType", "ua-data");
158 | encoder.WriteString("PublisherId", app.ApplicationName);
159 | encoder.PushArray("Messages");
160 | encoder.PushStructure("");
161 | encoder.WriteString("DataSetWriterId", endpointDescription.Server.ApplicationUri + ":" + publishingInterval.ToString());
162 | encoder.PushStructure("Payload");
163 | encoder.WriteDataValue(node.DisplayName.ToString(), value);
164 | encoder.PopStructure();
165 | encoder.PopStructure();
166 | encoder.PopArray();
167 | string payload = encoder.CloseAndReturnText();
168 |
169 | // send to MQTTv5 broker
170 | var message = new MqttApplicationMessageBuilder()
171 | .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
172 | .WithTopic("$iothub/telemetry")
173 | .WithContentType("application/json") // optional: sets `content-type` system property on message
174 | .WithUserProperty("@myProperty", "my value") // optional: adds custom property `myProperty`
175 | .WithUserProperty("creation-time", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString()) // optional: sets `creation-time` system property on message
176 | .WithPayload(Encoding.UTF8.GetBytes(payload))
177 | .Build();
178 |
179 | var response = _client.PublishAsync(message).GetAwaiter().GetResult();
180 |
181 | Task.Delay(publishingInterval).GetAwaiter().GetResult();
182 | }
183 |
184 | Console.WriteLine("Exciting!");
185 |
186 | session.Close();
187 | session.Dispose();
188 |
189 | _client.DisconnectAsync().GetAwaiter().GetResult();
190 | _client.Dispose();
191 | }
192 | catch (Exception ex)
193 | {
194 | Console.WriteLine("Exception: " + ex.Message);
195 |
196 | session.Close();
197 | session.Dispose();
198 |
199 | _client.DisconnectAsync().GetAwaiter().GetResult();
200 | _client.Dispose();
201 | }
202 | }
203 |
204 | // parses status from packet properties
205 | private static int? GetStatus(List properties)
206 | {
207 | var status = properties.FirstOrDefault(up => up.Name == "status");
208 | if (status == null)
209 | {
210 | return null;
211 | }
212 |
213 | return int.Parse(status.Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
214 | }
215 |
216 | // handles all incoming messages
217 | private static Task HandleMessageAsync(MqttApplicationMessageReceivedEventArgs args)
218 | {
219 | var msg = args.ApplicationMessage;
220 | if (msg.Topic.StartsWith("$iothub/methods/"))
221 | {
222 | var fork = Task.Run(async () =>
223 | {
224 | var response = HandleMethod(msg);
225 | await _client.PublishAsync(response).ConfigureAwait(false);
226 | });
227 | }
228 | else
229 | {
230 | Console.WriteLine("Unknown topic received: " + msg.Topic);
231 | }
232 |
233 | return Task.CompletedTask;
234 | }
235 |
236 | // handles direct method calls
237 | private static MqttApplicationMessage HandleMethod(MqttApplicationMessage message)
238 | {
239 | Console.WriteLine($"Received method call:\ntopic:{message.Topic}\npayload as a string: {Encoding.UTF8.GetString(message.PayloadSegment)}");
240 | return new MqttApplicationMessageBuilder()
241 | .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
242 | .WithTopic("$iothub/responses")
243 | .WithCorrelationData(message.CorrelationData)
244 | .WithUserProperty("response-code", "200")
245 | .WithPayload("{\"test\":123}")
246 | .Build();
247 | }
248 |
249 | private static void OPCUAServerCertificateValidationCallback(CertificateValidator validator, CertificateValidationEventArgs e)
250 | {
251 | // always trust the OPC UA server certificate
252 | if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted)
253 | {
254 | e.Accept = true;
255 | }
256 | }
257 | }
258 | }
259 |
--------------------------------------------------------------------------------
/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "MqttPublisher": {
4 | "commandName": "Project"
5 | },
6 | "Docker": {
7 | "commandName": "Docker"
8 | }
9 | }
10 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MQTTPublisherMVP
2 | Minimum Viable Product for an MQTTv5-based OPC UA PubSub Publisher for industrial cloud telemetry.
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------