// Async method to send simulated telemetry // ident : identification / number of the sensor to identify the place of teh car // enter : 1 the car is entered, 0 the car exited public async Task <string> SendSensorDeviceToCloudMessagesAsync(string ident, string enter) { // Create JSON message body with SensorDeviceObject SensorDevice sensor = new SensorDevice(ident, enter); string res = ""; var messageString = JsonConvert.SerializeObject(sensor); var message = new Message(Encoding.ASCII.GetBytes(messageString)); // Add a custom application property to the message. // An IoT hub can filter on these properties without access to the message body. //message.Properties.Add("sensorXXXX", zzzz); // Send the sensor message try { string deviceid = getAzureDeviceId(s_connectionString); await serviceClient.SendAsync(deviceid, message); } catch (Exception ex) { res = ex.Message; } return(res); }
// Manage message received message from Azure in Form side private void my_NetClient_DataReceived(object sender, NetClientReceivedEventArgs e) { switch (e.datatype) { case "sensor": SensorDevice sensor = (SensorDevice)e.data; // Insert Data in database sensor.insertSensorData(db); break; case "camera": CameraDevice camera = (CameraDevice)e.data; // Display Image received in form (test) ImageProcessing image = new ImageProcessing(); // tosee //pictureBoxDB.Image = image.convertToImage(camera.photo); if (camera.cleanResult == "") { // Request to Azure the OCR and process json result image.getOcrFromAzure(camera.photo, OcrKey); // Display trace log in textbox //rtbLastErrorTest.Text += "\n" + getDateTimeNow() + " : Received Camera, Hard Result : " + image.hardResult + "\n\nClean Result : " + image.cleanResult; // Insert Image and Ocr text in database camera.insertCameraData(db, image.data, image.hardResult, image.cleanResult); } else { // Display trace log in textbox //rtbLastErrorTest.Text += "\n" + getDateTimeNow() + " : Received Camera, Hard Result : " + camera.hardResult + "\n\nClean Result : " + camera.cleanResult; // Insert Image and Ocr text in database camera.insertCameraData(db, camera.photo, camera.hardResult, camera.cleanResult); } break; } }
public void requestAndLoadConfig() { // Request parameters devices to get messages from storage if route used in azure // Sensors string req = "select * from azure where type = 'STORAGE' and ident = 'SENSOR'"; ArrayList results = db.Select(req); storageSensorDevice = new SensorDevice[results.Count]; for (int l = 0; l < results.Count; l++) { System.Collections.Specialized.NameValueCollection row = (NameValueCollection)results[l]; // To Get Message from Storage container (for Sensors) storageSensorDevice[l] = new SensorDevice("", ""); // Readed messages sent using OnNetClientReceived to form storageSensorDevice[l].OnNetClientReceived += new SensorDevice.NetClientReceived(netClient_DataReceived); // Read message from Storage Account, buth the specific Blob container : TFMinis devicetfminicontainer storageSensorDevice[l].readMessagesFromBlob(row["ConnectionString"], row["EventsEndpoint"]); if (l == 0) { SensorDeviceClient = new AzureDeviceClient(row["ConnectionString"], row["EventsEndpoint"], OcrKey); } } // OCR Computer Vision Key req = "select * from azure where type = 'VISION' and ident = 'OCR'"; results = db.Select(req); for (int l = 0; l < 1; l++) { NameValueCollection row = (NameValueCollection)results[l]; OcrKey = row["PrimaryKey"]; } // Cameras req = "select * from azure where type = 'STORAGE' and ident = 'CAMERA'"; results = db.Select(req); storageCameraDevice = new CameraDevice[results.Count]; for (int l = 0; l < results.Count; l++) { NameValueCollection row = (NameValueCollection)results[l]; // To Get Message from Storage container (for Sensors) storageCameraDevice[l] = new CameraDevice("", ""); // Readed messages sent using OnNetClientReceived to form storageCameraDevice[l].OnNetClientReceived += new CameraDevice.NetClientReceived(netClient_DataReceived); // Read message from Storage Account, buth the specific Blob container : TFMinis devicecameracontainer storageCameraDevice[l].readMessagesFromBlob(row["ConnectionString"], row["EventsEndpoint"], OcrKey); // Create a Test camera device for c# program if (l == 0) { CameraDeviceClient = new AzureDeviceClient(row["ConnectionString"], row["EventsEndpoint"], OcrKey); } } // Update parking price for all cars inside req = "select c.*, DATEDIFF(minute, c.enter_dt, '" + getBaseDateTimeNow() + "') as diff from cars c where c.enter = '1' and c.paid != '1' order by c.id desc"; results = db.Select(req); for (int i = 0; i < results.Count; i++) { NameValueCollection row = (NameValueCollection)results[i]; string id = row["id"]; // Update the previous entry price p = new price(db, row["number"], row["diff"]); req = "update cars set payment_dt='" + getBaseDateTimeNow() + "', payment_mns='" + row["diff"] + "', payment_dhm='" + p.dayshoursmns + "', amount='" + p.amount + "' where id = '" + id + "'"; db.noSelect(req); } }
public void insertSensorData(string ident, string enter) { SensorDevice sensor = new SensorDevice(ident, enter); sensor.insertSensorData(db); }
// Read Blob message from container public async void listenBlob(string blobcontainername, string connectionString) { int maxloop = 1; for (int l = 0; l < maxloop; l++) { CloudStorageAccount storageAccount = null; CloudBlobContainer cloudBlobContainer = null; // Check whether the connection string can be parsed. if (CloudStorageAccount.TryParse(connectionString, out storageAccount)) { try { // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account. CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); cloudBlobContainer = cloudBlobClient.GetContainerReference(blobcontainername); // Set the permissions so the blobs are public. BlobContainerPermissions permissions = new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }; await cloudBlobContainer.SetPermissionsAsync(permissions); // List the blobs in the container. BlobContinuationToken blobContinuationToken = null; do { var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken); // Get the value of the continuation token returned by the listing call. blobContinuationToken = results.ContinuationToken; foreach (IListBlobItem item in results.Results) { try { var textFromAzureBlob = (new WebClient()).DownloadString(item.Uri); // Match device TFMini event MatchCollection match = Regex.Matches(textFromAzureBlob, @"""type""\:""([^""]*)"",""ident""\:""([^""]*)"",""enter""\:""([^""]*)""}", RegexOptions.IgnoreCase); for (int i = 0; i < match.Count; i++) { string data = "{" + match[i].Value; SensorDevice sensor = JsonConvert.DeserializeObject <SensorDevice>(data); // Send Sensor Object to Form Side OnNetClientReceived(this, new NetClientReceivedEventArgs(sensor.type, sensor)); // Wait a little to dont lock Form GUI await Task.Delay(1000); } // delete item file ((ICloudBlob)item).Delete(); } catch (Exception ex) { string error = ex.Message; } } } while (blobContinuationToken != null); // Loop while the continuation token is not null. } catch (StorageException) { // Error returned from the service: {0}", ex.Message } finally { // After reading delete content if (cloudBlobContainer != null) { // Not good delete the container itself //await cloudBlobContainer.DeleteIfExistsAsync(); // Delete all items // Parallel.ForEach(cloudBlobContainer.ListBlobs(useFlatBlobListing: true), x => ((CloudBlob)x).Delete()); } } } //await Task.Delay(1000); } }