Merge branch 'master' of rvb.name:openhab-process
[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 os import getpid,uname
17 from pprint import pprint
18
19 client_name='agi-'+uname()[1]+'-'+str(getpid())
20 print client_name
21
22 conffile, topic = sys.argv[1:3]
23
24 config = ConfigParser()
25 config.add_section('mqtt')
26 # set defaults for anonymous auth
27 config.set('mqtt', 'username', '')
28 config.set('mqtt', 'password', '')
29 config.set('mqtt', 'port', '1883')
30 config.read(conffile)
31
32 mqtt_server = config.get('mqtt', 'server')
33 mqtt_port = config.getint('mqtt', 'port')
34 mqtt_username = config.get('mqtt', 'username')
35 mqtt_password = config.get('mqtt', 'password')
36
37 agi = []
38 while 1:
39     line = sys.stdin.readline()
40     if not line or line == "\n":
41         break
42     agi.append(line)
43
44 agi = dict([line.rstrip('\n').replace('agi_', '', 1).split(': ', 1) for line in agi])
45
46 if len(sys.argv) > 3:
47     agi['extension'] = sys.argv[3]
48
49 def agi_exit(rc, *args):
50     if rc != 0:
51         print "VERBOSE rc=%s %s" % (rc, args)
52     sys.exit(rc)
53
54 def on_connect(mosq, rc, *args):
55     if rc != 0:
56         agi_exit(1, "Connection failed: %d" % rc)
57
58 def on_publish(mosq, *args):
59     # done
60     agi_exit(0)
61
62 client = paho.Client(client_name)
63 client.username_pw_set(mqtt_username, mqtt_password)
64 client.connect(mqtt_server, port=mqtt_port)
65 client.on_connect = on_connect
66 client.on_publish = on_publish
67
68 client.publish(topic, payload=json.dumps(agi))
69 client.loop()
70 agi_exit(1, "Message publish timed out")