2df79693bdf07cfafe04dbc579269a08e41ad5f1
[auerswald-callnotifier.git] / src / callnotifier / MessageHandler.php
1 <?php
2 namespace callnotifier;
3
4 class MessageHandler
5 {
6     protected $dumpHdl;
7
8
9     public function __construct($config, $log, $callMonitor)
10     {
11         $this->config = $config;
12         $this->prepareDump();
13         $this->log = $log;
14         $this->callMonitor = $callMonitor;
15     }
16
17     public function handle($msg)
18     {
19         if ($this->config->dumpFile !== null) {
20             $this->dump($msg);
21         }
22         if (substr($msg, 0, 9) != '[DKANPROT') {
23             //unknown message type
24             return;
25         }
26         $regex = '#^\\[DKANPROT-([^ ]+) ([0-9]+)\\] (.*)$#';
27         if (!preg_match($regex, $msg, $matches)) {
28             //message should always be that way
29             return false;
30         }
31         list(, $type, $someid, $details) = $matches;
32         $this->log->log(
33             'msgData',
34             array(
35                 'type' => $type,
36                 'id' => $someid,
37                 'details' => $details
38             )
39         );
40
41         if ($type == 'Debug') {
42             $msg = $this->parseEDSS1($details);
43             if (is_object($msg)) {
44                 $this->log->log('edss1msg', array('msg' => $msg));
45                 $this->callMonitor->handle($msg);
46             }
47         }
48     }
49
50     /**
51      * Example string: "T02: 00 A3 06 0A 08 01 01 5A FF 0A"
52      *
53      * @param string $details Detail string of a debug message
54      *
55      * @return EDSS1_Message The retrieved message, NULL if none.
56      */
57     protected function parseEDSS1($details)
58     {
59         if ($details{0} != 'T' && $details{0} != 'N') {
60             //we only want byte data
61             return;
62         }
63         if (substr($details, 16, 4) != ' 08 ') {
64             //only E-DSS-1, no other packets
65             return;
66         }
67         
68         $bytestring = substr($details, 5);
69         $bytes = static::getBytesFromHexString($bytestring);
70
71         $mp = new EDSS1_Parser();
72         return $mp->parse($bytes);
73     }
74
75     public static function getBytesFromHexString($bytestring)
76     {
77         $bytes = '';
78         foreach (explode(' ', $bytestring) as $strbyte) {
79             $bytes .= chr(hexdec($strbyte));
80         }
81         return $bytes;
82     }
83
84     protected function prepareDump()
85     {
86         if ($this->config->dumpFile === null) {
87             return;
88         }
89         $this->dumpHdl = fopen($this->config->dumpFile, 'w');
90         if (!$this->dumpHdl) {
91             throw new Exception('Cannot open replay file for reading');
92         }
93     }
94
95     protected function dump($msg)
96     {
97         fwrite($this->dumpHdl, $msg . "\n");
98     }
99 }
100
101 ?>