async Task SendDataAsync(string connectionString) { var list = await CacheHelper.GetSimulatedSensorListFromCacheAsync(_cache); DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); if (deviceClient == null) { await FeedbackHelper.Channel.SendMessageAsync("Failed to connect to Azure IoT Hub.", MessageType.Info); return; } while (CacheHelper.IsInSendingDataState(_cache)) { await FeedbackHelper.Channel.SendMessageAsync("Sending Data...", MessageType.Info); foreach (SimulatedSensor sensor in list) { await IoTHubHelper.SendEvent(deviceClient, sensor); } await Task.Delay(TimeSpan.FromSeconds(ConfigHelper.Config.parameters.SimulatorTimer)); } await FeedbackHelper.Channel.SendMessageAsync("Sending data stopped.", MessageType.Info); }
static public async Task Do(CmdArguments args) { var twin = new Twin(); twin.ETag = "*"; twin.Set(args.KVPairs); var startTime = DateTime.UtcNow + TimeSpan.FromSeconds(args.StartOffsetInSeconds); var client = JobClient.CreateFromConnectionString(Settings.Default.ConnectionString); var jobId = args.JobId; if (string.IsNullOrEmpty(jobId)) { jobId = Guid.NewGuid().ToString(); } JobResponse job = await client.ScheduleTwinUpdateAsync( jobId, args.QueryCondition, twin, startTime, args.TimeoutInSeconds); Console.WriteLine($"{job.Type} job {job.JobId} scheduled"); await IoTHubHelper.WaitJob(client, job); }
static public async Task Do(CmdArguments args) { var client = JobClient.CreateFromConnectionString(Settings.Default.ConnectionString); var method = new CloudToDeviceMethod(args.Names.Single()); method.SetPayloadJson(args.Values.Single()); var startTime = DateTime.UtcNow + TimeSpan.FromSeconds(args.StartOffsetInSeconds); var jobId = args.JobId; if (string.IsNullOrEmpty(jobId)) { jobId = Guid.NewGuid().ToString(); } JobResponse job = await client.ScheduleDeviceMethodAsync( jobId, args.QueryCondition, method, startTime, args.TimeoutInSeconds); Console.WriteLine($"{job.Type} job {job.JobId} scheduled"); await IoTHubHelper.WaitJob(client, job); }
static public async Task Do(CmdArguments args) { var client = RegistryManager.CreateFromConnectionString(Settings.Default.ConnectionString); if (args.Ids != null) { await IoTHubHelper.QueryDevicesByIds(client, args.Ids); } else { await IoTHubHelper.QueryDevicesByCondition(client, args.QueryCondition ?? "select * from devices"); } }
public static async Task <Game> GetCurrentGameAsync() { try { Game CurrentGame = await IoTHubHelper.CurrentGameMethod(); return(CurrentGame); } catch (Exception ex) { throw ex; } }
static public async Task Do(CmdArguments args) { var client = RegistryManager.CreateFromConnectionString(Settings.Default.ConnectionString); var deviceId = args.Ids.Single(); var twin = new Twin(deviceId); twin.Set(args.KVPairs); twin = await client.UpdateTwinAsync(deviceId, twin, "*"); IoTHubHelper.OutputDevice(twin); Console.WriteLine("1 device updated"); }
private static void UpdateDeviceListFromIoTHub() { List <IDictionary <string, object> > devices = IoTHubHelper.ListDevices(100); if (devices != null) { foreach (IDictionary <string, object> device in devices) { AddToDeviceList(device); } // Clean up the list of devices removing devices that are no longer provisionned in IoT Hub devicesList.RemoveAll(device => devices.Find(item => item["guid"].ToString() == device.guid) == null); Global.globalSettings.DevicesListRefreshed = true; } }
public async void ThreadProc() { AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel(); try { IoTHubHelper iotHubHelper = new IoTHubHelper(_ConnectionString); await iotHubHelper.UpdateTwinDesiredProperty(_IoTDeviceId, _DeviceConfiguration); ProvisionApp._appLogger.Info("[IoT Hub Device] " + _Action + " success: DeviceId-" + _IoTDeviceId); operationTask.UpdateTaskBySuccess(_TaskId); } catch (Exception ex) { StringBuilder logMessage = new StringBuilder(); logMessage.AppendLine("[IoT Hub Device] " + _Action + " Failed: DeviceId-" + _IoTDeviceId); logMessage.AppendLine("\tMessage:" + JsonConvert.SerializeObject(this)); logMessage.AppendLine("\tException:" + ex.Message); ProvisionApp._appLogger.Error(logMessage); operationTask.UpdateTaskByFail(_TaskId, ex.Message); } }
static public async Task Do(CmdArguments args) { var client = RegistryManager.CreateFromConnectionString(Settings.Default.ConnectionString); foreach (var deviceId in args.Ids) { await client.AddDeviceAsync(new Device(deviceId)); Console.WriteLine($"{deviceId} added"); if (args.KVPairs != null) { var twin = new Twin(); twin.Set(args.KVPairs); await client.UpdateTwinAsync(deviceId, twin, "*"); } } await IoTHubHelper.QueryDevicesByIds(client, args.Ids); }
public async void ThreadProc() { AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel(); try { IoTHubHelper iotHubHelper = new IoTHubHelper(_ConnectionString); switch (_Action) { case "register iothub register": _AuthenticationType = _JsonMessage["Content"]["authenticationType"].ToString().ToLower(); if (_AuthenticationType == "key") { string IoTHubDeviceKey = _JsonMessage["Content"]["iothubDeviceKey"].ToString(); await iotHubHelper.RegisterDeviceByKey(_IoTDeviceId, IoTHubDeviceKey); } else { string CertificateThumbprint = _JsonMessage["Content"]["certificateThumbprint"].ToString(); await iotHubHelper.RegisterDeviceByCertThumbprint(_IoTDeviceId, CertificateThumbprint); } break; case "remove iothub register": await iotHubHelper.RemoveDevice(_IoTDeviceId); break; } ProvisionApp._appLogger.Info("[IoT Hub Device] " + _Action + " success: DeviceId-" + _IoTDeviceId); operationTask.UpdateTaskBySuccess(_TaskId); } catch (Exception ex) { StringBuilder logMessage = new StringBuilder(); logMessage.AppendLine("[IoT Hub Device] " + _Action + " Failed: DeviceId-" + _IoTDeviceId); logMessage.AppendLine("\tMessage:" + JsonConvert.SerializeObject(this)); logMessage.AppendLine("\tException:" + ex.Message); ProvisionApp._appLogger.Error(logMessage); operationTask.UpdateTaskByFail(_TaskId, ex.Message); } }
public async Task <ActionResult> Index(int seconds = 1) { try { var sent = await IoTHubHelper.SendDirectMethod(seconds); if (sent == 200) { ViewBag.Result = "Message sent! "; } else { ViewBag.Result = $"Error sending. {sent}"; } } catch (IotHubException ex) { ViewBag.Result = $"Exception sending. {ex.Message}"; Trace.TraceError(ex.Message); } return(View()); }
private void PingIoTHubTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (Global.globalSettings.RefreshDevicesList) { Global.globalSettings.RefreshDevicesList = false; Global.UpdateDeviceListFromIoTHub(); } if (Global.globalSettings.AddDevice) { Global.globalSettings.AddDevice = false; Global.globalSettings.DeviceAddedResult = IoTHubHelper.AddDevice(Global.globalSettings.NewDeviceName); Global.globalSettings.DeviceAdded = true; } if (Global.globalSettings.DeleteDevice) { Global.globalSettings.DeleteDevice = false; Global.globalSettings.DeviceDeletedResult = IoTHubHelper.DeleteDevice(Global.globalSettings.DeviceToDeleteName); Global.globalSettings.DeviceDeleted = true; } }
public async Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> events) { try { var now = DateTime.UtcNow; foreach (var eventData in events) { // We don't care about messages that are older than bufferTimeInterval if ((eventData.EnqueuedTimeUtc + bufferTimeInterval) >= now) { // Get message from the eventData body and convert JSON string into message object string eventBodyAsString = Encoding.UTF8.GetString(eventData.GetBytes()); // There can be several messages in one IList <IDictionary <string, object> > messagePayloads; try { // Attempt to deserialze event body as single JSON message messagePayloads = new List <IDictionary <string, object> > { JsonConvert.DeserializeObject <IDictionary <string, object> >(eventBodyAsString) }; } catch { // Not a single JSON message: attempt to deserialize as array of messages // Azure Stream Analytics Preview generates invalid JSON for some multi-values queries // Workaround: turn concatenated json objects (ivalid JSON) into array of json objects (valid JSON) if (eventBodyAsString.IndexOf("}{") >= 0) { eventBodyAsString = eventBodyAsString.Replace("}{", "},{"); } if (eventBodyAsString.IndexOf("}\r\n{") >= 0) { eventBodyAsString = eventBodyAsString.Replace("}\r\n{", "},{"); } if (!eventBodyAsString.EndsWith("]")) { eventBodyAsString = eventBodyAsString + "]"; } if (!eventBodyAsString.StartsWith("[")) { eventBodyAsString = "[" + eventBodyAsString.Substring(eventBodyAsString.IndexOf("{")); } messagePayloads = JsonConvert.DeserializeObject <IList <IDictionary <string, object> > >(eventBodyAsString); } var rnd = new Random(); foreach (var messagePayload in messagePayloads) { // Read time value if (messagePayload.ContainsKey("timecreated")) { messagePayload["time"] = messagePayload["timecreated"]; } if (messagePayload.ContainsKey("timearrived")) { messagePayload["time"] = messagePayload["timearrived"]; } // process an alert if (messagePayload.ContainsKey("alerttype") && messagePayload.ContainsKey("timecreated")) { Debug.Print("Alert message received!"); // If the IoTHub service client has not yet been created, go create it. if (IoTHub == null) { IoTHub = new IoTHubHelper(Microsoft.Azure.CloudConfigurationManager.GetSetting("Azure.IoT.IoTHub.ConnectionString")); } // Send alert to device if (IoTHub != null) { var alertMessage = JsonConvert.SerializeObject(messagePayload).ToString(); IoTHub.SendMessage(messagePayload["guid"].ToString(), alertMessage); } DateTime time = DateTime.Parse(messagePayload["timecreated"].ToString()); // find the nearest point lock (sortedDataBuffer) { int idx = SearchHelper.FindFirstIndexGreaterThanOrEqualTo(sortedDataBuffer, time); bool found = false; string alertType = messagePayload["alerttype"] as string; if (idx >= sortedDataBuffer.Values.Count) { idx = sortedDataBuffer.Values.Count - 1; } while (idx >= 0) { List <IDictionary <string, object> > dictList = sortedDataBuffer.Values[idx]; foreach (IDictionary <string, object> dict in dictList) { if ( (dict.ContainsKey("guid") && messagePayload.ContainsKey("guid") && messagePayload["guid"].ToString() == dict["guid"].ToString()) && (dict.ContainsKey("measurename") && messagePayload.ContainsKey("measurename") && messagePayload["measurename"].ToString() == dict["measurename"].ToString()) && (!messagePayload.ContainsKey("displayname") || dict.ContainsKey("displayname") && messagePayload["measurename"].ToString() == dict["measurename"].ToString()) ) { // fill anomaly message if (!messagePayload.ContainsKey("value")) { messagePayload["value"] = dict["value"]; } if (!messagePayload.ContainsKey("displayname") && dict.ContainsKey("displayname")) { messagePayload["displayname"] = dict["displayname"]; } if (!messagePayload.ContainsKey("time")) { messagePayload["time"] = messagePayload["timecreated"]; } found = true; break; } } if (found) { break; } idx--; } } } if (messagePayload.ContainsKey("guid")) { var guid = messagePayload["guid"].ToString(); double val = Convert.ToDouble(messagePayload["value"]); if (!MinMaxValue.ContainsKey(guid)) { MinMaxValue.Add(guid, new MinMax { min = val, max = val }); } MinMax tmp = MinMaxValue[messagePayload["guid"].ToString()]; if (tmp.min > val) { tmp.min = val; } if (tmp.max < val) { tmp.max = val; } } // We want to read the time value from the message itself. // If none is found we will use the enqueued time DateTime messageTimeStamp = new DateTime(); if (messagePayload.ContainsKey("time")) { messageTimeStamp = DateTime.Parse(messagePayload["time"].ToString()); //if (GenerateAnomalies && rnd.Next(100) >= 95) //{ // messagePayload.Add("alerttype", "testType"); // messagePayload.Add("dsplalert", "testAlert"); // messagePayload.Add("message", "Anomaly detected by Azure ML model."); // messagePayload.Add("timestart", messagePayload["time"]); // // correct value // if (rnd.Next(2) == 1) // messagePayload["value"] = MinMaxValue[messagePayload["guid"].ToString()].max * (1.01 + 0.05 * rnd.Next(100) / 100); // else // messagePayload["value"] = MinMaxValue[messagePayload["guid"].ToString()].min * (0.99 - 0.05 * rnd.Next(100) / 100); //} } else if (messagePayload.ContainsKey("timestart")) { messageTimeStamp = DateTime.Parse(messagePayload["timestart"].ToString()); } else { messageTimeStamp = eventData.EnqueuedTimeUtc; } // Build up the list of devices seen so far (in lieu of a formal device repository) // Also keep the last message received per device (not currently used in the sample) if (messagePayload.ContainsKey("guid") && !messagePayload.ContainsKey("valueAvg")) { string guid = messagePayload["guid"].ToString(); if (guid != null) { WebSocketEventProcessor.g_devices.TryAdd(guid, messagePayload); } } // Notify clients MyWebSocketHandler.SendToClients(messagePayload); // Buffer messages so we can resend them to clients that connect later // or when a client requests data for a different device // Lock to guard against concurrent reads from client resend lock (sortedDataBuffer) { if (!sortedDataBuffer.ContainsKey(messageTimeStamp)) { sortedDataBuffer.Add(messageTimeStamp, new List <IDictionary <string, object> >()); } sortedDataBuffer[messageTimeStamp].Add(messagePayload); } } } else { Debug.Print("Received old message timestamped:" + eventData.EnqueuedTimeUtc.ToString()); } } //Call checkpoint every minute if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(1)) { await context.CheckpointAsync(); lock (this) { this.checkpointStopWatch.Restart(); } // trim data buffer to keep only last 10 minutes of data lock (sortedDataBuffer) { DateTime oldDataPoint = now - bufferTimeInterval; // find the closest point int idx = SearchHelper.FindFirstIndexGreaterThanOrEqualTo(sortedDataBuffer, oldDataPoint); // trim while (idx > 0 && sortedDataBuffer.Count > 0 && sortedDataBuffer.Keys[0] <= oldDataPoint) { sortedDataBuffer.RemoveAt(0); } } } } catch (Exception e) { Trace.TraceError("Error processing events in EH {0}, partition {1}: {0}", context.EventHubPath, context.Lease.PartitionId, e.Message); } }
public void ThreadProc() { OperationTaskModel operationTask = new OperationTaskModel(); try { AzureSQLHelper.IoTHubModel iotHubModel = new AzureSQLHelper.IoTHubModel(); IoTHub iotHub = iotHubModel.GetById(_IoTHubReceiverMsg.content.iotHubId); string iotHubConnectionString = iotHub.IoTHubConnectionString; //IoTHub iotHub = new IoTHub(); //iotHub.Id = 1001; //iotHub.IoTHubName = "OPC UA Default"; //string iotHubConnectionString = "HostName=opcuademobox.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=2eHR7uKDmrajO6201NBfUlzGGLrIDi55A2URg0EZuCo="; IoTHubHelper iotHubHelper = new IoTHubHelper(iotHubConnectionString); string[] partitions = iotHubHelper.GetPartitions(); _Version = _IoTHubReceiverMsg.content.version; if (string.IsNullOrEmpty(_Version)) { _Version = _SrvFabricIoTHubReceiverTypeVersion; } _CompanyId = _IoTHubReceiverMsg.content.companyId.ToString(); if (_CompanyId == "0") { _CompanyId = iotHub.CompanyID.ToString(); } ProvisionApp._appLogger.Info(string.Format("Company ID: {0}, IoTHub ID: {1}, Version: {2}", _CompanyId, _IoTHubReceiverMsg.content.iotHubId, _Version)); switch (_IoTHubReceiverMsg.task) { case TaskName.IoTHubReceiver_Launch: if (iotHub.EnableMultipleReceiver) { for (int i = 0; i < partitions.Length; i++) { string label = i + "-" + partitions.Length; lanuchIoTHubReceiver(iotHub.CompanyID.ToString(), iotHub, partitions[i], label); ProvisionApp._appLogger.Info("[IoTHubReceiver] " + _IoTHubReceiverMsg.task + " success: CompanyId-" + _CompanyId + ", IoTHubReceiverName-" + iotHub.IoTHubName + ", Label-" + label); } } else { lanuchIoTHubReceiver(_CompanyId, iotHub, "ALL", "ALL"); ProvisionApp._appLogger.Info("[IoTHubReceiver] " + _IoTHubReceiverMsg.task + " success: CompanyId-" + _CompanyId + ", IoTHubReceiverName-" + iotHub.IoTHubName + ", Label-" + "ALL"); } break; case TaskName.IoTHubReceiver_Shutdown: // Shutdown All Partitions Processes (it maybe not running) for (int i = 0; i < partitions.Length; i++) { string label = i + "-" + partitions.Length; shutdownIoTHubReceiver(_CompanyId, iotHub, partitions[i], label); ProvisionApp._appLogger.Info("[IoTHubReceiver] " + _IoTHubReceiverMsg.task + " success: CompanyId-" + _CompanyId + ", IoTHubReceiverName-" + iotHub.IoTHubName + ", Label-" + label); } // Shutdown Non-Partition Process (it maybe not running) shutdownIoTHubReceiver(_CompanyId, iotHub, "ALL", "ALL"); ProvisionApp._appLogger.Info("[IoTHubReceiver] " + _IoTHubReceiverMsg.task + " success: CompanyId-" + _CompanyId + ", IoTHubReceiverName-" + iotHub.IoTHubName + ", Label-" + "ALL"); break; } operationTask.UpdateTaskBySuccess(_IoTHubReceiverMsg.taskId); } catch (Exception ex) { StringBuilder logMessage = new StringBuilder(); logMessage.AppendLine("[IoTHubReceiver] " + _IoTHubReceiverMsg.task + " Failed: CompanyId-" + _CompanyId + ", IoTHubId-" + _IoTHubReceiverMsg.content.iotHubId); logMessage.AppendLine("\tMessage:" + JsonConvert.SerializeObject(this)); logMessage.AppendLine("\tException:" + ex.Message); ProvisionApp._appLogger.Error(logMessage); operationTask.UpdateTaskByFail(_IoTHubReceiverMsg.taskId, ex.Message); } }
public async void ThreadProc() { AzureSQLHelper.EventRuleCatalogModel eventRuleModel = new AzureSQLHelper.EventRuleCatalogModel(); List <Application> appList = eventRuleModel.GetActionApplicationById(_MessageCatalogId); try { foreach (var app in appList) { string applicationTargetType = app.TargetType.ToLower(); try { WebHelper webHelper = new WebHelper(); JObject outputTemplate = new JObject(); switch (applicationTargetType) { case "webapi": outputTemplate = ParsingOutputTemplate(app.MessageTemplate); switch (app.Method.ToLower()) { case "post-x-www": string postData = ConvertJObjectToQueryString(outputTemplate); switch (app.AuthType.ToLower()) { case "none": webHelper.PostContent(app.ServiceURL, postData); break; case "basic auth": webHelper.PostContent(app.ServiceURL, postData, app.AuthID, app.AuthPW); break; } break; case "post-multi": NameValueCollection formData = new NameValueCollection(); foreach (var elem in outputTemplate) { formData.Add(elem.Key, outputTemplate[elem.Key].ToString()); } switch (app.AuthType.ToLower()) { case "none": webHelper.PostMultipartContent(app.ServiceURL, formData); break; case "basic auth": break; } break; case "post-json": switch (app.AuthType.ToLower()) { case "none": webHelper.PostJsonContent(app.ServiceURL, JsonConvert.SerializeObject(outputTemplate)); break; case "basic auth": webHelper.PostJsonContent(app.ServiceURL, JsonConvert.SerializeObject(outputTemplate), app.AuthID, app.AuthPW); break; } break; } break; case "dashboard": try { webHelper.PostContent(EventActionApp._rtEventFeedInURL, JsonConvert.SerializeObject(_FullAlarmMessage)); } catch (Exception ex) { EventActionApp._appLogger.Error("RTEventFeedInURL Exception: " + ex.Message); } break; case "iot device": int deviceId = int.Parse(app.ServiceURL); AzureSQLHelper.IoTDeviceModel iotDeviceModel = new AzureSQLHelper.IoTDeviceModel(); IoTDevice iotDevice = iotDeviceModel.GetById(deviceId); try { IoTHubHelper iotHubHelper = new IoTHubHelper(iotDevice.IoTHub.IoTHubConnectionString); outputTemplate = ParsingOutputTemplate(app.MessageTemplate); iotHubHelper.SendC2DMessage(iotDevice.IoTHubDeviceID, outputTemplate); } catch (Exception ex) { EventActionApp._appLogger.Error("C2D Message Error, DeviceID:" + iotDevice.Id + "; Exception:" + ex.Message); } break; case "email": break; case "sms": break; } } catch (Exception ex) { EventActionApp._appLogger.Error("EventAction Exception: " + ex.Message + ";" + app.Name + "; (id:" + app.Id + ") failed: "); continue; } } } catch (Exception ex) { StringBuilder logMessage = new StringBuilder(); logMessage.AppendLine("EventAction Task Exception: " + ex.Message); logMessage.AppendLine("EventAction Task Message: " + Convert.ToString(_FullAlarmMessage)); EventActionApp._appLogger.Error(logMessage); } }