PageRenderTime 46ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Server/DeviceHive.API/Controllers/DeviceCommandPollController.cs

https://github.com/oryol/devicehive-.net
C# | 59 lines | 39 code | 7 blank | 13 comment | 4 complexity | 4a13053f0cdae1d84f1dae83bec53c29 MD5 | raw file
Possible License(s): MIT
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Web.Http;
  7. using DeviceHive.API.Business;
  8. using DeviceHive.API.Filters;
  9. using DeviceHive.API.Mapping;
  10. using DeviceHive.Data.Model;
  11. using Newtonsoft.Json.Linq;
  12. using Ninject;
  13. namespace DeviceHive.API.Controllers
  14. {
  15. /// <resource cref="DeviceCommand" />
  16. public class DeviceCommandPollController : BaseController
  17. {
  18. private ObjectWaiter<DeviceCommand> _commandWaiter;
  19. private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(30);
  20. public DeviceCommandPollController(ObjectWaiter<DeviceCommand> commandWaiter)
  21. {
  22. _commandWaiter = commandWaiter;
  23. }
  24. /// <name>poll</name>
  25. /// <summary>
  26. /// <para>Polls new device commands.</para>
  27. /// <para>This method returns all device commands that were created after specified timestamp.</para>
  28. /// <para>In the case when no commands were found, the method blocks until new command is received.
  29. /// The blocking period is limited (currently 30 seconds), and the server returns empty response if no commands are received.
  30. /// In this case, to continue polling, the client should repeat the call with the same timestamp value.
  31. /// </para>
  32. /// </summary>
  33. /// <param name="deviceGuid">Device unique identifier.</param>
  34. /// <param name="timestamp">Timestamp of the last received command (UTC). If not specified, the server's timestamp is taken instead.</param>
  35. /// <returns cref="DeviceCommand">If successful, this method returns array of <see cref="DeviceCommand"/> resources in the response body.</returns>
  36. [AuthorizeDeviceOrUser]
  37. public JArray Get(Guid deviceGuid, DateTime? timestamp = null)
  38. {
  39. EnsureDeviceAccess(deviceGuid);
  40. var device = DataContext.Device.Get(deviceGuid);
  41. if (device == null || !IsNetworkAccessible(device.NetworkID))
  42. ThrowHttpResponse(HttpStatusCode.NotFound, "Device not found!");
  43. var start = timestamp != null ? timestamp.Value.AddTicks(10) : DateTime.UtcNow;
  44. var result = _commandWaiter.WaitForObjects(device.ID, () => DataContext.DeviceCommand.GetByDevice(device.ID, start, null), _timeout);
  45. return new JArray(result.Select(n => Mapper.Map(n)));
  46. }
  47. private IJsonMapper<DeviceCommand> Mapper
  48. {
  49. get { return GetMapper<DeviceCommand>(); }
  50. }
  51. }
  52. }