public async Task <Twin> GetTwinAsync() { return(await ModuleClient.GetTwinAsync()); }
public ValidateHostRanges(TestReporter testReporter, IMetricsScraper scraper, ModuleClient moduleClient) : base(testReporter, scraper, moduleClient) { }
public async Task SetMethodHandlerAsync(string methodName, MethodCallback methodHandler, object userContext) { await ModuleClient.SetMethodHandlerAsync(methodName, methodHandler, userContext); Log.Information($"Method Handler Set for {methodName}"); }
public async Task CloseAsync() { await ModuleClient.CloseAsync(); Log.Information("Closed ModuleClient"); }
/// <summary> /// Creates a blackboard from a XML configuration file /// </summary> /// <param name="path">The path of the XML configuration file</param> /// <param name="log">Output log</param> /// <returns>The configured blackboard</returns> public static Blackboard FromXML(string path, TextWriter log) { Blackboard blackboard; XmlDocument doc; XmlDocument tmpDoc; XmlNodeList modules; XmlNodeList commands; int i, j, cmdCount; string moduleName; string programPath; string programArgs; string cmdName; bool cmdParams; bool cmdAnswer; bool cmdPriority; int cmdTimeOut; Command startupCommand; Prototype msg; List<Prototype> msgList; ModuleClient mod; IPAddress ip; int port; log.Flush(); if (!File.Exists(path)) { log.WriteLine("File does not exist"); throw new FileLoadException("File does not exist"); } doc = new XmlDocument(); doc.Load(path); if ( (doc.GetElementsByTagName("blackboard").Count != 1) || (doc.GetElementsByTagName("configuration").Count != 1) || (doc.GetElementsByTagName("modules").Count < 1)) { log.WriteLine("Incorrect format"); throw new FileLoadException("Incorrect format"); } blackboard = new Blackboard(); log.WriteLine("Loading configuration..."); tmpDoc = new XmlDocument(); tmpDoc.LoadXml(doc.GetElementsByTagName("configuration")[0].OuterXml); // Leo puerto if ((tmpDoc.GetElementsByTagName("port").Count != 1) || !Int32.TryParse(tmpDoc.GetElementsByTagName("port")[0].InnerText, out blackboard.port)) { blackboard.port = 2300; log.WriteLine("No Blackboard port specified, using default: " + blackboard.Port); } else log.WriteLine("Blackboard port: " + blackboard.Port); if (doc.GetElementsByTagName("modules").Count < 1) { log.WriteLine("No modules to load"); throw new Exception("No modules to load"); } modules = doc.GetElementsByTagName("modules")[0].ChildNodes; blackboard.Initialize(); #region Extraccion de Modulos for (i = 0; i < modules.Count; ++i) { try { // Verifico que sea un modulo if ((modules[i].Name != "module") || (modules[i].Attributes.Count < 1) || (modules[i].Attributes["name"].Value.Length < 1)) continue; #region Extraccion de info del modulo moduleName = modules[i].Attributes["name"].Value.ToUpper(); log.WriteLine("Loading module " + moduleName); // Creo un subdocumento XML tmpDoc.LoadXml(modules[i].OuterXml); // Leo el Path de la aplicacion if (tmpDoc.GetElementsByTagName("programPath").Count != 0) programPath = tmpDoc.GetElementsByTagName("programPath")[0].InnerText; // Leo los argumentos con que se inicia la aplicacion if (tmpDoc.GetElementsByTagName("programArgs").Count != 0) programArgs = tmpDoc.GetElementsByTagName("programArgs")[0].InnerText; // Leo el comando de inicio //if (tmpDoc.GetElementsByTagName("startupCommand").Count != 0) // startupMessage = Command.Parse(tmpDoc.GetElementsByTagName("startupCommand")[0].InnerText); // Leo la IP de la maquina donde esta el modulo if ( (tmpDoc.GetElementsByTagName("ip").Count == 0) || !IPAddress.TryParse(tmpDoc.GetElementsByTagName("ip")[0].InnerText, out ip)) { log.WriteLine("\tInvalid IP Address"); log.WriteLine("Module skipped"); continue; } // Leo el puerto de conexion del modulo if ( (tmpDoc.GetElementsByTagName("port").Count == 0) || !Int32.TryParse(tmpDoc.GetElementsByTagName("port")[0].InnerText, out port) || (port <= 1024)) { log.WriteLine("\tInvalid port"); log.WriteLine("Module skipped"); continue; } #endregion // Creo el modulo mod = new ModuleClient(moduleName, ip, port); // Leo lista de comandos. log.WriteLine("\tLoading module commands..."); if (doc.GetElementsByTagName("commands").Count < 1) { log.WriteLine("\tNo commands to load"); log.WriteLine("Module skipped"); continue; } commands = tmpDoc.GetElementsByTagName("commands")[0].ChildNodes; msgList = new List<Prototype>(commands.Count); #region Extraccion de Comandos de modulo for (j = 0; j < commands.Count; ++j) { // Verifico que sea un comando if ((commands[j].Name == "command") && (commands[j].Attributes.Count >= 3) && (commands[j].Attributes["name"].Value.Length > 1) && Boolean.TryParse(commands[j].Attributes["answer"].Value, out cmdAnswer) && Int32.TryParse(commands[j].Attributes["timeout"].Value, out cmdTimeOut) && (cmdTimeOut >= 0)) { // Leo nombre de comando cmdName = commands[j].Attributes["name"].Value; log.WriteLine("\t\tAdded command " + cmdName); // Verifico si requiere parametros if(!Boolean.TryParse(commands[j].Attributes["parameters"].Value, out cmdParams)) cmdParams = true; // Verifico si tiene prioridad if (!Boolean.TryParse(commands[j].Attributes["priority"].Value, out cmdPriority)) cmdPriority = false; // Creo el prototipo msg = new Prototype(cmdName, cmdParams, cmdAnswer, cmdTimeOut); // Agrego el prototipo al modulo mod.Prototypes.Add(msg); msgList.Add(msg); } else log.WriteLine("\t\tInvalid Command "); } #endregion // Si no hay comandos soportados por el modulo, salto el modulo if (msgList.Count < 1) { log.WriteLine("\tAll commands rejected."); log.WriteLine("Module skipped"); continue; } // Agrego el modulo al blackboard blackboard.modules.Add(mod); log.WriteLine("Loading module complete!"); } catch { // Error al cargar el modulo log.WriteLine("Invalid module"); // Continuo con el siguiente continue; } #endregion } return blackboard; /* <module name=""> <programPath></programPath> <programArgs></programArgs> <startupCommand></startupCommand> <ip>192.168.1.x</ip> <port>2000</port> <commands> <command name="" answer="True" timeout="100" /> <command name="" answer="True" timeout="100" /> <command name="" answer="True" timeout="100" /> </commands> </module> */ }
public async Task SendEventAsync(string outputName, Message message) { await ModuleClient.SendEventAsync(outputName, message); Log.Information($"Message Sent to {outputName}"); }
private void Process(ModuleClient origin, string str, string id) { throw new Exception("The method or operation is not implemented."); }
public EventHubMetricsUpload(ModuleClient moduleClient) { this.moduleClient = Preconditions.CheckNotNull(moduleClient, nameof(moduleClient)); }
private void module_Disconnected(ModuleClient m) { if (BlackboardDisconnectedFromModule != null) BlackboardDisconnectedFromModule(m); }
//public bool ParseMessage(string s, out Module m) //private bool ParseMessage(string s, out Module m) //{ // string rxSpace = @"[\t ]+"; // string rxOrigin = @"(?<origin>[A-Z][A-Z\-]*)"; // string rxDestination = @"((?<destination>[A-Z][A-Z\-]*)" + rxSpace + ")?"; // string rxCommand = @"(?<cmd>[a-z][a-zA-Z0-9\-_]*)"; // string rxParam = @"(?<param>\x22[^\x00\0x22]*\x22)"; // //string rxParam = @"(?<param>\x22[a-zA-Z0-9\-_ \t\.]*\x22)"; // string rxSuccess = @"[\t ]*"; // string rxStr = @"(?<str>[\w \t\.]+[\w\.])"; // string rxId = "(" + rxSpace + @"\@(?<id>\d+)[\t ]*)?"; // Match result; // Regex rx; // Module origin; // Module destination; // string command; // string param; // string str; // string msg; // string id; // m = null; // rx = new Regex(rxOrigin + rxSpace + rxDestination + "(?<msg>(" + rxCommand + rxSpace + rxParam + "|" + rxStr + "))" + rxId, RegexOptions.Compiled); // result = rx.Match(s.Trim()); // if (!result.Success) return false; // origin = getModule(result.Result("${origin}")); // if (origin == null) // { // if(MessageReceived!= null) MessageReceived(null, s); // return false; // } // destination = getModule(result.Result("${destination}")); // command = result.Result("${cmd}"); // param = result.Result("${param}"); // str = result.Result("${str}"); // id = result.Result("${id}"); // msg = result.Result("${msg}"); // if(MessageReceived!= null) // MessageReceived(origin, msg + (id != "" ? " @" + id : "")); // if (destination != null) // RedirectMsg(origin, destination, msg + (id != "" ? " @" + id : "")); // if(command != "") // Process(origin, command, param, id); // else Process(origin, str, id); // return true; //} private void Process(ModuleClient origin, string command, string param, string id) { //throw new Exception("The method or operation is not implemented."); }
private void module_Connected(ModuleClient m) { if (BlackboardConnectedToModule != null) BlackboardConnectedToModule(m); }
/// <summary> /// Look for a module in the blackboard that supports specified command /// </summary> /// <param name="commandName">The name of the command to look for</param> /// <param name="destination">When this method returns, contains the Module that supports the command /// specified, if the conversion succeeded, or null if no module supports the command. /// The search fails if the s parameter is a null reference (Nothing in Visual Basic) or is not of the correct format. /// This parameter is passed uninitialized</param> /// <param name="prototype">When this method returns, contains the Prototype for the command /// specified, if the conversion succeeded, or null if no module supports the command. /// The conversion fails if the s parameter is a null reference (Nothing in Visual Basic) or is not of the correct format. /// This parameter is passed uninitialized</param> /// <returns>true if a destination module was found, false otherwise</returns> public bool FindDestinationModule(string commandName, out ModuleClient destination, out Prototype prototype) { destination = null; prototype = null; if ((commandName == null) || !Regex.IsMatch(commandName, @"[A-Za-z_]+")) return false; foreach (ModuleClient m in modules) if (m.SupportCommand(commandName, out prototype)) { destination = m; return true; } return false; }
/// <summary> /// Look for a module in the blackboard that supports specified command /// </summary> /// <param name="commandName">The name of the command to look for</param> /// <param name="destination">When this method returns, contains the Module that supports the command /// specified, if the conversion succeeded, or null if no module supports the command. /// The search fails if the s parameter is a null reference (Nothing in Visual Basic) or is not of the correct format. /// This parameter is passed uninitialized</param> /// <returns>true if a destination module was found, false otherwise</returns> public bool FindDestinationModule(string commandName, out ModuleClient destination) { Prototype p; return FindDestinationModule(commandName, out destination, out p); }
async Task InitCallBack() { try { ITransportSettings transportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { transportSettings }; //if running as Edge module if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("IOTEDGE_APIVERSION"))) { ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("IOTEDGE_TIMEOUT"))) { ioTHubModuleClient.OperationTimeoutInMilliseconds = Convert.ToUInt32(Environment.GetEnvironmentVariable("IOTEDGE_TIMEOUT")); Logger.Log($"Changing timeout to {ioTHubModuleClient.OperationTimeoutInMilliseconds} ms", Logger.LoggingLevel.Info); } Logger.Init(ioTHubModuleClient); Logger.Log("Getting properties from module twin...", Logger.LoggingLevel.Info); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; try { LoraDeviceInfoManager.FacadeServerUrl = moduleTwinCollection["FacadeServerUrl"]; Logger.Log($"Facade function url: {LoraDeviceInfoManager.FacadeServerUrl}", Logger.LoggingLevel.Always); } catch (ArgumentOutOfRangeException e) { Logger.Log("Module twin FacadeServerName not exist", Logger.LoggingLevel.Error); throw e; } try { LoraDeviceInfoManager.FacadeAuthCode = moduleTwinCollection["FacadeAuthCode"]; } catch (ArgumentOutOfRangeException e) { Logger.Log("Module twin FacadeAuthCode does not exist", Logger.LoggingLevel.Error); throw e; } await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null); await ioTHubModuleClient.SetMethodHandlerAsync("ClearCache", ClearCache, null); } //running as non edge module for test and debugging else { LoraDeviceInfoManager.FacadeServerUrl = Environment.GetEnvironmentVariable("FacadeServerUrl"); LoraDeviceInfoManager.FacadeAuthCode = Environment.GetEnvironmentVariable("FacadeAuthCode"); } } catch (Exception ex) { Logger.Log($"Initialization failed with error: {ex.Message}", Logger.LoggingLevel.Error); throw ex; } }
private void RedirectMsg(ModuleClient origin, ModuleClient destination, string msg) { // destination.SendMessage(msg); //if (MessageRedirect != null) // MessageRedirect(origin, destination, msg); }
static async Task CallDirectMethodFromCloud( string serviceClientConnectionString, string deviceId, string moduleId, TransportType transportType, TimeSpan delay, CancellationTokenSource cts) { Logger.LogInformation("CallDirectMethodFromCloud started."); ModuleClient moduleClient = null; ServiceClient serviceClient = null; try { Guid batchId = Guid.NewGuid(); int count = 1; IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(serviceClientConnectionString); Logger.LogInformation($"Prepare to call Direct Method from cloud ({iotHubConnectionStringBuilder.IotHubName}) on device [{deviceId}] module [{moduleId}]"); serviceClient = ServiceClient.CreateFromConnectionString(serviceClientConnectionString, Microsoft.Azure.Devices.TransportType.Amqp); var cloudToDeviceMethod = new CloudToDeviceMethod("HelloWorldMethod").SetPayloadJson("{ \"Message\": \"Hello\" }"); moduleClient = await ModuleUtil.CreateModuleClientAsync( transportType, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy, Logger); while (!cts.Token.IsCancellationRequested) { Logger.LogInformation($"Calling Direct Method from cloud ({iotHubConnectionStringBuilder.IotHubName}) on device [{deviceId}] module [{moduleId}] of count {count}."); try { CloudToDeviceMethodResult result = await serviceClient.InvokeDeviceMethodAsync(deviceId, moduleId, cloudToDeviceMethod, CancellationToken.None); if (result.Status == (int)HttpStatusCode.OK) { var eventMessage = new Message(Encoding.UTF8.GetBytes($"Direct Method [{transportType}] Call succeeded.")); eventMessage.Properties.Add("sequenceNumber", count.ToString()); eventMessage.Properties.Add("batchId", batchId.ToString()); Logger.LogInformation($"Calling Direct Method from cloud with count {count} succeeded."); await moduleClient.SendEventAsync(RouteOutputName, eventMessage); } else { Logger.LogError($"Calling Direct Method from cloud with count {count} failed with status code {result.Status}."); } count++; } catch (Exception e) { Logger.LogError($"Exception caught with count {count}: {e}"); } await Task.Delay(delay, cts.Token); } } catch (Exception e) { Logger.LogError($"Exception caught: {e}"); throw; } finally { Logger.LogInformation("Close connection for service client and module client"); if (serviceClient != null) { await serviceClient.CloseAsync(); } if (moduleClient != null) { await moduleClient.CloseAsync(); } } Logger.LogInformation("CallDirectMethodFromCloud finished."); }
/// <summary> /// Iterate through each Modbus session to poll data /// </summary> /// <param name="userContext"></param> /// <returns></returns> static async Task Start(object userContext) { var userContextValues = userContext as Tuple <ModuleClient, Slaves.ModuleHandle>; if (userContextValues == null) { throw new InvalidOperationException("UserContext doesn't contain " + "expected values"); } ModuleClient ioTHubModuleClient = userContextValues.Item1; Slaves.ModuleHandle moduleHandle = userContextValues.Item2; if (moduleHandle.ModbusSessionList.Count == 0) { Console.WriteLine("No valid modbus session available!!"); } foreach (ModbusSlaveSession s in moduleHandle.ModbusSessionList) { if (s.config.Operations.Count == 0) { Console.WriteLine("No valid operation in modbus session available!!"); } else { s.ProcessOperations(); } } while (m_run) { Message message = null; switch (m_version.Version) { case "1": List <object> resultV1 = moduleHandle.CollectAndResetOutMessageFromSessionsV1(); if (resultV1.Count > 0) { message = new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(resultV1))); message.Properties.Add("content-type", "application/edge-modbus-json"); } break; // Reformat for IoT Central case "2": List <object> resultV1 = moduleHandle.CollectAndResetOutMessageFromSessionsV1(); Dictionary <string, string> resultCentral = ModuleHandle.UnfurlOutMessageForCentral(resultV1); if (resultV1.Count > 0) { message = new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(resultCentral))); message.Properties.Add("content-type", "application/edge-modbus-json"); } break; default: List <object> result = moduleHandle.CollectAndResetOutMessageFromSessions(); if (result.Count > 0) { ModbusOutMessage out_message = new ModbusOutMessage { PublishTimestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Content = result }; message = new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(out_message))); message.Properties.Add("content-type", "application/edge-modbus-json"); } break; } if (message != null) { await ioTHubModuleClient.SendEventAsync("modbusOutput", message); } if (!m_run) { break; } await Task.Delay(m_interval.PublishInterval); } moduleHandle.Release(); }
public void ModuleClient_CreateFromConnectionString_WithModuleId() { ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(ConnectionStringWithModuleId); Assert.IsNotNull(moduleClient); }
static async void SendVesselData(ModuleClient moduleClient) { if (File.Exists(_dataFile)) { FileStream stream = null; string log = string.Empty; try { stream = File.OpenRead(_dataFile); log = new StreamReader(stream).ReadToEnd(); stream.Close(); while (true) { // Parse bool readingMeasurements = false; List <string> channels = new List <string>(); List <string> tags = new List <string>(); List <string> units = new List <string>(); string deviceType = string.Empty; string deviceID = string.Empty; StringBuilder builder = new StringBuilder(); StringReader reader = new StringReader(log); DateTime dateTime = DateTime.Now; string line = reader.ReadLine(); while (line != null) { string[] data = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (data != null && data.Length > 0) // Skip empty lines { if (!readingMeasurements) { if (data[0] == "Tag") { for (int i = 1; i < data.Length; i++) { tags.Add(data[i].Trim().Replace(" ", "_").Replace("-", "_")); } } else if (data[0] == "Unit") { for (int i = 1; i < data.Length; i++) { if (data[i].Trim() == "?S/cm") { data[i] = "uS/cm"; } units.Add(data[i].Trim()); } } else if (data[0] == "Date") { readingMeasurements = true; } else { if (data[0] == "Device Type") { deviceType = data[1].Trim(); } else if (data[0] == "Serial No.") { deviceID = data[1].Trim(); } } } else { builder.Append("{"); builder.AppendFormat("Collector:\"{0}\",", _collectorName); builder.Append("CollectorType:\"Vessel2\","); builder.AppendFormat("DeviceID:\"{0}\",", deviceID); builder.AppendFormat("DeviceType:\"{0}\",", deviceType); builder.AppendFormat("DateTime:\"{0}\",", dateTime); for (int i = 3; i < data.Length; i++) { if (i % 2 == 0) { builder.AppendFormat("{0}_MAX:{1},", tags[(i - 3) / 2], data[i]); builder.AppendFormat("{0}_UOM:\"{1}\"", tags[(i - 3) / 2], units[(i - 3) / 2].Trim()); } else { if (i > 3) { builder.Append(","); } builder.AppendFormat("{0}_MIN:{1},", tags[(i - 3) / 2], data[i]); } } builder.Append("}"); JObject jsonLog = JObject.Parse(builder.ToString()); Console.WriteLine("Sending Vessel2 Telemetry"); await moduleClient.SendEventAsync("output1", new Message(Encoding.UTF8.GetBytes(jsonLog.ToString()))); } } builder.Clear(); dateTime.AddSeconds(1); line = reader.ReadLine(); } Console.WriteLine("Vessel2Collector: File {0} - processed successfully.", _dataFile); await Task.Delay(600000); } } catch (Exception ex) { Guid correlationID = Guid.NewGuid(); Console.WriteLine("Vessel2Collector: Correlation ID {0}. Processing of file {1} failed. Exception: {2}", correlationID, _dataFile, ex.Message); Console.WriteLine("Vessel2Collector: Correlation ID {0}. StackTrace: {1}", correlationID, ex.StackTrace); if (ex.InnerException != null) { Console.WriteLine("Vessel2Collector: Correlation ID {0}. Inner exception: {0}", correlationID, ex.InnerException.Message); Console.WriteLine("Vessel2Collector: Correlation ID {0}. Inner exception StackTrace: {0}", correlationID, ex.InnerException.StackTrace); } } finally { if (stream != null) { stream.Close(); } } } else { Console.WriteLine("Vessel2 DataSet Not Found!"); } }
/// <summary> /// Create ModuleClient from the specified connection string using the specified transport type /// </summary> public static IHubClient CreateModuleClientFromEnvironment(TransportType transportType) { return(new HubClient(ModuleClient.CreateFromEnvironmentAsync(transportType).Result)); }
static async Task <MessageResponse> ProcessAndSendMessageAsync(Message message, object userContext) { Logger.LogInformation($"Received message from device: {message.ConnectionDeviceId}, module: {message.ConnectionModuleId}"); var testResultCoordinatorUrl = Option.None <Uri>(); if (Settings.Current.EnableTrcReporting) { var builder = new UriBuilder(Settings.Current.TestResultCoordinatorUrl); builder.Host = Dns.GetHostEntry(Settings.Current.TestResultCoordinatorUrl.Host).AddressList[0].ToString(); testResultCoordinatorUrl = Option.Some(builder.Uri); } try { if (!(userContext is MessageHandlerContext messageHandlerContext)) { throw new InvalidOperationException("UserContext doesn't contain expected value"); } ModuleClient moduleClient = messageHandlerContext.ModuleClient; DuplicateMessageAuditor duplicateMessageAuditor = messageHandlerContext.DuplicateMessageAuditor; // Must make a new message instead of reusing the old message because of the way the SDK sends messages string trackingId = string.Empty; string batchId = string.Empty; string sequenceNumber = string.Empty; var messageProperties = new List <KeyValuePair <string, string> >(); var testResultReportingClient = Option.None <TestResultReportingClient>(); if (Settings.Current.EnableTrcReporting) { foreach (KeyValuePair <string, string> prop in message.Properties) { switch (prop.Key) { case TestConstants.Message.TrackingIdPropertyName: trackingId = prop.Value ?? string.Empty; break; case TestConstants.Message.BatchIdPropertyName: batchId = prop.Value ?? string.Empty; break; case TestConstants.Message.SequenceNumberPropertyName: sequenceNumber = prop.Value ?? string.Empty; break; } messageProperties.Add(new KeyValuePair <string, string>(prop.Key, prop.Value)); } if (string.IsNullOrWhiteSpace(trackingId) || string.IsNullOrWhiteSpace(batchId) || string.IsNullOrWhiteSpace(sequenceNumber)) { Logger.LogWarning($"Received message missing info: trackingid={trackingId}, batchId={batchId}, sequenceNumber={sequenceNumber}"); return(MessageResponse.Completed); } if (duplicateMessageAuditor.ShouldFilterMessage(sequenceNumber)) { return(MessageResponse.Completed); } // Report receiving message successfully to Test Result Coordinator testResultReportingClient = Option.Some(new TestResultReportingClient { BaseUrl = testResultCoordinatorUrl.OrDefault().AbsoluteUri }); var testResultReceived = new MessageTestResult(Settings.Current.ModuleId + ".receive", DateTime.UtcNow) { TrackingId = trackingId, BatchId = batchId, SequenceNumber = sequenceNumber }; await ModuleUtil.ReportTestResultAsync(testResultReportingClient.OrDefault(), Logger, testResultReceived); Logger.LogInformation($"Successfully received message: trackingid={trackingId}, batchId={batchId}, sequenceNumber={sequenceNumber}"); } if (!Settings.Current.ReceiveOnly) { byte[] messageBytes = message.GetBytes(); var messageCopy = new Message(messageBytes); messageProperties.ForEach(kvp => messageCopy.Properties.Add(kvp)); await moduleClient.SendEventAsync(Settings.Current.OutputName, messageCopy); Logger.LogInformation($"Message relayed upstream for device: {message.ConnectionDeviceId}, module: {message.ConnectionModuleId}"); if (Settings.Current.EnableTrcReporting) { // Report sending message successfully to Test Result Coordinator var testResultSent = new MessageTestResult(Settings.Current.ModuleId + ".send", DateTime.UtcNow) { TrackingId = trackingId, BatchId = batchId, SequenceNumber = sequenceNumber }; await ModuleUtil.ReportTestResultAsync(testResultReportingClient.OrDefault(), Logger, testResultSent); Logger.LogInformation($"Successfully reported message: trackingid={trackingId}, batchId={batchId}, sequenceNumber={sequenceNumber}"); } } else { int uniqueResultsExpected = Settings.Current.UniqueResultsExpected.Expect <ArgumentException>(() => throw new ArgumentException("Must supply this value if in ReceiveOnly mode")); if (!resultsReceived.Contains(sequenceNumber)) { resultsReceived.Add(sequenceNumber); } if (resultsReceived.Count == uniqueResultsExpected) { isFinished = true; } } } catch (Exception ex) { Logger.LogError(ex, $"Error in {nameof(ProcessAndSendMessageAsync)} method"); } return(MessageResponse.Completed); }
public async Task SetInputMessageHandlerAsync(string inputName, MessageHandler messageHandler, object userContext) { await ModuleClient.SetInputMessageHandlerAsync(inputName, messageHandler, userContext); Log.Information($"Message Handler Set for {inputName}"); }
/** * Initialize and Send DeviceInfo message */ public static async Task <GatewayController> Start(ModuleClient ioTHubModuleClient, Twin moduleTwin, CancellationToken cancelToken) { if (moduleTwin == null || moduleTwin.Properties == null) { throw new ArgumentOutOfRangeException("No module Twin desired properties provided."); } GatewayModel gatewayDeviceConfig = CreateGatewayModel(moduleTwin.Properties.Desired); GatewayController gatewayHandle = new GatewayController(gatewayDeviceConfig); DeviceProperties gatewayProperties = gatewayHandle.GatewayDeviceConfig.DeviceProperties; gatewayProperties.DeviceID = moduleTwin.ModuleId; // This is the place you can specify the metadata for your device. The below fields are not mandatory. gatewayProperties.UpdatedTime = DateTime.UtcNow.ToString(); gatewayProperties.FirmwareVersion = "1.0"; gatewayProperties.InstalledRAM = "Unknown"; gatewayProperties.Manufacturer = "Unknown"; gatewayProperties.ModelNumber = "Unknown"; gatewayProperties.Platform = RuntimeInformation.OSDescription; gatewayProperties.Processor = Enum.GetName(typeof(Architecture), RuntimeInformation.OSArchitecture); gatewayProperties.SerialNumber = "Unknown"; // Create send task await Task.Factory.StartNew(async() => { while (true) { if (gatewayHandle.GatewayConfig.ReportEnabledState) { bool hasMutex = false; try{ hasMutex = gatewayHandle.telemetryMutex.WaitOne(gatewayHandle.GatewayConfig.ReportingInterval); if (hasMutex) { if (gatewayHandle.Telemetry.Count > 0) // Send current telemetry data { gatewayHandle.SendData(ioTHubModuleClient, gatewayHandle.Telemetry); gatewayHandle.Telemetry.Clear(); } if (gatewayHandle.IsDeviceInfoUpdated) // Send DeviceInfo structure into module twin { string serializedStr = JsonConvert.SerializeObject(gatewayHandle.GatewayDeviceConfig); TwinCollection reported = JsonConvert.DeserializeObject <TwinCollection>(serializedStr); await ioTHubModuleClient.UpdateReportedPropertiesAsync(reported); gatewayHandle.IsDeviceInfoUpdated = false; } } else { Console.WriteLine("Error. Can't get mutext for telemetry data for {0} ms. Timeout!", gatewayHandle.GatewayConfig.ReportingInterval); } }catch (Exception ex) { Console.WriteLine("Error upload data: {0}, {1}", ex.Message, ex.StackTrace); } finally{ if (hasMutex) { gatewayHandle.telemetryMutex.ReleaseMutex(); } } } await Task.Delay(gatewayHandle.GatewayConfig.ReportingInterval); if (cancelToken.IsCancellationRequested) { // Cancel was called Console.WriteLine("Sending task canceled"); break; } } }, cancelToken); return(gatewayHandle); }
public async Task OpenAsync() { await ModuleClient.OpenAsync(); Log.Information("Opened ModuleClient"); }
public EdgeHubLogHost(ModuleClient client, LogModule.ContainerLocal local) { this.client = client; this.local = local; }
public async Task <Twin> GetTwinAsync(CancellationToken cancellationToken) { return(await ModuleClient.GetTwinAsync(cancellationToken)); }
public WrappingSdkModuleClient(ModuleClient sdkModuleClient) => this.sdkModuleClient = Preconditions.CheckNotNull(sdkModuleClient, nameof(sdkModuleClient));
static async Task <bool> SendMessage(string p_messageString, Message message, ModuleClient p_moduleclient) { bool resultbool = false; if (!string.IsNullOrEmpty(p_messageString)) { var messageBytes = Encoding.UTF8.GetBytes(p_messageString); var pipeMessage = new Message(messageBytes); pipeMessage.ContentEncoding = "utf-8"; pipeMessage.ContentType = "application/json"; // foreach (var prop in message.Properties) foreach (var prop in pipeMessage.Properties) { pipeMessage.Properties.Add(prop.Key, prop.Value); } await p_moduleclient.SendEventAsync("output1", pipeMessage); resultbool = true; } return(resultbool); }
private static async Task OutputErrorRouteMessage(string status, string result, ModuleClient moduleClient) { var outputMessage = new OutputMessage { Status = status, Result = result, }; var messageJson = JsonConvert.SerializeObject(outputMessage); var messageBytes = Encoding.UTF8.GetBytes(messageJson); using (var pipeMessage = new Message(messageBytes)) { pipeMessage.ContentType = "application/json"; pipeMessage.ContentEncoding = "utf-8"; await moduleClient.SendEventAsync("Exception", pipeMessage); Console.WriteLine($"Received message '{status}','{result}' sent"); CompensateThrottle(result); } }
public ModuleClientWrapper(ModuleClient moduleClient) { this.underlyingModuleClient = moduleClient; this.isActive = new AtomicBoolean(true); }
/// <summary> /// Module behavior: /// Sends data periodically (with default frequency of 5 seconds). /// Data trend: /// - Temperature regularly rises from 21C to 100C in regularly with jitter /// - Pressure correlates with Temperature 1 to 10psi /// - Suction Pressure stable around 5psi /// - Discharge Pressure stable around 5psi /// - Ambient temperature stable around 21C /// - Flow is stable with tiny jitter around 25% /// Method for resetting the data stream /// </summary> static async Task SendEvents( ModuleClient moduleClient, int messageCount, SimulatorParameters sim, CancellationTokenSource cts) { int count = 1; double currentTemp = sim.TempMin; double normal = (sim.PressureMax - sim.PressureMin) / (sim.TempMax - sim.TempMin); while (!cts.Token.IsCancellationRequested && (SendUnlimitedMessages(messageCount) || messageCount >= count)) { if (Reset) { currentTemp = sim.TempMin; Reset.Set(false); } if (currentTemp > sim.TempMax) { currentTemp += Rnd.NextDouble() - 0.5; // add value between [-0.5..0.5] } else { currentTemp += -0.25 + (Rnd.NextDouble() * 1.5); // add value between [-0.25..1.25] - average +0.5 } if (sendData) { var events = new List <MessageEvent>(); var deviceId = Environment.MachineName + "-" + Environment.GetEnvironmentVariable("DEVICE"); // Add Desired Number of Events into the Message for (int i = 0; i < eventCount; i++) { events.Add(new MessageEvent { DeviceId = deviceId + "-" + i, TimeStamp = DateTime.UtcNow, Temperature = new SensorReading { Value = currentTemp, Units = "degC", Status = 200 }, Pressure = new SensorReading { Value = sim.PressureMin + ((currentTemp - sim.TempMin) * normal), Units = "psig", Status = 200 }, SuctionPressure = new SensorReading { Value = sim.PressureMin + 4 + ((currentTemp - sim.TempMin) * normal), Units = "psig", Status = 200 }, DischargePressure = new SensorReading { Value = sim.PressureMin + 1 + ((currentTemp - sim.TempMin) * normal), Units = "psig", Status = 200 }, Flow = new SensorReading { Value = Rnd.Next(78, 82), Units = "perc", Status = 200 } }); currentTemp += -0.25 + (Rnd.NextDouble() * 1.5); } var msgBody = new MessageBody { Asset = Environment.GetEnvironmentVariable("ASSET") ?? "whidbey", Source = Environment.MachineName, Events = events }; string dataBuffer = JsonConvert.SerializeObject(msgBody); var eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer)); eventMessage.Properties.Add("sequenceNumber", count.ToString()); eventMessage.Properties.Add("batchId", BatchId.ToString()); eventMessage.Properties.Add("asset", msgBody.Asset); var size = eventMessage.GetBytes().Length; if (debug) { Console.WriteLine($"\t{DateTime.Now.ToLocalTime()}> Sending message: {count}, Size: {size}, Body: [{dataBuffer}]"); } else { Console.WriteLine($"\t{DateTime.Now.ToLocalTime()}> Sending message: {count}, Size: {size}"); } try { if (insights) { telemetryClient.GetMetric("SendMessage").TrackValue(1); telemetryClient.Context.Operation.Name = "Special Operation"; Metric sizeStats = telemetryClient.GetMetric("Special Operation Message Size"); sizeStats.TrackValue(size); } await moduleClient.SendEventAsync("temperatureOutput", eventMessage); } catch (Microsoft.Azure.Devices.Client.Exceptions.MessageTooLargeException exception) { Console.WriteLine(exception.Message); if (insights) { telemetryClient.GetMetric("MessageSizeExceeded").TrackValue(1); } } count++; } await Task.Delay(messageDelay, cts.Token); } if (messageCount < count) { Console.WriteLine($"Done sending {messageCount} messages"); } }
public async Task InvokeMethodOnModuleTest(ITransportSettings[] transportSettings) { // Arrange string deviceName = string.Format("moduleMethodTest-{0}", transportSettings.First().GetTransportType().ToString("g")); string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey"); IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString); RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString); ModuleClient receiver = null; string edgeDeviceConnectionString = ConfigHelper.TestConfig[Constants.ConfigKey.IotHubConnectionString]; Client.IotHubConnectionStringBuilder edgeHubConnectionStringBuilder = Client.IotHubConnectionStringBuilder.Create(edgeDeviceConnectionString); string edgeDeviceId = edgeHubConnectionStringBuilder.DeviceId; Device edgeDevice = await rm.GetDeviceAsync(edgeDeviceId); var request = new TestMethodRequest("Prop1", 10); var response = new TestMethodResponse("RespProp1", 20); TestMethodRequest receivedRequest = null; Task <MethodResponse> MethodHandler(MethodRequest methodRequest, object context) { receivedRequest = JsonConvert.DeserializeObject <TestMethodRequest>(methodRequest.DataAsJson); return(Task.FromResult( new MethodResponse( Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response)), 200))); } string receiverModuleName = "method-module"; (string deviceId, string deviceConnStr) = await RegistryManagerHelper.CreateDevice(deviceName, iotHubConnectionString, rm, true, false, edgeDevice.Scope); try { ServiceClient sender = ServiceClient.CreateFromConnectionString(iotHubConnectionString); string receiverModuleConnectionString = await RegistryManagerHelper.CreateModuleIfNotExists(rm, connectionStringBuilder.HostName, deviceId, receiverModuleName); receiver = ModuleClient.CreateFromConnectionString(receiverModuleConnectionString, transportSettings); await receiver.OpenAsync(); await receiver.SetMethodHandlerAsync("poke", MethodHandler, null); // Need longer sleep to ensure receiver is completely initialized await Task.Delay(TimeSpan.FromSeconds(10)); // Act CloudToDeviceMethodResult cloudToDeviceMethodResult = await sender.InvokeDeviceMethodAsync( deviceId, receiverModuleName, new CloudToDeviceMethod("poke").SetPayloadJson(JsonConvert.SerializeObject(request))); // Assert Assert.NotNull(cloudToDeviceMethodResult); Assert.NotNull(receivedRequest); Assert.Equal(receivedRequest.RequestProp1, request.RequestProp1); Assert.Equal(receivedRequest.RequestProp2, request.RequestProp2); Assert.Equal(200, cloudToDeviceMethodResult.Status); var receivedResponse = JsonConvert.DeserializeObject <TestMethodResponse>(cloudToDeviceMethodResult.GetPayloadAsJson()); Assert.NotNull(receivedResponse); Assert.Equal(receivedResponse.ResponseProp1, response.ResponseProp1); Assert.Equal(receivedResponse.ResponseProp2, response.ResponseProp2); } finally { await rm.CloseAsync(); if (receiver != null) { await receiver.CloseAsync(); } try { await RegistryManagerHelper.RemoveDevice(deviceId, rm); } catch (Exception) { // ignored } } // wait for the connection to be closed on the Edge side await Task.Delay(TimeSpan.FromSeconds(10)); }
public ValidateNumberOfMessagesSent(TestReporter testReporter, IMetricsScraper scraper, ModuleClient moduleClient) : base(testReporter, scraper, moduleClient) { }
/// <summary> /// Create client /// </summary> /// <param name="client"></param> internal ModuleClientAdapter(ModuleClient client) { _client = client ?? throw new ArgumentNullException(nameof(client)); }
public async Task ModulesClient_InvokeMethodOnModule() { if (!this.IsAsync) { // TODO: Tim: The module client doesn't appear to open a connection to iothub or start // listening for method invocations when this test is run in Sync mode. Not sure why though. // calls to track 1 library don't throw, but seem to silently fail return; } string testDeviceId = $"InvokeMethodDevice{GetRandom()}"; string testModuleId = $"InvokeMethodModule{GetRandom()}"; DeviceIdentity device = null; ModuleIdentity module = null; ModuleClient moduleClient = null; IotHubServiceClient serviceClient = GetClient(); try { // Create a device to house the modules device = (await serviceClient.Devices .CreateOrUpdateIdentityAsync( new DeviceIdentity { DeviceId = testDeviceId }) .ConfigureAwait(false)) .Value; // Create the module on the device module = (await serviceClient.Modules.CreateOrUpdateIdentityAsync( new ModuleIdentity { DeviceId = testDeviceId, ModuleId = testModuleId }).ConfigureAwait(false)).Value; // Method expectations string expectedMethodName = "someMethodToInvoke"; int expectedStatus = 222; object expectedRequestPayload = null; // Create module client instance to receive the method invocation string moduleClientConnectionString = $"HostName={GetHostName()};DeviceId={testDeviceId};ModuleId={testModuleId};SharedAccessKey={module.Authentication.SymmetricKey.PrimaryKey}"; moduleClient = ModuleClient.CreateFromConnectionString(moduleClientConnectionString, TransportType.Mqtt_Tcp_Only); // These two methods are part of our track 1 device client. When the test fixture runs when isAsync = true, // these methods work. When isAsync = false, these methods silently don't work. await moduleClient.OpenAsync().ConfigureAwait(false); await moduleClient.SetMethodHandlerAsync( expectedMethodName, (methodRequest, userContext) => { return(Task.FromResult(new MethodResponse(expectedStatus))); }, null).ConfigureAwait(false); // Invoke the method on the module CloudToDeviceMethodRequest methodRequest = new CloudToDeviceMethodRequest() { MethodName = expectedMethodName, Payload = expectedRequestPayload, ConnectTimeoutInSeconds = 5, ResponseTimeoutInSeconds = 5 }; var methodResponse = (await serviceClient.Modules.InvokeMethodAsync(testDeviceId, testModuleId, methodRequest).ConfigureAwait(false)).Value; Assert.AreEqual(expectedStatus, methodResponse.Status); } finally { if (moduleClient != null) { await moduleClient.CloseAsync().ConfigureAwait(false); } await CleanupAsync(serviceClient, device).ConfigureAwait(false); } }
// Tests_SRS_DEVICECLIENT_10_001: [** if `connectionString` is null, an `ArgumentNullException` shall be thrown. **]** public void ModuleClient_CreateFromConnectionString_NullConnectionString() { ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(null); }
/// <summary> /// Ctor for the class. /// </summary> public HubClient(ModuleClient edgeHubClient) { _edgeHubClient = edgeHubClient; }
public void ModuleClient_CreateFromConnectionString_WithNoModuleIdThrows() { ModuleClient.CreateFromConnectionString(ConnectionStringWithoutModuleId); }
private ModuleResponse CallSageExchange(string xmlForSageExchange) { ModuleClient sedClient = new ModuleClient(); return (ModuleResponse)sedClient.GetResponse(xmlForSageExchange); }