forked from itskenny0/Yeelight-PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Yeelight.class.php
54 lines (43 loc) · 1.17 KB
/
Yeelight.class.php
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
<?php
class Yeelight {
private $jobs = array();
public function __construct($ip, $port) {
$this->ip = $ip;
$this->port = $port;
if (!$this->verifyConnection()) throw new Exception("Failed connecting to Yeelight device.");
}
private function verifyConnection() {
$this->fp = fsockopen($this->ip, $this->port, $this->errno, $this->errstr, 30);
if (!$this->fp) return false;
stream_set_blocking($this->fp, false);
return true;
}
private function getNextID() {
if(!empty($this->jobs)) return count($this->jobs);
else return 0;
}
public function __call($method, $args) {
$jObj = new stdClass;
$jObj->id = $this->getNextID();
$jObj->method = $method;
$jObj->params = $args;
$this->jobs[] = $jObj;
return $this;
}
public function commit() {
if (!$this->verifyConnection()) throw new Exception("Failed connecting to Yeelight device.");
foreach($this->jobs as $job) {
$jStr = json_encode($job);
fwrite($this->fp, $jStr . "\r\n");
fflush($this->fp);
usleep(100 * 1000);
$out[] = fgets($this->fp);
}
$this->jobs = array();
if(!empty($out)) return $out;
else return true;
}
public function disconnect() {
fclose($this->fp);
}
}