Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

HttpRequestSensor.php 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: robin
  5. * Date: 11/24/15
  6. * Time: 12:49 AM
  7. */
  8. namespace App\Http\Business\Sensors;
  9. use App\Http\DBO\SensorsValueDbo;
  10. use GuzzleHttp\Client;
  11. use GuzzleHttp\Exception\ClientException;
  12. use GuzzleHttp\Exception\RequestException;
  13. use Luticate\Utils\LuLog;
  14. class HttpRequestSensor extends AbstractSensor
  15. {
  16. /**
  17. * {
  18. * "Url": "https://example.com/sensor"
  19. * "Method": "GET|POST|PUT|...",
  20. * "Options": {
  21. * },
  22. * "Mapping": {
  23. * "Values": {
  24. * "ON": 1,
  25. * "OFF": 0
  26. * },
  27. * "ValuesDefault": 0
  28. * }
  29. * }
  30. *
  31. */
  32. protected function map($value, $mapping)
  33. {
  34. $default = isset($mapping["ValuesDefault"]) ? $mapping["ValuesDefault"] : $value;
  35. $values = isset($mapping["Values"]) ? $mapping["Values"] : array();
  36. if (isset($values[$value]))
  37. {
  38. return $values[$value];
  39. }
  40. else
  41. {
  42. return $default;
  43. }
  44. }
  45. /**
  46. * @return SensorsValueDbo
  47. */
  48. public function getValue()
  49. {
  50. $data = $this->_sensor->getData();
  51. $url = $data["Url"];
  52. $method = isset($data["Method"]) ? $data["Method"] : "GET";
  53. $options = isset($data["Options"]) ? $data["Options"] : array();
  54. $client = new Client();
  55. try {
  56. $response = $client->request($method, $url, $options);
  57. } catch (ClientException $e) {
  58. $response = $e->getResponse();
  59. if (!is_null($response)) {
  60. LuLog::log($response->getBody());
  61. }
  62. LuLog::log($e);
  63. abort(500, "Failed to execute request (client)");
  64. } catch (RequestException $e) {
  65. $response = $e->getResponse();
  66. if (!is_null($response)) {
  67. LuLog::log($response->getBody());
  68. }
  69. LuLog::log($e);
  70. abort(500, "Failed to execute request (request)");
  71. } catch (\Exception $e) {
  72. LuLog::log($e);
  73. abort(500, "Failed to execute request (unknown)");
  74. }
  75. if ($response->getStatusCode() != 200)
  76. {
  77. abort(500, "Failed to execute request (" . $response->getStatusCode() . ")");
  78. }
  79. $mapping = isset($data["Mapping"]) ? $data["Mapping"] : array();
  80. $value = new SensorsValueDbo();
  81. $value->setValue($this->map((string) $response->getBody(), $mapping));
  82. return $value;
  83. }
  84. }