/// <summary>
/// Gets a command
/// </summary>
/// <param name="device">Device data of the device that is getting a command</param>
/// <param name="onlyUnprocessed">Get commands with empty status only</param>
/// <returns>Command data structure or null if there are no pending commands</returns>
/// <remarks>
/// This method returns all the commands that are waiting at the server since last GetCommand call. It returns immediately, regardless if there are commands to execute or not.
/// </remarks>
public DeviceCommand GetCommand(Device device, bool onlyUnprocessed = true)
{
if (CommandQueue.Count != 0)
{
return (DeviceCommand)CommandQueue.Dequeue();
}
string TimeString = UriExtensions.EscapeDataString(LastTimeStamp);
string Url = CloudUrl + DeviceCommand + device.id.ToString() + PollCommandName + TimeString + "&waitTimeout=0";
byte[] bts = null;
WebResponse resp = MakeRequest(Url, null, GetMethod, device.id.ToString(), device.key);
if (resp.ContentType.IndexOf(ContentType) >= 0)
{
if (resp.ContentLength > 0)
{
using (Stream rs = resp.GetResponseStream())
{
bts = new byte[(int)rs.Length];
rs.Read(bts, 0, bts.Length);
rs.Close();
}
}
}
resp.Close();
if (bts != null)
{
JsonFormatter js = new JsonFormatter();
object o = js.FromJson(bts, typeof(DeviceCommand));
DeviceCommand dc = o as DeviceCommand;
if (dc != null && (!onlyUnprocessed || StringExtensions.IsNullOrEmpty(dc.status)))
{
return dc;
}
ArrayList al = o as ArrayList;
if (al != null)
{
if (al.Count == 0) return null;
for (int x = 0; x < al.Count; ++x)
{
dc = (DeviceCommand)al[x];
if (!onlyUnprocessed || StringExtensions.IsNullOrEmpty(dc.status))
{
CommandQueue.Enqueue(dc);
}
}
DeviceCommand ldc = (DeviceCommand)al[al.Count - 1];
LastTimeStamp = ldc.timestamp;
return CommandQueue.Count == 0 ? null : (DeviceCommand)CommandQueue.Dequeue();
}
}
return null;
}