36e468dc1b5b98b0d698ba688d0e3c187647d9ea
[auerswald-callnotifier.git] / src / callnotifier / Source / Remote.php
1 <?php
2 namespace callnotifier;
3
4 class Source_Remote
5 {
6     protected $socket;
7
8     public function __construct($config, $handler)
9     {
10         $this->config  = $config;
11         $this->handler = $handler;
12     }
13
14     public function run()
15     {
16         $this->connect($this->config->host, $this->config->port);
17         $this->init();
18         $this->loop();
19         $this->disconnect();
20     }
21
22     public function connect($ip, $port)
23     {
24         $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
25         if ($socket === false) {
26             echo "socket_create() failed: reason: "
27                 . socket_strerror(socket_last_error()) . "\n";
28         } else {
29             echo "OK.\n";
30         }
31         echo "Attempting to connect to '$ip' on port '$port'...";
32         $result = socket_connect($socket, $ip, $port);
33         if ($result === false) {
34             echo "socket_connect() failed.\nReason: ($result) "
35                 . socket_strerror(socket_last_error($socket)) . "\n";
36         } else {
37             echo "OK.\n";
38         }
39
40         $this->socket = $socket;
41     }
42
43     function init()
44     {
45         $msg = "\x00\x01DecoderV=1\n";
46         socket_write($this->socket, $msg, strlen($msg));
47         $res = $this->read_response();
48         socket_write($this->socket, "\x00\x02", 2);
49     }
50
51     function loop()
52     {
53         while (true) {
54             $dbgmsg = $this->read_response();
55             //echo $dbgmsg . "\n";
56             $this->handler->handle($dbgmsg);
57         }
58     }
59
60     function read_response()
61     {
62         $res = socket_read($this->socket, 2048, PHP_NORMAL_READ);
63         return substr($res, 2, -1);
64     }
65
66     function disconnect()
67     {
68         socket_write($this->socket, "\x00\x03", 2);
69         socket_close($this->socket);
70     }
71
72 }
73
74 ?>