public void EncodeDecodeNetworkMessage() { var payload = new Dictionary <string, DataValue> { { "1", new DataValue(new Variant(5), StatusCodes.Good, DateTime.Now) }, { "2", new DataValue(new Variant(0.5), StatusCodes.Good, DateTime.Now) }, { "3", new DataValue("abcd") } }; var message = new DataSetMessage { DataSetWriterId = "WriterId", MetaDataVersion = new ConfigurationVersionDataType { MajorVersion = 1, MinorVersion = 1 }, SequenceNumber = ++_currentSequenceNumber, Status = StatusCodes.Good, Timestamp = DateTime.UtcNow, MessageContentMask = (uint)( JsonDataSetMessageContentMask.DataSetWriterId | JsonDataSetMessageContentMask.SequenceNumber | JsonDataSetMessageContentMask.MetaDataVersion | JsonDataSetMessageContentMask.Timestamp | JsonDataSetMessageContentMask.Status), Payload = new DataSet(payload) { FieldContentMask = (uint)(DataSetFieldContentMask.StatusCode | DataSetFieldContentMask.SourceTimestamp) } }; var networkMessage = new NetworkMessage { MessageId = Guid.NewGuid().ToString(), // TODO MessageType = "ua-data", Messages = new List <DataSetMessage>(), PublisherId = "PublisherId" }; networkMessage.Messages.Add(message); networkMessage.MessageContentMask = (uint)( JsonNetworkMessageContentMask.PublisherId | JsonNetworkMessageContentMask.NetworkMessageHeader | JsonNetworkMessageContentMask.SingleDataSetMessage); byte[] buffer; string json; var context = new ServiceMessageContext(); using (var stream = new MemoryStream()) { using (var encoder = new JsonEncoderEx(stream, context)) { networkMessage.Encode(encoder); } buffer = stream.ToArray(); json = buffer.ToBase16String(); } using (var stream = new MemoryStream(buffer)) { using (var decoder = new JsonDecoderEx(stream, context)) { var result = decoder.ReadEncodeable(null, typeof(NetworkMessage)) as NetworkMessage; Assert.Equal(networkMessage, result); } } }
/// <inheritdoc/> public async Task HandleAsync(string deviceId, string moduleId, byte[] payload, IDictionary <string, string> properties, Func <Task> checkpoint) { var json = Encoding.UTF8.GetString(payload); MonitoredItemMessage message; try { var context = new ServiceMessageContext(); using (var stream = new MemoryStream(payload)) { using (var decoder = new JsonDecoderEx(stream, context)) { message = decoder.ReadEncodeable(null, typeof(MonitoredItemMessage)) as MonitoredItemMessage; } } } catch (Exception ex) { _logger.Error(ex, "Failed to decode message"); return; } try { var dataset = new DataSetMessageModel { PublisherId = (message.ExtensionFields != null && message.ExtensionFields.TryGetValue("PublisherId", out var publisherId)) ? publisherId : message.ApplicationUri ?? message.EndpointUrl, MessageId = null, DataSetClassId = message.NodeId.AsString(null), DataSetWriterId = (message.ExtensionFields != null && message.ExtensionFields.TryGetValue("DataSetWriterId", out var dataSetWriterId)) ? dataSetWriterId : message.EndpointUrl ?? message.ApplicationUri, SequenceNumber = 0, Status = StatusCode.LookupSymbolicId(message.Value.StatusCode.Code), MetaDataVersion = "1.0", Timestamp = message.Timestamp, Payload = new Dictionary <string, DataValueModel>() { [message.NodeId.AsString(null)] = new DataValueModel() { Value = message?.Value?.WrappedValue.Value, Status = (message?.Value?.StatusCode.Code == StatusCodes.Good) ? null : StatusCode.LookupSymbolicId(message.Value.StatusCode.Code), SourceTimestamp = (message?.Value?.SourceTimestamp == DateTime.MinValue) ? null : (DateTime?)message?.Value?.SourceTimestamp, ServerTimestamp = (message?.Value?.ServerTimestamp == DateTime.MinValue) ? null : (DateTime?)message?.Value?.ServerTimestamp } } }; await Task.WhenAll(_handlers.Select(h => h.HandleMessageAsync(dataset))); } catch (Exception ex) { _logger.Error(ex, "Publishing message {message} failed with exception - skip", message); } }
/// <inheritdoc/> public async Task HandleAsync(string deviceId, string moduleId, byte[] payload, IDictionary <string, string> properties, Func <Task> checkpoint) { try { var context = new ServiceMessageContext(); var decoder = new JsonDecoderEx(new MemoryStream(payload), context); while (decoder.ReadEncodeable(null, typeof(NetworkMessage)) is NetworkMessage message) { foreach (var dataSetMessage in message.Messages) { var dataset = new DataSetMessageModel { PublisherId = message.PublisherId, MessageId = message.MessageId, DataSetClassId = message.DataSetClassId, DataSetWriterId = dataSetMessage.DataSetWriterId, SequenceNumber = dataSetMessage.SequenceNumber, Status = StatusCode.LookupSymbolicId(dataSetMessage.Status.Code), MetaDataVersion = $"{dataSetMessage.MetaDataVersion.MajorVersion}" + $".{dataSetMessage.MetaDataVersion.MinorVersion}", Timestamp = dataSetMessage.Timestamp, Payload = new Dictionary <string, DataValueModel>() }; foreach (var datapoint in dataSetMessage.Payload) { var codec = _encoder.Create(context); var type = BuiltInType.Null; dataset.Payload[datapoint.Key] = new DataValueModel { Value = datapoint.Value == null ? null : codec.Encode(datapoint.Value.WrappedValue, out type), DataType = type == BuiltInType.Null ? null : type.ToString(), Status = (datapoint.Value?.StatusCode.Code == StatusCodes.Good) ? null : StatusCode.LookupSymbolicId(datapoint.Value.StatusCode.Code), SourceTimestamp = (datapoint.Value?.SourceTimestamp == DateTime.MinValue) ? null : datapoint.Value?.SourceTimestamp, SourcePicoseconds = (datapoint.Value?.SourcePicoseconds == 0) ? null : datapoint.Value?.SourcePicoseconds, ServerTimestamp = (datapoint.Value?.ServerTimestamp == DateTime.MinValue) ? null : datapoint.Value?.ServerTimestamp, ServerPicoseconds = (datapoint.Value?.ServerPicoseconds == 0) ? null : datapoint.Value?.ServerPicoseconds }; } await Task.WhenAll(_handlers.Select(h => h.HandleMessageAsync(dataset))); } } } catch (Exception ex) { _logger.Error(ex, "Subscriber json network message handling failed - skip"); } }
/// <inheritdoc/> public async Task HandleAsync(string deviceId, string moduleId, byte[] payload, IDictionary <string, string> properties, Func <Task> checkpoint) { try { var context = new ServiceMessageContext(); var decoder = new JsonDecoderEx(new MemoryStream(payload), context); while (decoder.ReadEncodeable(null, typeof(MonitoredItemMessage)) is MonitoredItemMessage message) { var type = BuiltInType.Null; var codec = _encoder.Create(context); var dataset = new DataSetMessageModel { PublisherId = (message.ExtensionFields != null && message.ExtensionFields.TryGetValue("PublisherId", out var publisherId)) ? publisherId : message.ApplicationUri ?? message.EndpointUrl, MessageId = null, DataSetClassId = message.NodeId.AsString(null), DataSetWriterId = (message.ExtensionFields != null && message.ExtensionFields.TryGetValue("DataSetWriterId", out var dataSetWriterId)) ? dataSetWriterId : message.EndpointUrl ?? message.ApplicationUri, SequenceNumber = message.SequenceNumber, Status = StatusCode.LookupSymbolicId(message.Value.StatusCode.Code), MetaDataVersion = "1.0", Timestamp = message.Timestamp, Payload = new Dictionary <string, DataValueModel>() { [message.NodeId.AsString(context)] = new DataValueModel { Value = message?.Value == null ? null : codec.Encode(message.Value.WrappedValue, out type), DataType = type == BuiltInType.Null ? null : type.ToString(), Status = (message?.Value?.StatusCode.Code == StatusCodes.Good) ? null : StatusCode.LookupSymbolicId(message.Value.StatusCode.Code), SourceTimestamp = (message?.Value?.SourceTimestamp == DateTime.MinValue) ? null : message?.Value?.SourceTimestamp, SourcePicoseconds = (message?.Value?.SourcePicoseconds == 0) ? null : message?.Value?.SourcePicoseconds, ServerTimestamp = (message?.Value?.ServerTimestamp == DateTime.MinValue) ? null : message?.Value?.ServerTimestamp, ServerPicoseconds = (message?.Value?.ServerPicoseconds == 0) ? null : message?.Value?.ServerPicoseconds } } }; await Task.WhenAll(_handlers.Select(h => h.HandleMessageAsync(dataset))); } } catch (Exception ex) { _logger.Error(ex, "Publishing messages failed - skip"); } }
/// <inheritdoc/> public async Task HandleAsync(string deviceId, string moduleId, byte[] payload, IDictionary <string, string> properties, Func <Task> checkpoint) { var json = Encoding.UTF8.GetString(payload); using (var stream = new MemoryStream(payload)) { var context = new ServiceMessageContext(); using (var decoder = new JsonDecoderEx(stream, context)) { var networkMessage = decoder.ReadEncodeable(null, typeof(NetworkMessage)) as NetworkMessage; foreach (var message in networkMessage.Messages) { foreach (var datapoint in message.Payload) { try { var sample = new MonitoredItemSampleModel() { Value = (datapoint.Value?.WrappedValue.Value != null) ? datapoint.Value.WrappedValue.Value : null, Status = StatusCode.LookupSymbolicId(datapoint.Value.StatusCode.Code), TypeId = (datapoint.Value?.WrappedValue.TypeInfo != null) ? TypeInfo.GetSystemType( datapoint.Value.WrappedValue.TypeInfo.BuiltInType, datapoint.Value.WrappedValue.TypeInfo.ValueRank) : null, DataSetId = message.DataSetWriterId, Timestamp = DateTime.UtcNow, SubscriptionId = message.DataSetWriterId, EndpointId = networkMessage.PublisherId, NodeId = datapoint.Key, SourcePicoseconds = datapoint.Value.SourcePicoseconds, ServerPicoseconds = datapoint.Value.ServerPicoseconds, SourceTimestamp = datapoint.Value.SourceTimestamp, ServerTimestamp = datapoint.Value.ServerTimestamp }; if (sample == null) { continue; } await Task.WhenAll(_handlers.Select(h => h.HandleSampleAsync( sample))); } catch (Exception ex) { _logger.Error(ex, "Subscriber message {message} failed with exception - skip", message); } } } } } }
/// <inheritdoc/> public async Task HandleAsync(string deviceId, string moduleId, byte[] payload, IDictionary <string, string> properties, Func <Task> checkpoint) { MonitoredItemMessage message; try { var context = new ServiceMessageContext(); using (var stream = new MemoryStream(payload)) { using (var decoder = new JsonDecoderEx(stream, context)) { var result = decoder.ReadEncodeable(null, typeof(MonitoredItemMessage)) as MonitoredItemMessage; message = result; } } } catch (Exception ex) { _logger.Error(ex, "Failed to decode message"); return; } try { var sample = new MonitoredItemSampleModel() { Value = (message?.Value?.WrappedValue.Value != null) ? message.Value.WrappedValue.Value : null, Status = StatusCode.LookupSymbolicId(message.Value.StatusCode.Code), TypeId = (message?.Value?.WrappedValue.TypeInfo != null) ? TypeInfo.GetSystemType( message.Value.WrappedValue.TypeInfo.BuiltInType, message.Value.WrappedValue.TypeInfo.ValueRank) : null, DataSetId = !string.IsNullOrEmpty(message.DisplayName) ? message.DisplayName : message.NodeId.AsString(null), Timestamp = message.Timestamp, EndpointId = (message.ExtensionFields != null && message.ExtensionFields.TryGetValue("EndpointId", out var endpointId)) ? endpointId : message.ApplicationUri ?? message.SubscriptionId, SubscriptionId = message.SubscriptionId ?? message.ApplicationUri, NodeId = message.NodeId.AsString(null), DisplayName = message.DisplayName, SourcePicoseconds = message.Value.SourcePicoseconds, ServerPicoseconds = message.Value.ServerPicoseconds, SourceTimestamp = message.Value.SourceTimestamp, ServerTimestamp = message.Value.ServerTimestamp }; await Task.WhenAll(_handlers.Select(h => h.HandleSampleAsync(sample))); } catch (Exception ex) { _logger.Error(ex, "Publishing message {message} failed with exception - skip", message); } }
/// <inheritdoc/> public async Task HandleAsync(string deviceId, string moduleId, byte[] payload, IDictionary <string, string> properties, Func <Task> checkpoint) { var json = Encoding.UTF8.GetString(payload); using (var stream = new MemoryStream(payload)) { var context = new ServiceMessageContext(); try { using (var decoder = new JsonDecoderEx(stream, context)) { var networkMessage = decoder.ReadEncodeable(null, typeof(NetworkMessage)) as NetworkMessage; foreach (var dataSetMessage in networkMessage.Messages) { var dataset = new DataSetMessageModel { PublisherId = networkMessage.PublisherId, MessageId = networkMessage.MessageId, DataSetClassId = networkMessage.DataSetClassId, DataSetWriterId = dataSetMessage.DataSetWriterId, SequenceNumber = dataSetMessage.SequenceNumber, Status = StatusCode.LookupSymbolicId(dataSetMessage.Status.Code), MetaDataVersion = $"{dataSetMessage.MetaDataVersion.MajorVersion}" + $".{dataSetMessage.MetaDataVersion.MinorVersion}", Timestamp = dataSetMessage.Timestamp, Payload = new Dictionary <string, DataValueModel>() }; foreach (var datapoint in dataSetMessage.Payload) { dataset.Payload[datapoint.Key] = new DataValueModel() { Value = datapoint.Value?.Value, Status = (datapoint.Value?.StatusCode.Code == StatusCodes.Good) ? null : StatusCode.LookupSymbolicId(datapoint.Value.StatusCode.Code), SourceTimestamp = (datapoint.Value?.SourceTimestamp == DateTime.MinValue) ? null : (DateTime?)datapoint.Value?.SourceTimestamp, ServerTimestamp = (datapoint.Value?.ServerTimestamp == DateTime.MinValue) ? null : (DateTime?)datapoint.Value?.ServerTimestamp }; } await Task.WhenAll(_handlers.Select(h => h.HandleMessageAsync(dataset))); } } } catch (Exception ex) { _logger.Error(ex, "Subscriber json network message handling failed - skip"); } } }
public void EncodeDecodeNetworkMessageFull() { var payload = new Dictionary <string, DataValue> { ["abcd"] = new DataValue(new Variant(1234), StatusCodes.Good, DateTime.Now, DateTime.UtcNow), ["http://microsoft.com"] = new DataValue(new Variant(-222222222), StatusCodes.Bad, DateTime.MinValue, DateTime.Now), ["1111111111111111111111111"] = new DataValue(new Variant(false), StatusCodes.Bad, DateTime.UtcNow, DateTime.MinValue), ["@#$%^&*()_+~!@#$%^*(){}"] = new DataValue(new Variant(new byte[] { 0, 2, 4, 6 }), StatusCodes.Good), ["1245"] = new DataValue(new Variant("hello"), StatusCodes.Bad, DateTime.Now, DateTime.MinValue), ["..."] = new DataValue(new Variant(new Variant("imbricated"))) }; var message = new DataSetMessage { DataSetWriterId = "WriterId", MetaDataVersion = new ConfigurationVersionDataType { MajorVersion = 1, MinorVersion = 1 }, SequenceNumber = ++_currentSequenceNumber, Status = StatusCodes.Good, Timestamp = DateTime.UtcNow, Picoseconds = 1234, MessageContentMask = (uint)( JsonDataSetMessageContentMask.DataSetWriterId | JsonDataSetMessageContentMask.SequenceNumber | JsonDataSetMessageContentMask.MetaDataVersion | JsonDataSetMessageContentMask.Timestamp | JsonDataSetMessageContentMask.Status), Payload = new DataSet(payload, (uint)( DataSetFieldContentMask.StatusCode | DataSetFieldContentMask.SourceTimestamp | DataSetFieldContentMask.ServerTimestamp | DataSetFieldContentMask.SourcePicoSeconds | DataSetFieldContentMask.ServerPicoSeconds)) }; var networkMessage = new NetworkMessage { MessageId = Guid.NewGuid().ToString(), // TODO MessageType = "ua-data", Messages = new List <DataSetMessage>(), PublisherId = "PublisherId", DataSetClassId = "1234" }; networkMessage.Messages.Add(message); networkMessage.MessageContentMask = (uint)( JsonNetworkMessageContentMask.PublisherId | JsonNetworkMessageContentMask.NetworkMessageHeader | JsonNetworkMessageContentMask.SingleDataSetMessage | JsonNetworkMessageContentMask.DataSetClassId); byte[] buffer; var context = new ServiceMessageContext(); using (var stream = new MemoryStream()) { using (var encoder = new JsonEncoderEx(stream, context)) { networkMessage.Encode(encoder); } buffer = stream.ToArray(); } ConvertToOpcUaUniversalTime(networkMessage); using (var stream = new MemoryStream(buffer)) { using (var decoder = new JsonDecoderEx(stream, context)) { var result = decoder.ReadEncodeable(null, typeof(NetworkMessage)) as NetworkMessage; Assert.Equal(networkMessage, result); } } }
public void ReadWriteProgramDiagnostic2DataTypeStream() { // Create dummy type var expected = new ProgramDiagnostic2DataType { CreateClientName = "Testname", CreateSessionId = new NodeId(Guid.NewGuid()), InvocationCreationTime = DateTime.UtcNow, LastMethodCall = "swappido", LastMethodCallTime = DateTime.UtcNow, LastMethodInputArguments = new ArgumentCollection { new Argument("something1", new NodeId(2354), -1, "somedesciroeioi") { ArrayDimensions = new uint[0] }, new Argument("something2", new NodeId(23), -1, "fdsadfsdaf") { ArrayDimensions = new uint[0] }, new Argument("something3", new NodeId(44), 1, "fsadf sadfsdfsadfsd") { ArrayDimensions = new uint[0] }, new Argument("something4", new NodeId(23), 1, "dfad sdafdfdf fasdf") { ArrayDimensions = new uint[0] } }, LastMethodInputValues = new VariantCollection { new Variant(4L), new Variant("test"), new Variant(new long[] { 1, 2, 3, 4, 5 }), new Variant(new string[] { "1", "2", "3", "4", "5" }) }, LastMethodOutputArguments = new ArgumentCollection { new Argument("foo1", new NodeId(2354), -1, "somedesciroeioi") { ArrayDimensions = new uint[0] }, new Argument("foo2", new NodeId(33), -1, "fdsadfsdaf") { ArrayDimensions = new uint[0] }, new Argument("adfsdafsdsdsafdsfa", new NodeId("absc"), 1, "fsadf sadfsdfsadfsd") { ArrayDimensions = new uint[0] }, new Argument("ddddd", new NodeId(25), 1, "dfad sdafdfdf fasdf") { ArrayDimensions = new uint[0] } }, LastMethodOutputValues = new VariantCollection { new Variant(4L), new Variant("test"), new Variant(new long[] { 1, 2, 3, 4, 5 }), new Variant(new string[] { "1", "2", "3", "4", "5" }) }, LastMethodReturnStatus = StatusCodes.BadAggregateConfigurationRejected, LastMethodSessionId = new NodeId( Utils.Nonce.CreateNonce(32)), LastTransitionTime = DateTime.UtcNow - TimeSpan.FromDays(23) }; var count = 100; byte[] buffer; var context = new ServiceMessageContext(); using (var stream = new MemoryStream()) { using (var encoder = new JsonEncoderEx(stream, context, JsonEncoderEx.JsonEncoding.Array)) { for (var i = 0; i < count; i++) { encoder.WriteEncodeable(null, expected, expected.GetType()); } } buffer = stream.ToArray(); } using (var stream = new MemoryStream(buffer)) { using (var decoder = new JsonDecoderEx(stream, context)) { for (var i = 0; i < count; i++) { var result = decoder.ReadEncodeable(null, expected.GetType()); Assert.True(result.IsEqual(expected)); } var eof = decoder.ReadEncodeable(null, expected.GetType()); Assert.Null(eof); } } }