-
Notifications
You must be signed in to change notification settings - Fork 0
/
LockService.cs
196 lines (178 loc) · 7.35 KB
/
LockService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
namespace LockInitClient
{
public class DeviceMsg
{
public string deviceId { get; set; }
}
public class LockMsg
{
public bool lockState;
}
public class LockService
{
private Auth0.Windows.Auth0User user;
private HttpClient client;
private string serverBase;
private readonly string deviceRegistrationPath = "/api/device/register";
private readonly string deviceDeregistrationPath = "/api/device/deregister";
private readonly string listDevicePath = "/api/device/list";
private readonly string lockDevicePath = "/api/device/{0}/lock";
private readonly string unlockDevicePath = "/api/device/{0}/lock";
public LockService(Auth0.Windows.Auth0User user, string serverBase)
{
this.user = user;
this.client = new HttpClient();
this.client.DefaultRequestHeaders.Add("Authorization", "Bearer " + user.IdToken);
this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
this.serverBase = serverBase;
}
public void ListLocksAync(Action<bool, List<string>, string> callback)
{
client.GetAsync(GetUri(listDevicePath)).ContinueWith((requestTask) =>
{
if (IsSuccessful("ListLockAsync", requestTask))
{
HttpResponseMessage response = requestTask.Result;
if (response.IsSuccessStatusCode)
{
response.Content.ReadAsStringAsync().ContinueWith((readTask) =>
{
var result = Newtonsoft.Json.Linq.JObject.Parse(readTask.Result);
List<string> locks = (result["Locks"].ToObject<List<string>>());
callback(true, locks, response.StatusCode.ToString());
});
}
else
{
System.Diagnostics.Trace.TraceError("http failure status code: {0} {1}", response.StatusCode, response.ReasonPhrase);
callback(false, null, response.ReasonPhrase);
}
}
else
{
callback(false, null, requestTask.Exception.Message);
}
});
}
public void LockDeviceAsync(string lockId, bool lockStatus, Action<bool, string, string> callback)
{
var lockMsg = new LockMsg() { lockState = lockStatus };
var path = lockStatus ? string.Format(lockDevicePath, lockId) : string.Format(unlockDevicePath, lockId);
client.PutAsJsonAsync<LockMsg>(GetUri(path), lockMsg).ContinueWith((requestTask) =>
{
if (IsSuccessful("LockDeviceAsync", requestTask))
{
HttpResponseMessage response = requestTask.Result;
if (response.IsSuccessStatusCode)
{
response.Content.ReadAsStringAsync().ContinueWith((readTask) =>
{
var result = Newtonsoft.Json.Linq.JObject.Parse(readTask.Result);
string status = result["status"].ToObject<string>();
callback(true, status, response.StatusCode.ToString());
});
}
else
{
System.Diagnostics.Trace.TraceError("http failure status code: {0} {1}", response.StatusCode, response.ReasonPhrase);
callback(false, null, response.ReasonPhrase);
}
}
else
{
callback(false, null, requestTask.Exception.Message);
}
});
}
public void DeviceDeregistrationAsync(string deviceId, Action<bool, string> callback)
{
var msg = new DeviceMsg()
{
deviceId = deviceId
};
client.PostAsJsonAsync<DeviceMsg>(GetUri(deviceDeregistrationPath), msg).ContinueWith(taskresp =>
{
if (IsSuccessful("DeviceDegisterationAsync", taskresp))
{
HttpResponseMessage result = taskresp.Result;
if (result.IsSuccessStatusCode )
{
callback(true, null);
}
else
{
System.Diagnostics.Trace.TraceError("http failure status code: {0} {1}", result.StatusCode, result.ReasonPhrase);
callback(false, result.ReasonPhrase);
}
}
else
{
callback(false, taskresp.Exception.Message);
}
});
}
public void DeviceRegistrationAsync(string deviceId, Action<bool, byte[], string> callback)
{
var msg = new DeviceMsg()
{
deviceId = deviceId
};
client.PostAsJsonAsync<DeviceMsg>(GetUri(deviceRegistrationPath), msg).ContinueWith(async taskresp =>
{
if (IsSuccessful("PostAsJsonAsync", taskresp))
{
HttpResponseMessage result = taskresp.Result;
if (result.IsSuccessStatusCode)
{
string respContent = await result.Content.ReadAsStringAsync();
var resMsg = Newtonsoft.Json.Linq.JObject.Parse(respContent);
byte[] keyBytes = (resMsg["Key"].ToObject<List<Byte>>()).ToArray();
callback(true, keyBytes, null);
}
else
{
System.Diagnostics.Trace.TraceError("http failure status code: {0} {1}", result.StatusCode, result.ReasonPhrase);
callback(false, null, result.ReasonPhrase);
}
}
else
{
callback(false, null, taskresp.Exception.Message);
}
});
}
private string GetUri(string method)
{
return "http://" + serverBase + method;
}
private bool IsSuccessful(string method, Task<HttpResponseMessage> task)
{
if (task.IsCompleted && task.Status != TaskStatus.Faulted)
{
return true;
}
LogTaskError(method, task);
return false;
}
private void LogTaskError(string method, Task<HttpResponseMessage> taskresp)
{
if (taskresp.Exception != null)
{
System.Diagnostics.Trace.TraceError("failed on {0} {1}", method, taskresp.Exception.ToString());
}
else
{
System.Diagnostics.Trace.TraceError("failed on {0} faulted: {1} completed: {2}",
method, taskresp.IsFaulted, taskresp.IsCanceled);
}
}
}
}