OnenetApi.php 18.5 KB
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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
<?php
/**
 * Created by PhpStorm.
 * User: billy
 * Date: 30/08/2017
 * Time: 10:18 AM
 */
namespace App\Modules\Onenet;

use Illuminate\Support\Facades\Log;

class OnenetApi
{
    protected $_raw_response = ''; // 服务端返回的原始数据

    protected $_http_code = 200;

    protected $_error_no = 0;

    protected $_error = '';

    protected static $_ALLOW_METHODS = array(
        'GET',
        'PUT',
        'POST',
        'DELETE'
    );

    private function raw_response()
    {
        return $this->_raw_response;
    }

    private function error()
    {
        return $this->_error;
    }

    private function error_no()
    {
        return $this->_error_no;
    }

    private function http_code()
    {
        return $this->_http_code;
    }

    private function curApiKey()
    {
        return config('constants.heCloud.api_key');
    }

    // 设备相关API
    public function device($id)
    {
        if (empty($id)) {
            return FALSE;
        }

        $api = "/devices/{$id}";

        return $this->_call($api);
    }

    public function device_list($page = 1, $page_size = 30, $key_word = NULL, $tag = NULL, $is_online = NULL, $is_private = NULL, $device_ids = NULL)
    {
        $params = array(
            'page' => is_numeric($page) ? $page : 1,
            'per_page' => is_numeric($page_size) ? $page_size : 30
        );

        if (! is_null($key_word)) {
            $params['key_words'] = $key_word;
        }

        if (! is_null($tag)) {
            $params['tag'] = $tag;
        }

        if (! is_null($is_private)) {
            $params['private'] = $is_private;
        }

        if (! is_null($device_ids)) {
            $params['device_id'] = $device_ids;
        }

        $params_str = http_build_query($params);

        // 2015-10-29 http build query会将true转义为1,API只接受true/false的布尔串
        if (! is_null($is_online)) {
            $params_str = $params_str . '&online=true';
        }

        $api = '/devices?' . $params_str;

        return $this->_call($api);
    }

    public function device_add($device)
    {
        $api = '/devices';
        return $this->_call($api, 'POST', $device);
    }

    public function device_edit($id, $device)
    {
        if (empty($id)) {
            return FALSE;
        }

        $api = "/devices/{$id}";
        return $this->_call($api, 'PUT', $device);
    }

    public function device_delete($id)
    {
        if (empty($id)) {
            return FALSE;
        }

        $api = "/devices/{$id}";
        return $this->_call($api, 'DELETE');
    }

    // 数据流相关API
    public function datastream($device_id, $datastream_id)
    {
        if (empty($device_id) || empty($datastream_id)) {
            return FALSE;
        }

        // 对空格进行转义
        // $datastream_id = str_replace(" ","+", $datastream_id);
        $datastream_id = rawurlencode($datastream_id); // 空格处理的修改 2015-08-25

        $api = "/devices/{$device_id}/datastreams/{$datastream_id}";
        return $this->_call($api);
    }

    /**
     * 获取某个设备下面的数据流
     */
    public function datastream_of_dev($device_id)
    {
        if (empty($device_id)) {
            return FALSE;
        }

        $api = "/devices/{$device_id}/datastreams";
        return $this->_call($api);
    }

    public function datastream_add($device_id, $datastream)
    {
        if (empty($device_id) || empty($datastream)) {
            return FALSE;
        }

        $api = "/devices/{$device_id}/datastreams";
        return $this->_call($api, 'POST', $datastream);
    }

    public function datastream_edit($device_id, $datastream_id, $datastream)
    {
        if (empty($device_id) || empty($datastream_id) || empty($datastream)) {
            return FALSE;
        }

        $api = "/devices/{$device_id}/datastreams/{$datastream_id}";
        return $this->_call($api, 'PUT', $datastream);
    }

    public function datastream_delete($device_id, $datastream_id)
    {
        if (is_null($device_id) || is_null($datastream_id)) {
            return FALSE;
        }

        $api = "/devices/{$device_id}/datastreams/{$datastream_id}";
        return $this->_call($api, 'DELETE');
    }

    /**
     * $datas:
     * array(
     * timestamp => data
     * )
     */
    // 数据点操作
    public function datapoint_add($device_id, $datastream_id, $datas)
    {
        if (empty($datas)) {
            return TRUE;
        }

        if (empty($device_id) || empty($datastream_id)) {
            return FALSE;
        }
        $datastream_data = array();
        foreach ($datas as $t => $v) {
            $t = date('Y-m-d\TH:i:s', $t);
            if (empty($t)) {
                continue;
            }
            $datastream_data[] = array(
                'at' => $t,
                'value' => $v
            );
        }
        $api_data = array(
            'datastreams' => array(
                array(
                    'id' => $datastream_id,
                    'datapoints' => $datastream_data
                )
            )
        );
        $api = "/devices/{$device_id}/datapoints";
        return $this->_call($api, 'POST', $api_data);
    }

    /**
     * 多个datastream一次添加
     * $datas:
     * array(
     * 'datastream_id' => array(
     * 'timestamp' => data
     * )
     * )
     */
    public function datapoint_multi_add($device_id, $datas)
    {
        if (empty($datas)) {
            return TRUE;
        }

        if (empty($device_id)) {
            return FALSE;
        }

        $api_data = array(
            'datastreams' => array()
        );

        foreach ($datas as $datastream_id => $d) {
            $datastream_data = array();
            foreach ($d as $t => $v) {
                $t = date('Y-m-d\TH:i:s', $t);
                if (empty($t)) {
                    continue;
                }
                $datastream_data[] = array(
                    'at' => $t,
                    'value' => $v
                );
            }

            if (empty($datastream_data)) {
                continue;
            }

            $api_data['datastreams'][] = array(
                'id' => $datastream_id,
                'datapoints' => $datastream_data
            );
        }
        $api = "/devices/{$device_id}/datapoints";

        return $this->_call($api, 'POST', $api_data);
    }

    /**
     * 2015-04-13 OneNet更新后,将不再支持以下参数:
     * sort_time 可选,指定时按时间倒序排,最新时间在前面
     * page 指定页码, 可选
     * per_page 指定每页输出数据点个数,可选, 默认300,最多1000
     *
     * 当前datastream更像是数据流的操作。废弃之前 datapoint_list, datapoint_multi_list 方法
     */
    public function datapoint_get($device_id, $datastream_id, $start_time = NULL, $end_time = NULL, $limit = NULL, $cursor = NULL)
    {
        if (empty($device_id) || empty($datastream_id)) {
            return FALSE;
        }

        return $this->datapoint_multi_get($device_id, $start_time, $end_time, $limit, $cursor, $datastream_id);
    }

    public function datapoint_multi_get($device_id, $start_time = NULL, $end_time = NULL, $limit = NULL, $cursor = NULL, $datastream_ids = array())
    {
        if (empty($device_id)) {
            return FALSE;
        }

        $params = array();

        if (! empty($datastream_ids)) {
            if (is_array($datastream_ids)) {
                $datastream_ids = implode(',', $datastream_ids);
            }

            $params['datastream_id'] = $datastream_ids;
        }

        if (! empty($start_time)) {
            $start_time = date('Y-m-d\TH:i:s', strtotime($start_time));
            $params['start'] = $start_time;
        }
        if (! empty($end_time)) {
            $end_time = date('Y-m-d\TH:i:s', strtotime($end_time));
            $params['end'] = $end_time;
        }
        if (! empty($limit)) {
            $params['limit'] = $limit;
        }
        if (! empty($cursor)) {
            $params['cursor'] = $cursor;
        }

        $params_str = http_build_query($params);

        $api = "/devices/{$device_id}/datapoints?" . $params_str;

        return $this->_call($api);
    }

    public function datapoint_delete($device_id, $datastream_id, $start_time = NULL, $end_time = NULL)
    {
        if (empty($device_id) || empty($datastream_id)) {
            return FALSE;
        }
        $startduration = $this->_startendtime_to_startduration($start_time, $end_time);
        $params = array(
            'start' => $startduration[0],
            'duration' => $startduration[1],
            'datastream_id' => $datastream_id
        );

        $params_str = http_build_query($params);
        $api = "/devices/{$device_id}/datapoints?" . $params_str;
        return $this->_call($api, 'DELETE');
    }

    public function datapoint_multi_delete($device_id, $start_time = NULL, $end_time = NULL)
    {
        if (empty($device_id)) {
            return FALSE;
        }
        $startduration = $this->_startendtime_to_startduration($start_time, $end_time);
        $params = array(
            'start' => $startduration[0],
            'duration' => $startduration[1]
        );

        $params_str = http_build_query($params);
        $api = "/devices/{$device_id}/datapoints?" . $params_str;
        return $this->_call($api, 'DELETE');
    }

    // 触发器操作
    public function trigger($trigger_id)
    {
        if (empty($trigger_id)) {
            return FALSE;
        }

        $api = "/triggers/{$trigger_id}";
        return $this->_call($api);
    }

    public function trigger_list($page = NULL, $per_page = NULL, $title = NULL)
    {
        $params = array(
            'page' => is_numeric($page) ? $page : 1,
            'per_page' => is_numeric($per_page) ? $per_page : 30
        );

        if (! is_null($title)) {
            $params['title'] = $title;
        }

        $params_str = http_build_query($params);

        $api = "/triggers?" . $params_str;
        return $this->_call($api);
    }

    public function trigger_add($trigger)
    {
        if (empty($trigger)) {
            return FALSE;
        }
        $api = "/triggers";

        return $this->_call($api, 'POST', $trigger);
    }

    public function trigger_edit($trigger_id, $trigger)
    {
        if (empty($trigger_id) || empty($trigger)) {
            return FALSE;
        }
        $api = "/triggers/{$trigger_id}";
        return $this->_call($api, 'PUT', $trigger);
    }

    public function trigger_delete($trigger_id)
    {
        if (empty($trigger_id)) {
            return FALSE;
        }
        $api = "/triggers/{$trigger_id}";

        return $this->_call($api, 'DELETE');
    }

    /**
     * 获取APIKey
     *
     * @return array 当指定$dev_id 和|或 $key时,返回满足条件的key信息;当两个参数都不指定时,返回用户的所用key
     */
    public function api_key($dev_id = NULL, $key = NULL, $page = NULL, $per_page = NULL)
    {
        $params = array();
        if (! is_null($dev_id)) {
            $params['device_id'] = $dev_id;
        }
        if (! is_null($key)) {
            $params['key'] = $key;
        }
        if (! is_null($page)) {
            $params['page'] = $page;
        }
        if (! is_null($per_page)) {
            $params['per_page'] = $per_page;
        }

        $api = "/keys";
        $par_str = http_build_query($params);
        if (! empty($par_str)) {
            $api .= "?" . $par_str;
        }

        $ret = $this->_call($api, 'GET');
        if ($ret === TRUE) {
            // 数据是空的
            $ret = array();
        }

        return $ret;
    }

    // 暂时只提供到dev_id级别权限, 必须是master_key 才行
    public function api_key_add($dev_id, $title)
    {
        if (empty($title) || empty($dev_id)) {
            return FALSE;
        }

        $data = array(
            'title' => $title,
            'permissions' => array(
                array(
                    'resources' => array(
                        array(
                            'dev_id' => $dev_id
                        )
                    )
                )
            )
        );

        $api = "/keys";

        return $this->_call($api, 'POST', $data);
    }

    // 修改key
    public function api_key_edit($key, $title, $resource = null)
    {
        if (empty($key)) {
            return false;
        }

        $data = array(
            'title' => $title,
            'permissions' => array(
                array(
                    'resources' => $resource
                )
            )
        );

        $api = "/keys/{$key}";
        $res = $this->_call($api, 'PUT', $data);

        return $res;
    }

    // 删除指定的api_key
    public function api_key_delete($api_key)
    {
        if (empty($api_key)) {
            return FALSE;
        }
        $api_key = urlencode($api_key);
        $api = "/keys/{$api_key}";

        $res = $this->_call($api, 'DELETE');

        return $res;
    }

    public function request_log($device_id, $start_time)
    {
        if (empty($device_id)) {
            return FALSE;
        }
        if (empty($start_time)) {
            $start_time = date('Y-m-d\TH:i:s', time() - 3600); // 向后查询1个小时
        } else {
            $start_time = date('Y-m-d\TH:i:s', $start_time + 5); // 随后就有开始时间了
        }

        $api = "/logs/{$device_id}?t_start=" . $start_time;

        return $this->_call($api);
    }

    public function send_data_to_edp($device_id, $qos, $timeout, $sms)
    {
        if (empty($device_id)) {
            return FALSE;
        }
        $api = "/cmds?device_id={$device_id}&qos={$qos}&timeout={$timeout}";
        return $this->_call($api, 'POST', $sms);
    }

    public function send_data_to_mqtt($topic, $sms)
    {

        $api = "/mqtt?topic={$topic}";
        return $this->_call($api, 'POST', $sms);
    }

    public function get_dev_status($cmd_uuid)
    {
        if (empty($cmd_uuid)) {
            return FALSE;
        }

        $api = "/cmds/{$cmd_uuid}";
        $res = $this->_call($api, 'GET');
        return $res;
    }

    public function get_dev_status_resp($cmd_uuid)
    {
        if (empty($cmd_uuid)) {
            return FALSE;
        }

        $api = "/cmds/{$cmd_uuid}/resp";
        $res = $this->_call($api, 'GET');
        return $res;
    }

    // 开始时间和结束时间转换为接口形式
    protected function _startendtime_to_startduration($start_time, $end_time)
    {
        $duration = 3600;
        $start = 0;
        if (! empty($start_time)) {
            $start = strtotime($start_time) + 1; // 不返回这个时间的点
            $start_time = date('Y-m-d\TH:i:s', $start);
        }

        if (! empty($end_time)) {
            $duration = $end_time - $start_time;
        }
        return array(
            $start_time,
            $duration
        );
    }

    // 权限key操作,具体还需要修改
    protected function _paddingUrl($url)
    {
        if (empty($url)) {
            return $url;
        }

        if ($url[0] != '/') {
            $url = '/' . $url;
        }

        return config('constants.heCloud.api_url') . $url;
    }

    // 返回直接的ret数据
    protected function _rawcall($url, $method = 'GET', $data = array(), $headers = array())
    {
        $url = $this->_paddingUrl($url);

        $this->_error_no = 0;
        $this->_error = NULL;
        $default_headers = array(
            "api-key: {$this->curApiKey()}"
        );

        if (empty($this->curApiKey())) {
            $default_headers = array();
        }

        if (empty($url)) {
            $this->_http_code = 500;
            return FALSE;
        }

        if (! in_array($method, self::$_ALLOW_METHODS)) {
            $this->_http_code = 500;
            return FALSE;
        }

        //如果data不是想要的,直接设置为NULL
        if (is_null($data) || (is_array($data) && count($data) == 0) || $data === FALSE) {
            $data = NULL;
        } else {
            if (is_array($data)) {
                $data = json_encode($data);
            }
        }
        Log::info('[HeCloudRepository _rawcall] request:'.$data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
        if ($method != 'GET') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        // header set
        if (! empty($headers)) {
            $headers = array_merge($default_headers, $headers);
        } else {
            $headers = $default_headers;
        }

        // 有可能default_header为空
        if (! empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        $this->_beforeCall($ch, $url, $method, $data);
        $ret = curl_exec($ch);
        $this->_afterCall($ch, $url, $method, $data, $ret);

        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (! empty($http_code)) {
            $this->_http_code = $http_code;
        }

        curl_close($ch);
        $this->_raw_response = $ret;
        Log::info('[HeCloudRepository _rawcall] response:'.$ret);
        return $ret;
    }

    protected function _call($url, $method = 'GET', $data = array(), $headers = array())
    {
        $ret = $this->_rawcall($url, $method, $data, $headers);
        $ori_ret = $ret;

        $ret = @json_decode($ret, TRUE);

//        if (empty($ret)) {
//            $ret = FALSE;
//        } else {
//            if (empty($ret['errno'])) {
//                if (isset($ret['data'])) {
//                    $ret = $ret['data'];
//                } else {
//                    $ret = TRUE;
//                }
//            } else {
//                // 产生了错误了
//                /**
//                 * {
//                 * errno:0 //0表示成功
//                 * error:''//错误信息
//                 * data:{} //如果有数据放在这里边
//                 * }
//                 */
//                $this->_error_no = $ret['errno'];
//                if (! empty($ret['error'])) {
//                    $this->_error = $ret['error'];
//                }
//
//                $ret = FALSE;
//            }
//        }
//        $this->_afterDecode($url, $method, $data, $ori_ret, $ret);

        return $ret;
    }

    protected function _beforeCall($ch, $url, $method, $data)
    {}

    protected function _afterCall($ch, $url, $method, $data, $ret)
    {}

    protected function _afterDecode($url, $method, $data, $ori_ret, $ret)
    {}
}