39b042c966de7a3f1958ad5b4c80026e3c2e4e1f
[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         if ($ip == '') {
25             throw new \Exception('No remote IP or hostname given.');
26         }
27
28         $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
29         if ($socket === false) {
30             throw new \Exception(
31                 'socket_create() failed: reason: '
32                 . socket_strerror(socket_last_error())
33             );
34         }
35         //echo "Attempting to connect to '$ip' on port '$port'...";
36         $result = socket_connect($socket, $ip, $port);
37         if ($result === false) {
38             throw new \Exception(
39                 "socket_connect() failed. Reason: "
40                 . socket_strerror(socket_last_error($socket))
41             );
42         }
43
44         $this->socket = $socket;
45     }
46
47     function init()
48     {
49         $msg = "\x00\x01DecoderV=1\n";
50         socket_write($this->socket, $msg, strlen($msg));
51         $res = $this->read_response();
52         socket_write($this->socket, "\x00\x02", 2);
53     }
54
55     function loop()
56     {
57         while (true) {
58             $dbgmsg = $this->read_response();
59             //echo $dbgmsg . "\n";
60             $this->handler->handle($dbgmsg);
61         }
62     }
63
64     function read_response()
65     {
66         $res = socket_read($this->socket, 2048, PHP_NORMAL_READ);
67         return substr($res, 2, -1);
68     }
69
70     function disconnect()
71     {
72         socket_write($this->socket, "\x00\x03", 2);
73         socket_close($this->socket);
74     }
75
76 }
77
78 ?>