1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- <?php
- /**
- * Created by PhpStorm.
- * User: robin
- * Date: 11/24/15
- * Time: 12:49 AM
- */
-
- namespace App\Http\Business\Sensors;
-
- use App\Http\DBO\SensorsValueDbo;
- use GuzzleHttp\Client;
- use GuzzleHttp\Exception\ClientException;
- use GuzzleHttp\Exception\RequestException;
- use Luticate\Utils\LuLog;
-
- class HttpRequestSensor extends AbstractSensor
- {
- /**
- * {
- * "Url": "https://example.com/sensor"
- * "Method": "GET|POST|PUT|...",
- * "Options": {
- * },
- * "Mapping": {
- * "Values": {
- * "ON": 1,
- * "OFF": 0
- * },
- * "ValuesDefault": 0
- * }
- * }
- *
- */
- protected function map($value, $mapping)
- {
- $default = isset($mapping["ValuesDefault"]) ? $mapping["ValuesDefault"] : $value;
-
- $values = isset($mapping["Values"]) ? $mapping["Values"] : array();
- if (isset($values[$value]))
- {
- return $values[$value];
- }
- else
- {
- return $default;
- }
- }
-
- /**
- * @return SensorsValueDbo
- */
- public function getValue()
- {
- $data = $this->_sensor->getData();
- $url = $data["Url"];
- $method = isset($data["Method"]) ? $data["Method"] : "GET";
- $options = isset($data["Options"]) ? $data["Options"] : array();
-
- $client = new Client();
-
- try {
- $response = $client->request($method, $url, $options);
- } catch (ClientException $e) {
- $response = $e->getResponse();
- if (!is_null($response)) {
- LuLog::log($response->getBody());
- }
- LuLog::log($e);
- abort(500, "Failed to execute request (client)");
- } catch (RequestException $e) {
- $response = $e->getResponse();
- if (!is_null($response)) {
- LuLog::log($response->getBody());
- }
- LuLog::log($e);
- abort(500, "Failed to execute request (request)");
- } catch (\Exception $e) {
- LuLog::log($e);
- abort(500, "Failed to execute request (unknown)");
- }
-
- if ($response->getStatusCode() != 200)
- {
- abort(500, "Failed to execute request (" . $response->getStatusCode() . ")");
- }
-
- $mapping = isset($data["Mapping"]) ? $data["Mapping"] : array();
-
- $value = new SensorsValueDbo();
- $value->setValue($this->map((string) $response->getBody(), $mapping));
-
- return $value;
- }
- }
|