├── LICENSE ├── README.md ├── authorize.php ├── dueros.php ├── gate.php ├── hass.php ├── server.php └── token.php /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 小度音箱的homeassistant网关 2 | 3 | Fork From https://github.com/Deschanel/DuerSmartHome.git 4 | 5 | 增加长期访问令牌支持 6 | 7 | Add Long-Lived Access Tokens Support 8 | 9 | # 本文为Oauth2.0搭建过程 10 | 11 | 搭建网站 12 | 13 | 下载代码 14 | 15 | 把我github上的代码放到根目录 16 | 17 | 然后在网站根目录输入以下命令: 18 | 19 | 20 | ``` 21 | $ git clone https://github.com/bshaffer/oauth2-server-php.git -b master 22 | ``` 23 | 24 | 修改文件 25 | 26 | 修改serverDuerOS.php中的dbname、host、username和password! 27 | 28 | 修改homeassistant_conf.php中的地址和密码! 29 | 30 | 数据库操作 31 | 32 | 默认数据库已经建好且默认编码为utf8! 33 | 34 | 然后执行以下语句! 35 | 36 | ``` 37 | CREATE TABLE oauth_clients ( 38 | client_id VARCHAR(80) NOT NULL, 39 | client_secret VARCHAR(80), 40 | redirect_uri VARCHAR(2000), 41 | grant_types VARCHAR(80), 42 | scope VARCHAR(4000), 43 | user_id VARCHAR(80), 44 | PRIMARY KEY (client_id) 45 | ); 46 | 47 | CREATE TABLE oauth_access_tokens ( 48 | access_token VARCHAR(40) NOT NULL, 49 | client_id VARCHAR(80) NOT NULL, 50 | user_id VARCHAR(80), 51 | expires TIMESTAMP NOT NULL, 52 | scope VARCHAR(4000), 53 | PRIMARY KEY (access_token) 54 | ); 55 | 56 | CREATE TABLE oauth_authorization_codes ( 57 | authorization_code VARCHAR(40) NOT NULL, 58 | client_id VARCHAR(80) NOT NULL, 59 | user_id VARCHAR(80), 60 | redirect_uri VARCHAR(2000), 61 | expires TIMESTAMP NOT NULL, 62 | scope VARCHAR(4000), 63 | id_token VARCHAR(1000), 64 | PRIMARY KEY (authorization_code) 65 | ); 66 | 67 | CREATE TABLE oauth_refresh_tokens ( 68 | refresh_token VARCHAR(40) NOT NULL, 69 | client_id VARCHAR(80) NOT NULL, 70 | user_id VARCHAR(80), 71 | expires TIMESTAMP NOT NULL, 72 | scope VARCHAR(4000), 73 | PRIMARY KEY (refresh_token) 74 | ); 75 | 76 | CREATE TABLE oauth_users ( 77 | username VARCHAR(80), 78 | password VARCHAR(80), 79 | first_name VARCHAR(80), 80 | last_name VARCHAR(80), 81 | email VARCHAR(80), 82 | email_verified BOOLEAN, 83 | scope VARCHAR(4000), 84 | PRIMARY KEY (username) 85 | ); 86 | 87 | CREATE TABLE oauth_scopes ( 88 | scope VARCHAR(80) NOT NULL, 89 | is_default BOOLEAN, 90 | PRIMARY KEY (scope) 91 | ); 92 | 93 | CREATE TABLE oauth_jwt ( 94 | client_id VARCHAR(80) NOT NULL, 95 | subject VARCHAR(80), 96 | public_key VARCHAR(2000) NOT NULL 97 | ); 98 | ``` 99 | 100 | 然后插入数据! 101 | 102 | ``` 103 | insert into oauth_clients (client_id, client_secret, redirect_uri) VALUES ("your clientid", "your secret", "your callback address"); 104 | ``` 105 | 106 | 智能家居技能填写 107 | 108 | 授权地址 109 | 110 | 就是给予duer授权码的地址,也就是authorize.php地址 111 | 112 | - Client_Id 113 | 114 | 不解释 115 | 116 | - Scope 117 | 118 | 如果有的话,如实填写 119 | 120 | - Token地址 121 | 122 | 就是duerOS使用授权码获取token的地址,也就是token.php地址 123 | 124 | - 请求方式 125 | 126 | 按照你的需求选择,Oauth2.0标准是post方法 127 | 128 | - ClientSecret 129 | 130 | 不解释 131 | 132 | 设备云信息的WebService 133 | 134 | 根据智能家居协议写的网关地址,也就是gate.php地址 135 | 136 | 授权 137 | 138 | 授权时可以看到一个很丑的页面,就是authorize.php里的form表单,可以自己修改漂亮一点,加上逻辑验证等! 139 | 140 | 看到json数据中有login success就说明好了! 141 | 142 | 说明 143 | 144 | dueros.php为与hass连接的文件,目前只完成了状态查看和控制简单动作,可自行开发,参见智能家居技能的协议! 145 | 146 | # DuerSmartHome 147 | This project is based on DuerOS & HomeAssistant. 148 | 注意看里面的注释 149 | applianceId是你Hass里面的Entity 150 | ,教程地址https://xiaozhuo1314.github.io/ 151 | -------------------------------------------------------------------------------- /authorize.php: -------------------------------------------------------------------------------- 1 | query['redirect_uri']; 8 | $temp = substr($m,0,strpos($m,"?")); 9 | $request->query['redirect_uri']= $temp; 10 | 11 | // validate the authorize request 12 | if (!$server->validateAuthorizeRequest($request, $response)) { 13 | $response->send(); 14 | die; 15 | } 16 | // display an authorization form 17 | if (empty($_POST)) { 18 | exit(' 19 |
20 |
21 | 22 | 23 |
'); 24 | } 25 | 26 | // print the authorization code if the user has authorized your client 27 | $is_authorized = ($_POST['authorized'] === 'yes'); 28 | $server->handleAuthorizeRequest($request, $response, $is_authorized); 29 | if ($is_authorized) { 30 | // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client 31 | $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5); 32 | #exit("SUCCESS! Authorization Code: $code"); 33 | } 34 | $response->send(); 35 | -------------------------------------------------------------------------------- /dueros.php: -------------------------------------------------------------------------------- 1 | obj = $obj; 8 | $this->devices = $devices; 9 | $this->hassURL = $hassURL; 10 | $this->hassPASS = $hassPASS; 11 | } 12 | 13 | //获得messageID 14 | public function getMessageID(){ 15 | $chars = md5(uniqid(mt_rand(), true)); 16 | $uuid = substr($chars,0,8) . '-'; 17 | $uuid .= substr($chars,8,4) . '-'; 18 | $uuid .= substr($chars,12,4) . '-'; 19 | $uuid .= substr($chars,16,4) . '-'; 20 | $uuid .= substr($chars,20,12); 21 | return $uuid; 22 | } 23 | 24 | //设备发现 25 | public function discovery(){ 26 | $header = array( 27 | "namespace" => "DuerOS.ConnectedHome.Discovery", 28 | "name" => "DiscoverAppliancesResponse", 29 | "messageId " => $this->getMessageID(), 30 | "payloadVersion" => "1" 31 | ); 32 | return json_encode(array("header" => $header, "payload" => $this->devices)); 33 | } 34 | 35 | //设备控制 36 | public function control(){ 37 | $payload = array(); 38 | $applianceId=$this->obj->payload->appliance->applianceId; 39 | $action = ''; 40 | $additionalApplianceDetails = $this->object2array($this->obj->payload->appliance->additionalApplianceDetails); 41 | $name = substr( $this->obj->header->name, 0, -7); 42 | $deviceType = substr( $applianceId, 0, stripos($applianceId,".") ); 43 | switch($name){ 44 | case 'TurnOn': 45 | $action = 'turn_on'; 46 | $payload["entity_id"] = $applianceId; 47 | break; 48 | case 'TurnOff': 49 | $action='turn_off'; 50 | $payload["entity_id"] = $applianceId; 51 | break; 52 | case 'TimingTurnOn': 53 | $nowTime = time(); 54 | $actionTime = $this->obj->payload->timestamp->value; 55 | sleep(int($actionTime) - int($nowTime)); 56 | $action='turn_on'; 57 | $payload["entity_id"] = $applianceId; 58 | break; 59 | case 'TimingTurnOff': 60 | $nowTime = time(); 61 | $actionTime = $this->obj->payload->timestamp->value; 62 | sleep( int($actionTime) - int($nowTime) ); 63 | $action='turn_off'; 64 | $payload["entity_id"] = $applianceId; 65 | break; 66 | case 'Pause': 67 | //$action = 68 | break; 69 | case 'Continue': 70 | //$action = 71 | break; 72 | case 'SetBrightnessPercentage': 73 | //$privious = $this->priviousState(); 74 | if(!empty($additionalApplianceDetails["setBrightnessPercentage"]) && !empty($this->obj->payload->brightness->value)){ 75 | $detail = $additionalApplianceDetails["setBrightnessPercentage"]; 76 | $payload[$detail] = $this->obj->payload->brightness->value; 77 | } 78 | $payload["entity_id"] = $applianceId; 79 | $action = 'turn_on'; 80 | break; 81 | case 'IncrementBrightnessPercentage': 82 | //$privious = $this->priviousState(); 83 | //$action='brightness_up'; 84 | break; 85 | case 'DecrementBrightnessPercentage': 86 | //$privious = $this->priviousState(); 87 | //$action='brightness_down'; 88 | break; 89 | case 'SetColor': 90 | if(!empty($additionalApplianceDetails["setColor"]) && !empty($this->obj->payload->color)){ 91 | $detail = $additionalApplianceDetails["setColor"]; 92 | $payload[$detail] = $this->HSVtoRGB( $this->object2array($this->obj->payload->color) ); 93 | } 94 | $payload["entity_id"] = $applianceId; 95 | $action='turn_on'; 96 | break; 97 | case 'IncrementTemperature': 98 | //$action='temperature_up'; 99 | break; 100 | case 'IncrementTemperature': 101 | //$action='temperature_up'; 102 | break; 103 | //more 104 | default: 105 | break; 106 | } 107 | if(!empty($action) && !empty($deviceType)){ 108 | return $this->response($deviceType, $action, $payload, "services"); 109 | }else{ 110 | return false; 111 | } 112 | } 113 | 114 | //查询状态 115 | public function status(){ 116 | $payload = array(); 117 | $applianceId=$this->obj->payload->appliance->applianceId; 118 | $action = ''; 119 | $additionalApplianceDetails = $this->object2array($this->obj->payload->appliance->additionalApplianceDetails); 120 | $name = substr( $this->obj->header->name, 3, -7); 121 | $deviceType = ""; //substr( $applianceId, 0, stripos($applianceId,".") ); 122 | $action = ""; 123 | $payload = $applianceId; //初始化payload 124 | switch($name){ 125 | case "GetAirQualityIndex": 126 | break; 127 | case "GetAirPM25": 128 | break; 129 | case "GetAirPM10": 130 | break; 131 | case "GetCO2Quantity": 132 | break; 133 | case "GetHumidity": 134 | break; 135 | case "GetTemperatureReading": 136 | break; 137 | case "GetTargetTemperature": 138 | break; 139 | case "GetRunningTime": 140 | break; 141 | case "GetTimeLeft": 142 | break; 143 | case "GetRunningStatus": 144 | break; 145 | case "GetElectricityCapacity": 146 | break; 147 | case "GetWaterQuality": 148 | break; 149 | default: 150 | break; 151 | } 152 | return $this->response($deviceType, $action, $payload, "states"); 153 | } 154 | 155 | //与hass传输 156 | public function response($deviceType, $action, $payload, $callName){ 157 | if($callName == "services"){ 158 | // $http_url = $this->hassURL."/api/".$callName."/".$deviceType."/".$action."?api_password=".$this->hassPASS; 159 | // error_log($http_url); 160 | // $ch = curl_init($http_url); 161 | // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 162 | // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 163 | // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 164 | // curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($payload)); 165 | // curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); 166 | // curl_setopt($ch, CURLOPT_HEADER, 0); 167 | // curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: '.strlen(json_encode($payload)))); 168 | // $result = curl_exec($ch); 169 | // if(curl_errno($ch)){ 170 | // print curl_error($ch); 171 | // } 172 | // curl_close($ch); 173 | //----------- 174 | //支持Long-Lived Access Tokens 175 | $opts = array( 176 | 'http' => array( 177 | 'method' => "POST", 178 | 'header' => "Content-Type: application/json\r\n" . "Authorization: Bearer " . $this->hassPASS . "\r\n", 179 | 'content' => json_encode($payload) 180 | ) 181 | ); 182 | $context = stream_context_create($opts); 183 | $http_url = $this->hassURL . "/api/" . $callName . "/" . $deviceType . "/" . $action; 184 | $result = file_get_contents($http_url, false, $context); 185 | //-------- 186 | }elseif($callName == "states") { 187 | // $http_url = $this->hassURL."/api/".$callName."/".$payload."?api_password=".$this->hassPASS; 188 | // error_log($http_url); 189 | // $ch = curl_init($http_url); 190 | // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 191 | // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 192 | // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 193 | // curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); 194 | // curl_setopt($ch, CURLOPT_HEADER, 0); 195 | // //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: '.strlen($payload))); 196 | // $result = curl_exec($ch); 197 | // $result = json_decode($result, true); 198 | // if(curl_errno($ch)){ 199 | // print curl_error($ch); 200 | // } 201 | // curl_close($ch); 202 | //----------- 203 | //支持Long-Lived Access Tokens 204 | $opts = array( 205 | "http" => array( 206 | "method" => "GET", 207 | "header" => "Content-Type: application/json\r\n" . "Authorization: Bearer " . $this->hassPASS . "\r\n" 208 | ) 209 | ); 210 | $context = stream_context_create($opts); 211 | $http_url = $this->hassURL . "/api/" . $callName . "/" . $payload; 212 | $result = file_get_contents($http_url, false, $context); 213 | //-------- 214 | } 215 | return $result; 216 | } 217 | 218 | //如名字 219 | public function object2array($object) { 220 | $array = array(); //避免提示变量不存在 221 | if (is_object($object)) { 222 | foreach ($object as $key => $value) { 223 | $array[$key] = $value; 224 | } 225 | }else { 226 | $array = $object; 227 | } 228 | return $array; 229 | } 230 | //如名字 231 | //公式:https://en.wikipedia.org/wiki/HSL_and_HSV 232 | public function HSVtoRGB(array $hsv){ 233 | $keys = array_keys($hsv); 234 | $H = $hsv[$keys[0]]; 235 | $S = $hsv[$keys[1]]; 236 | $V = $hsv[$keys[2]]; 237 | $Hi = floor($H/60); 238 | $f = $H/60.0 - $Hi; 239 | $p = $V*(1-$S); 240 | $q = $V*(1-$S*$f); 241 | $t = $V*(1-$S*(1-$f)); 242 | if($S === 0){ 243 | return array(255*$V, 255*$V, 255*$V); 244 | } 245 | switch ($Hi){ 246 | case 0: 247 | $color = array(255*$V, 255*$t, 255*$p); 248 | break; 249 | case 1: 250 | $color = array(255*$q, 255*$V, 255*$p); 251 | break; 252 | case 2: 253 | $color = array(255*$p, 255*$V, 255*$t); 254 | break; 255 | case 3: 256 | $color = array(255*$p, 255*$q, 255*$V); 257 | break; 258 | case 4: 259 | $color = array(255*$t, 255*$p, 255*$V); 260 | break; 261 | case 5: 262 | $color = array(255*$V, 255*$p, 255*$q); 263 | break; 264 | case 6: 265 | $color = array(255*$V, 255*$t, 255*$p); 266 | break; 267 | } 268 | return $color; 269 | } 270 | // private function HSVtoRGB(array $hsv) { 271 | // $keys = array_keys($hsv); 272 | // $H = $hsv[$keys[0]]; 273 | // $S = $hsv[$keys[1]]; 274 | // $V = $hsv[$keys[2]]; 275 | // //1 276 | // $H *= 6; 277 | // //2 278 | // $I = floor($H); 279 | // $F = $H - $I; 280 | // //3 281 | // $M = $V * (1 - $S); 282 | // $N = $V * (1 - $S * $F); 283 | // $K = $V * (1 - $S * (1 - $F)); 284 | // //4 285 | // switch ($I) { 286 | // case 0: 287 | // list($R,$G,$B) = array($V,$K,$M); 288 | // break; 289 | // case 1: 290 | // list($R,$G,$B) = array($N,$V,$M); 291 | // break; 292 | // case 2: 293 | // list($R,$G,$B) = array($M,$V,$K); 294 | // break; 295 | // case 3: 296 | // list($R,$G,$B) = array($M,$N,$V); 297 | // break; 298 | // case 4: 299 | // list($R,$G,$B) = array($K,$M,$V); 300 | // break; 301 | // case 5: 302 | // case 6: //for when $H=1 is given 303 | // list($R,$G,$B) = array($V,$M,$N); 304 | // break; 305 | // } 306 | // return array(255*$R, 255*$G, 255*$B); 307 | // } 308 | } 309 | -------------------------------------------------------------------------------- /gate.php: -------------------------------------------------------------------------------- 1 | discovery(); 7 | } 8 | 9 | //设备控制 10 | function Hcontrol($o, $d){ 11 | //echo "a"; 12 | $result = $d->control(); 13 | $name = substr( $o->header->name, 0, -7); 14 | $response_name = $name.'Confirmation'; 15 | $header = array( 16 | "namespace" => "DuerOS.ConnectedHome.Control", 17 | "name" => $response_name, 18 | "messageId " => $d->getMessageID(), 19 | "payloadVersion" => "1" 20 | ); 21 | if($result !== false){ 22 | switch($o->header->name){ 23 | case 'TurnOnRequest': 24 | $payload = array("attributes" => array()); 25 | break; 26 | case 'TimingTurnOnRequest': 27 | $payload = array("attributes" => array()); 28 | break; 29 | case 'TurnOffRequest': 30 | $payload = array("attributes" => array()); 31 | break; 32 | case 'TimingTurnOffRequest': 33 | $payload = array("attributes" => array()); 34 | break; 35 | case 'PauseRequest': 36 | $payload = array("attributes" => array()); 37 | break; 38 | case 'ContinueRequest': 39 | $payload = array("attributes" => array()); 40 | break; 41 | case 'SetBrightnessPercentageRequest': 42 | $payload = array("previousState" => array("brightness" => array("value" => "null")), "brightness" => array("value" => $obj->payload->brightness->value), "attributes" => array()); 43 | break; 44 | case 'SetColorRequest': 45 | $payload = array("achievedState" => array("color" => $d->object2array($o->payload->color)), "attributes" => array()); 46 | break; 47 | //more 48 | default: 49 | $payload = array(); 50 | break; 51 | } 52 | }else{ 53 | return 'hahaha'; 54 | } 55 | return json_encode(array("header" => $header, "payload" => $payload)); 56 | } 57 | 58 | //状态查询 59 | function Hstatus($o, $d){ 60 | $result = $d->status(); 61 | $name = substr( $o->header->name, 0, -7); 62 | $response_name = $name.'Response'; 63 | $header = array( 64 | "namespace" => "DuerOS.ConnectedHome.Query", 65 | "name" => $response_name, 66 | "messageId " => $d->getMessageID(), 67 | "payloadVersion" => "1" 68 | ); 69 | if($result){ 70 | switch($o->header->name) { 71 | case 'GetHumidityRequest': 72 | $payload = array( "humidity"=>array( "value" => (float)($result["state"]/100) ) ); 73 | break; 74 | case "GetTemperatureReadingRequest": 75 | $payload = array( "temperatureReading"=>array( "value" => (float)$result["state"], "scale" => "CELSIUS" )); 76 | break; 77 | case "GetTargetTemperatureRequest": 78 | break; 79 | case "GetRunningTimeRequest": 80 | break; 81 | case "GetTimeLeftRequest": 82 | break; 83 | case "GetRunningStatusRequest": 84 | break; 85 | case "GetElectricityCapacityRequest": 86 | break; 87 | case "GetWaterQualityRequest": 88 | break; 89 | case "GetAirQualityIndexRequest": 90 | break; 91 | case "GetAirPM25Request": 92 | break; 93 | case "GetAirPM10Request": 94 | break; 95 | case "GetCO2QuantityRequest": 96 | break; 97 | default: 98 | // code... 99 | break; 100 | } 101 | }else{ 102 | return "hehehe"; 103 | } 104 | return json_encode(array("header" => $header, "payload" => $payload)); 105 | } 106 | 107 | //获得dueros的请求 108 | $poststr = file_get_contents("php://input"); 109 | $obj = json_decode($poststr); 110 | $duer = new dueros($obj, DEVICES, URL, PASS); 111 | switch($obj->header->namespace){ 112 | case 'DuerOS.ConnectedHome.Discovery': 113 | $resultStr = Hdiscovery($duer, DEVICES); 114 | break; 115 | case 'DuerOS.ConnectedHome.Control': 116 | //echo "lala"; 117 | $resultStr = Hcontrol($obj, $duer); 118 | break; 119 | case 'DuerOS.ConnectedHome.Query': 120 | $resultStr = Hstatus($obj, $duer); 121 | break; 122 | default: 123 | $resultStr='Nothing return,there is an error~!!'; 124 | } 125 | error_log('-------'); 126 | error_log('----get-request---'); 127 | error_log($poststr); 128 | error_log('----reseponse---'); 129 | error_log($resultStr); 130 | echo($resultStr); 131 | -------------------------------------------------------------------------------- /hass.php: -------------------------------------------------------------------------------- 1 | array( 7 | array( 8 | "actions" => array("turnOn", "timingTurnOn", "turnOff", "timingTurnOff"), 9 | "applianceTypes" => array("LIGHT"), 10 | "additionalApplianceDetails" => array(), 11 | "applianceId" => "light.sonoff", 12 | "friendlyDescription" => "LightDeviceId", 13 | "friendlyName" => "卧室的灯", 14 | "isReachable" => true, 15 | "manufacturerName" => "Nodemcu", 16 | "modelName" => "fancyLight", 17 | "version" => "1.0" 18 | ), 19 | array( 20 | "actions" => array("turnOn", "timingTurnOn", "turnOff", "timingTurnOff"), 21 | "applianceTypes" => array("HUMIDIFIER"), 22 | "additionalApplianceDetails" => array(), 23 | "applianceId" => "switch.pump", 24 | "friendlyDescription" => "浇水", 25 | "friendlyName" => "植物浇水器", 26 | "isReachable" => true, 27 | "manufacturerName" => "broadlink", 28 | "modelName" => "植物浇水器", 29 | "version" => "1.0" 30 | ), 31 | array( 32 | "actions" => array("turnOn", "timingTurnOn", "turnOff", "timingTurnOff"), 33 | "applianceTypes" => array("LIGHT"), 34 | "additionalApplianceDetails" => array(), 35 | "applianceId" => "switch.light", 36 | "friendlyDescription" => "补光", 37 | "friendlyName" => "植物补光器", 38 | "isReachable" => true, 39 | "manufacturerName" => "broadlink", 40 | "modelName" => "植物补光器", 41 | "version" => "1.0" 42 | ), 43 | array( 44 | "actions" => array("turnOn", "timingTurnOn", "turnOff", "timingTurnOff"), 45 | "applianceTypes" => array("HEATER"), 46 | "additionalApplianceDetails" => array(), 47 | "applianceId" => "switch.temperature", 48 | "friendlyDescription" => "温度", 49 | "friendlyName" => "植物调温器", 50 | "isReachable" => true, 51 | "manufacturerName" => "broadlink", 52 | "modelName" => "植物调温器", 53 | "version" => "1.0" 54 | ), 55 | array( 56 | "actions" => array("getTemperatureReading"), 57 | "applianceTypes" => array("AIR_MONITOR"), 58 | "additionalApplianceDetails" => array(), 59 | "applianceId" => "sensor.plant_temperature", 60 | "friendlyDescription" => "温度", 61 | "friendlyName" => "花花草草温度", 62 | "isReachable" => true, 63 | "manufacturerName" => "miflora", 64 | "modelName" => "花花草草温度", 65 | "version" => "1.0" 66 | ), 67 | array( 68 | "actions" => array("getHumidity"), 69 | "applianceTypes" => array("AIR_MONITOR"), 70 | "additionalApplianceDetails" => array(), 71 | "applianceId" => "sensor.plant_moisture", 72 | "friendlyDescription" => "湿度", 73 | "friendlyName" => "花花草草湿度", 74 | "isReachable" => true, 75 | "manufacturerName" => "miflora", 76 | "modelName" => "花花草草湿度", 77 | "version" => "1.0" 78 | ), 79 | array( 80 | "actions" => array("getWaterQuality"), 81 | "applianceTypes" => array("AIR_MONITOR"), 82 | "additionalApplianceDetails" => array(), 83 | "applianceId" => "sensor.plant_conductivity", 84 | "friendlyDescription" => "电导率", 85 | "friendlyName" => "花花草草电导率", 86 | "isReachable" => true, 87 | "manufacturerName" => "miflora", 88 | "modelName" => "花花草草电导率", 89 | "version" => "1.0" 90 | ), 91 | array( 92 | "actions" => array("getRunningStatus"), 93 | "applianceTypes" => array("AIR_MONITOR"), 94 | "additionalApplianceDetails" => array(), 95 | "applianceId" => "sensor.plant_battery", 96 | "friendlyDescription" => "电量", 97 | "friendlyName" => "花花草草电量", 98 | "isReachable" => true, 99 | "manufacturerName" => "miflora", 100 | "modelName" => "花花草草电量", 101 | "version" => "1.0" 102 | ), 103 | array( 104 | "actions" => array("getTemperatureReading"), 105 | "applianceTypes" => array("AIR_MONITOR"), 106 | "additionalApplianceDetails" => array(), 107 | "applianceId" => "sensor.temperature", 108 | "friendlyDescription" => "环境温度", 109 | "friendlyName" => "环境温度", 110 | "isReachable" => true, 111 | "manufacturerName" => "nodemcu", 112 | "modelName" => "环境温度", 113 | "version" => "1.0" 114 | ), 115 | array( 116 | "actions" => array("turnOn", "timingTurnOn", "turnOff", "timingTurnOff", "setBrightnessPercentage", "setColor"), 117 | "applianceTypes" => array("LIGHT"), 118 | "additionalApplianceDetails" => array("setBrightnessPercentage" => "brightness_pct", "setColor" => "rgb_color"), 119 | "applianceId" => "light.bed_room_light", 120 | "friendlyDescription" => "彩色灯环", 121 | "friendlyName" => "彩色灯环", 122 | "isReachable" => true, 123 | "manufacturerName" => "nodemcu", 124 | "modelName" => "彩色灯环", 125 | "version" => "1.0" 126 | ), 127 | array( 128 | "actions" => array("getHumidity"), 129 | "applianceTypes" => array("AIR_MONITOR"), 130 | "additionalApplianceDetails" => array(), 131 | "applianceId" => "sensor.humidity", 132 | "friendlyDescription" => "环境湿度", 133 | "friendlyName" => "环境湿度", 134 | "isReachable" => true, 135 | "manufacturerName" => "nodemcu", 136 | "modelName" => "环境温度", 137 | "version" => "1.0" 138 | ) 139 | ) 140 | ); 141 | ?> 142 | -------------------------------------------------------------------------------- /server.php: -------------------------------------------------------------------------------- 1 | $dsn, 'username' => $username, 'password' => $password)); 16 | 17 | // Pass a storage object or array of storage objects to the OAuth2 server class 18 | $server = new OAuth2\Server($storage); 19 | 20 | // Add the "Client Credentials" grant type (it is the simplest of the grant types) 21 | #$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage)); 22 | 23 | // Add the "Authorization Code" grant type (this is where the oauth magic happens) 24 | $server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage)); 25 | -------------------------------------------------------------------------------- /token.php: -------------------------------------------------------------------------------- 1 | addGrantType(new OAuth2\GrantType\AuthorizationCode($storage)); 10 | #$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send(); 11 | $server->handleTokenRequest(OAuth2\Request::createFromGlobals(), new OAuth2\Response())->send(); 12 | 13 | --------------------------------------------------------------------------------