Raspberry Piの環境構築は前回やったので、今回は何となくアプリ作成です。
ハードで動き続けるのでちゃんと動いているかわからないためHeatBeatをAzureStorageTableに1分おきに送信するプログラムを作ります。
VisualStudioの環境回りについては環境構築編を参考にしてください。
AzureStorageを利用するのでnugetでStorageクラスの取得が必要です。
PM> Install-Package WindowsAzure.Storage
1、まずはエンティティクラスを作成
internal class HeatbeatEntity:TableEntity { public HeatbeatEntity() { } public string message { get; set; } public string TimeStamp { get; set; } }
2、次にストレージアクセス、メッセージ送信のプログラムを作ります。
public CloudStorageAccount StorageAccount { get; private set; } public CloudTableClient TableClient { get; private set; } public clsAzureStorageContoroller(string storagename, string storagekey ) { StorageAccount = new CloudStorageAccount(new StorageCredentials(storagename, storagekey), useHttps: false); TableClient = StorageAccount.CreateCloudTableClient(); } public void doHeartbeat() { const string tableName = "HearBeatForIoT"; var table = TableClient.GetTableReference(tableName); // テーブル作成 var reesut = table.CreateIfNotExistsAsync(); var entity = new HeatbeatEntity() { PartitionKey = DateTime.Now.Ticks.ToString("D19"), RowKey = "HeatBeat", TimeStamp = DateTime.Now.ToString("yyyyMMdd hhmmss"), message = "working!!!" }; // テーブルストレージに追加 var operation = TableOperation.Insert(entity); var cloudTable = TableClient.GetTableReference(tableName); var resultexec = cloudTable.ExecuteAsync(operation); }
3、そしたらStartupTaskでストレージに1分おきにハートビートを送るようにする。
public sealed class StartupTask : IBackgroundTask { private string StorageName = "ストレージ名"; private string StorageKey = "ストレージキー"; public void Run(IBackgroundTaskInstance taskInstance) { clsAzureStorageContoroller asc = new clsAzureStorageContoroller(StorageName, StorageKey); while (true) { try { asc.doHeartbeat(); var temptime = DateTime.Now.AddSeconds(60); while (true) { if(temptime < DateTime.Now) { break; } } } catch { //todo break; } finally { //todo } } } }
System.Threading.ThreadがないのでSleepが使えないという罠にはまりました。
なんでないんだろう、Thread.Sleep、非同期前提なのかしら。
VisualStudioからBuildしますが、実行時はARMを選択するようにしてください。
組み込み用のBuildエンジンと解釈してますが、これでやらないとエラーになります。
とりあえず動いているかAzureStorageTableをみて確認します。
転送されていることを確認できました。
これでプログラムが動いているかどうかが判断できます。
次はセンサー系をいじりたいと思います。