<?php

class TemperatureDevice {
    protected $produceUrl = 'http://yun.eefield.com/coop/api/';
    protected $userName = '18610012796';
    protected $pwd = '123456';
    protected $login = false;

    /**
     *获取单个设备数据
     *
     * @author wst
     * @date   2021/6/8 18:03
     * @deviceId 设备id 多个用英文逗号隔开
     */
    public function getDevice($deviceId){
        $token = $this->getToken();
        try{
            if (empty($token)) {
               throw new Exception('token获取失败');
            }else{
                $data = curl_post($this->produceUrl . 'device/intimeData.htm', ['accessToken' => $token
                    ,"snaddrs"=>$deviceId]);
                $data = json_decode($data, true);
                if ($data['code'] == 0) {
                    $r = [
                        'success' => true,
                        'msg' => '操作成功',
                        'list' => $data['data']
                    ];
                }else {
                    throw new Exception($data['msg']);

                }
            }
            return $r;
        }catch (Exception $e){
              $r = [
                  'success'=>false,
                  'msg'=>$e->getMessage(),
              ];
            return $r;

        }

    }
    /**
     * 获取所有设备的基本信息
     *
     * @author wst
     * @date   2021/6/8 17:50
     */
    public function getDeviceList() {
        $token = $this->getToken();
        try{
            if (empty($token)) {
                throw new Exception('token获取失败');
            }
            else {
                $data = curl_post($this->produceUrl . 'device/list.htm', ['accessToken' => $token]);
                $data = json_decode($data, true);
                if ($data['code'] == 0) {
                    $r = [
                        'success' => true,
                        'msg' => '操作成功',
                        'list' => $data['data']
                    ];
                }
                else {
                    throw new Exception($data['msg']);
                }
            }
            return $r;
        }catch (Exception $e){
            $r = [
                'success'=>false,
                'msg'=>$e->getMessage(),
            ];
            return $r;
        }

    }
    public function getToken() {
        $cookie = cache('temperature_token');
        //\think\facade\Cache::delete('aqg_cookie');
        if (empty($cookie) || $cookie == 'false') {
            $url = $this->produceUrl . 'token.htm';
            $data = curl_post($url, ['user' => $this->userName, 'psw' => md5($this->pwd)]);
            $data = json_decode($data, true);
            if ($data['code'] == 0) {
                $cookie = $data['accessToken'];
                cache('temperature_token', $data['accessToken'], 604800);
            }
            else {
                $cookie = false;

            }
        }
        return $cookie;
    }
}