Better subprocess handling
[openhab-process.git] / mqtt-agi / mqtt
1 #!/usr/bin/env python
2
3 #
4 # Usage:
5 # AGI(/etc/asterisk/agi/mqtt,/etc/asterisk/agi/mqtt.cfg,calls/missed)
6 # or, to override the extension:
7 # AGI(/etc/asterisk/agi/mqtt,/etc/asterisk/agi/mqtt.cfg,calls/missed,+43123456789)
8 #
9
10 import sys
11 from ConfigParser import ConfigParser
12 import paho.mqtt.client as paho
13
14 import json
15
16 from pprint import pprint
17
18 conffile, topic = sys.argv[1:3]
19
20 config = ConfigParser()
21 config.add_section('mqtt')
22 # set defaults for anonymous auth
23 config.set('mqtt', 'username', '')
24 config.set('mqtt', 'password', '')
25 config.set('mqtt', 'port', '1883')
26 config.read(conffile)
27
28 mqtt_server = config.get('mqtt', 'server')
29 mqtt_port = config.getint('mqtt', 'port')
30 mqtt_username = config.get('mqtt', 'username')
31 mqtt_password = config.get('mqtt', 'password')
32
33 agi = []
34 while 1:
35     line = sys.stdin.readline()
36     if not line or line == "\n":
37         break
38     agi.append(line)
39
40 agi = dict([line.rstrip('\n').replace('agi_', '', 1).split(': ', 1) for line in agi])
41
42 if len(sys.argv) > 3:
43     agi['extension'] = sys.argv[3]
44
45 def agi_exit(rc, *args):
46     if rc != 0:
47         print "VERBOSE rc=%s %s" % (rc, args)
48     sys.exit(rc)
49
50 def on_connect(mosq, rc, *args):
51     if rc != 0:
52         agi_exit(1, "Connection failed: %d" % rc)
53
54 def on_publish(mosq, *args):
55     # done
56     agi_exit(0)
57
58 client = paho.Client('agi')
59 client.username_pw_set(mqtt_username, mqtt_password)
60 client.connect(mqtt_server, port=mqtt_port)
61 client.on_connect = on_connect
62 client.on_publish = on_publish
63
64 client.publish(topic, payload=json.dumps(agi))
65 client.loop()
66 agi_exit(1, "Message publish timed out")