-
Notifications
You must be signed in to change notification settings - Fork 1
/
obihai2mqtt.php
executable file
·82 lines (67 loc) · 2.06 KB
/
obihai2mqtt.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/php
<?php
require __DIR__ . '/vendor/bluerhinos/phpmqtt/phpMQTT.php';
$longOpts = array(
'poll_freq:',
'obihai_host:',
'obihai_user:',
'obihai_pass:',
'mqtt_host:',
'mqtt_port:',
'mqtt_user:',
'mqtt_pass:',
'mqtt_topic:',
);
$options = getopt(null, $longOpts);
if (!isset($options['obihai_host']))
{
print "Parameter --obihai_host is mandatory!\n";
exit(1);
}
$poll_freq = (isset($options['poll_freq']) ? $options['poll_freq'] : 5);
$obihai_host = $options['obihai_host'];
$obihai_user = (isset($options['obihai_user']) ? $options['obihai_user'] : 'admin');
$obihai_pass = (isset($options['obihai_pass']) ? $options['obihai_pass'] : 'admin');
$mqtt_host = (isset($options['mqtt_host']) ? $options['mqtt_host'] : 'localhost');
$mqtt_port = (isset($options['mqtt_port']) ? $options['mqtt_port'] : 1883);
$mqtt_user = (isset($options['mqtt_user']) ? $options['mqtt_user'] : '');
$mqtt_pass = (isset($options['mqtt_pass']) ? $options['mqtt_pass'] : '');
$mqtt_topic = (isset($options['mqtt_topic']) ? $options['mqtt_topic'] : 'obihai');
$mqtt = new phpMQTT($mqtt_host, $mqtt_port, 'obihai2mqtt_'.rand());
$url = 'http://' . $obihai_host . '/PI_FXS_1_Stats.xml';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_USERPWD, "$obihai_user:$obihai_pass");
while (true)
{
$states = array();
$xml = new SimpleXMLElement(curl_exec($curl));
$parameters = $xml->xpath('//parameter');
foreach ($parameters as $parameter)
{
foreach ($parameter->attributes() as $attribute => $value)
{
if ($attribute == 'name' && $value == 'State')
{
$states[] = $parameter->value['current'];
}
}
}
if ($mqtt->connect(true, null, $mqtt_user, $mqtt_pass))
{
$i = 1;
foreach ($states as $state)
{
$mqtt->publish($mqtt_topic . '/state_line' . $i, $state);
$i++;
}
$mqtt->close();
}
else
{
print "Cannot connect to MQTT.\n";
}
sleep($poll_freq);
}