├── .gitignore ├── LICENSE ├── README.md └── sip2mqtt.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | sip2mqttcfg.py 92 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Martin Tremblay 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sip2mqtt 2 | A SIP monitoring script that publishes incoming calls with CallerID to an MQTT channel 3 | 4 | see also [pjsip-docker](https://github.com/MartyTremblay/pjsip-docker) 5 | 6 | ## usage 7 | 8 | Allows the monitoring of SIP connections and publishes the CallerID payload to an MQTT channel. The script requires the following parametters: 9 | 10 | ```bash 11 | -a MQTT_ADDRESS, --mqtt_address MQTT_ADDRESS 12 | the MQTT broker address string 13 | -t MQTT_PORT, --mqtt_port MQTT_PORT 14 | the MQTT broker port number 15 | -u MQTT_USERNAME, --mqtt_username MQTT_USERNAME 16 | the MQTT broker username 17 | -p MQTT_PASSWORD, --mqtt_password MQTT_PASSWORD 18 | the MQTT broker password 19 | -d SIP_DOMAIN, --sip_domain SIP_DOMAIN 20 | the SIP domain 21 | -n SIP_USERNAME, --sip_username SIP_USERNAME 22 | the SIP username 23 | -s SIP_PASSWORD, --sip_password SIP_PASSWORD 24 | the SIP password 25 | ``` 26 | Example: 27 | ```bash 28 | python /opt/sip2mqtt/sip2mqtt.py -t16491 -afoo.cloudmqtt.com -uSip2Mqtt -pSECRET -dfoo.voip.ms -nSUB_DID -sSECRET -vvv 29 | ``` 30 | More optional parametters can be viewed by running python sip2mqtt.py -h 31 | -------------------------------------------------------------------------------- /sip2mqtt.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os as os 3 | import signal 4 | import logging 5 | import threading 6 | import time 7 | import re 8 | import argparse 9 | import json 10 | import pjsua as pj 11 | import paho.mqtt.client as mqtt 12 | 13 | global args 14 | 15 | def extract_caller_id(url): 16 | m = re.match(r"\"(.*)\".*:(.*)@", url) 17 | return m.group(1) + " " + phone_format(m.group(2)) 18 | 19 | def phone_format(phone_number): 20 | clean_phone_number = re.sub('[^0-9]+', '', phone_number) 21 | formatted_phone_number = '' 22 | 23 | try: 24 | formatted_phone_number = re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1-", "%d" % int(clean_phone_number[:-1])) + clean_phone_number[-1] 25 | except: 26 | logging.warn( "Warning: unable to format " + clean_phone_number ) 27 | formatted_phone_number = clean_phone_number 28 | 29 | return formatted_phone_number 30 | 31 | def signal_handler(signal, frame): 32 | logging.info( 'Exiting...' ) 33 | logging.info( '-- Unregistering --' ) 34 | time.sleep(2) 35 | logging.info( '-- Destroying Libraries --' ) 36 | time.sleep(2) 37 | lib.destroy() 38 | sys.exit(0) 39 | 40 | # Method to print Log of callback class 41 | def log_cb(level, str, len): 42 | logging.debug("SIP debug: " + str), 43 | 44 | # Callback for an established MQTT broker connection 45 | def mqtt_connect(broker, userdata, flags, rc): 46 | logging.info("MQTT: Connected with the broker...") 47 | 48 | # Callback to receive events from account 49 | class SMAccountCallback(pj.AccountCallback): 50 | global args 51 | 52 | def __init__(self, account=None): 53 | pj.AccountCallback.__init__(self, account) 54 | self.args = args 55 | 56 | def on_reg_state(self): 57 | logging.info( "SIP: Registration complete, status=" + str(self.account.info().reg_status) + " (" + str(self.account.info().reg_reason) + ")" ) 58 | 59 | def on_incoming_call(self, call): 60 | # Unless this callback is implemented, the default behavior is to reject the call with default status code. 61 | logging.info( "SIP: Incoming call from " + extract_caller_id( call.info().remote_uri ) ) 62 | broker.publish(args.mqtt_topic, payload="{\"verb\": \"incoming\", \"caller\":\"" + extract_caller_id( call.info().remote_uri ) + "\", \"uri\":" + json.dumps(call.info().remote_uri) + "}", qos=0, retain=True) 63 | 64 | current_call = call 65 | call_cb = SMCallCallback(current_call) 66 | current_call.set_callback(call_cb) 67 | 68 | def on_pager(self, from_uri, contact, mime_type, body): 69 | logging.info( "SIP: Incoming SMS from " + from_uri ) 70 | broker.publish(args.mqtt_topic, payload="{\"verb\": \"sms\", \"caller\":\"" + from_uri + "\", \"body\":" + json.dumps(body) + "}", qos=0, retain=True) 71 | 72 | 73 | class SMCallCallback(pj.CallCallback): 74 | def __init__(self, call=None): 75 | pj.CallCallback.__init__(self, call) 76 | self.args = args 77 | 78 | # Notification when call state has changed 79 | def on_state(self): 80 | logging.info( 'SIP: Call state is: ' + self.call.info().state_text ) 81 | if self.call.info().state == pj.CallState.CONFIRMED: 82 | logging.info( 'SIP: Current call is answered' ) 83 | broker.publish(args.mqtt_topic, payload="{\"verb\": \"answered\", \"caller\":\"" + extract_caller_id( self.call.info().remote_uri ) + "\", \"uri\":" + json.dumps(self.call.info().remote_uri) + "}", qos=0, retain=True) 84 | elif self.call.info().state == pj.CallState.DISCONNECTED: 85 | logging.info( 'SIP: Current call has ended' ) 86 | broker.publish(args.mqtt_topic, payload="{\"verb\": \"disconnected\", \"caller\":\"\", \"uri\":\"\"}", qos=0, retain=True) 87 | 88 | def main(argv): 89 | global broker 90 | global pj 91 | global lib 92 | global args 93 | 94 | app_name="SIP2MQTT" 95 | 96 | parser = argparse.ArgumentParser(description='A SIP monitoring tool that publishes incoming calls with CallerID to an MQTT channel') 97 | requiredNamed = parser.add_argument_group('required named arguments') 98 | 99 | requiredNamed.add_argument("-a", "--mqtt_domain", type=str, required=True, help="the MQTT broker domain string", default=os.environ.get('MQTT_DOMAIN', None)) 100 | requiredNamed.add_argument("-t", "--mqtt_port", type=int, required=True, help="the MQTT broker port number", default=os.environ.get('MQTT_PORT', None)) 101 | parser.add_argument( "--mqtt_keepalive", type=int, required=False, help="the MQTT broker keep alive in seconds", default=60) 102 | parser.add_argument( "--mqtt_protocol", type=str, required=False, help="the MQTT broker protocol", default="MQTTv311", choices=['MQTTv31', 'MQTTv311']) 103 | requiredNamed.add_argument("-u", "--mqtt_username", type=str, required=True, help="the MQTT broker username", default=os.environ.get('MQTT_USERNAME', None)) 104 | requiredNamed.add_argument("-p", "--mqtt_password", type=str, required=False, help="the MQTT broker password", default=os.environ.get('MQTT_PASSWORD', None)) 105 | parser.add_argument( "--mqtt_topic", type=str, required=False, help="the MQTT broker topic", default=os.environ.get('MQTT_TOPIC', "home/sip")) 106 | 107 | requiredNamed.add_argument("-d", "--sip_domain", type=str, required=True, help="the SIP domain", default=os.environ.get('SIP_DOMAIN', None)) 108 | parser.add_argument( "--sip_port", type=int, required=False, help="the SIP transport port number", default=os.environ.get('SIP_PORT', 5060)) 109 | requiredNamed.add_argument("-n", "--sip_username", type=str, required=True, help="the SIP username", default=os.environ.get('SIP_USERNAME', None)) 110 | requiredNamed.add_argument("-s", "--sip_password", type=str, required=False, help="the SIP password", default=os.environ.get('SIP_PASSWORD', None)) 111 | parser.add_argument( "--sip_display", type=str, required=False, help="the SIP user display name", default=app_name) 112 | 113 | parser.add_argument( "--log_level", type=int, required=False, help="the application log level", default=3, choices=[0, 1, 2, 3]) 114 | parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity", default=3) 115 | 116 | args = parser.parse_args() 117 | 118 | log_level = logging.INFO #Deault logging level 119 | if args.verbosity == 1: 120 | log_level = logging.ERROR 121 | elif args.verbosity == 2: 122 | log_level = logging.WARN 123 | elif args.verbosity == 3: 124 | log_level = logging.INFO 125 | elif args.verbosity >= 4: 126 | log_level = logging.DEBUG 127 | 128 | # Configure logging 129 | # logging.basicConfig(filename="sip2mqtt.log", format="%(asctime)s - %(levelname)s - %(message)s", 130 | # datefmt="%m/%d/%Y %I:%M:%S %p", level=log_level) 131 | root = logging.getLogger() 132 | root.setLevel(log_level) 133 | 134 | # ch = logging.StreamHandler(sys.stdout) 135 | # ch.setLevel(log_level) 136 | # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 137 | # ch.setFormatter(formatter) 138 | # root.addHandler(ch) 139 | # A more docker-friendly approach is to output to stdout 140 | logging.basicConfig(stream=sys.stdout, format="%(asctime)s - %(levelname)s - %(message)s", 141 | datefmt="%m/%d/%Y %I:%M:%S %p", level=log_level) 142 | 143 | # Log startup messages and our configuration parameters 144 | logging.info("------------------------") 145 | logging.info("Starting up...") 146 | logging.info("--- MQTT Broker Configuration ---") 147 | logging.info("Domain: " + args.mqtt_domain) 148 | logging.info("Port: " + str(args.mqtt_port)) 149 | logging.info("Protocol: " + args.mqtt_protocol) 150 | logging.info("Username: " + args.mqtt_username) 151 | logging.info("Keepalive Interval: " + str(args.mqtt_keepalive)) 152 | logging.info("Status Topic: " + args.mqtt_topic) 153 | logging.info("--- SIP Configuration ---") 154 | logging.info("Domain: " + args.sip_domain) 155 | logging.info("Username: " + args.sip_username) 156 | logging.info("DisplayName: " + args.sip_display) 157 | 158 | try: 159 | # Handle mqtt connection and callbacks 160 | broker = mqtt.Client(client_id="", clean_session=True, userdata=None, protocol=eval("mqtt." + args.mqtt_protocol)) 161 | broker.username_pw_set(args.mqtt_username, password=args.mqtt_password) 162 | broker.on_connect = mqtt_connect 163 | #broker.on_message = mqtt_message #don't need this callback for now 164 | broker.connect(args.mqtt_domain, args.mqtt_port, args.mqtt_keepalive) 165 | 166 | # Create library instance of Lib class 167 | lib = pj.Lib() 168 | 169 | ua = pj.UAConfig() 170 | ua.user_agent = app_name 171 | 172 | mc = pj.MediaConfig() 173 | mc.clock_rate = 8000 174 | 175 | lib.init(ua_cfg = ua, log_cfg = pj.LogConfig(level=args.verbosity, callback=None), media_cfg=mc) 176 | lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(args.sip_port)) 177 | lib.set_null_snd_dev() 178 | lib.start() 179 | 180 | acc_cfg = pj.AccountConfig() 181 | acc_cfg.id = "sip:" + args.sip_username + "@" + args.sip_domain 182 | acc_cfg.reg_uri = "sip:" + args.sip_domain 183 | acc_cfg.auth_cred = [ pj.AuthCred("*", args.sip_username, args.sip_password) ] 184 | acc_cfg.allow_contact_rewrite = False 185 | 186 | acc = lib.create_account(acc_cfg) 187 | acc_cb = SMAccountCallback(acc) 188 | acc.set_callback(acc_cb) 189 | 190 | logging.info( "-- Registration Complete --" ) 191 | logging.info( 'SIP: Status = ' + str(acc.info().reg_status) + ' (' + acc.info().reg_reason + ')' ) 192 | 193 | except pj.Error, e: 194 | logging.critical( ("Exception: " + str(e)) ) 195 | lib.destroy() 196 | sys.exit(1) 197 | 198 | # Main work loop 199 | try: 200 | rc = broker.loop_start() 201 | if rc: 202 | logging.warn( "Warning: " + str(rc) ) 203 | 204 | signal.signal(signal.SIGINT, signal_handler) 205 | while True: 206 | time.sleep(1) 207 | broker.loop_stop() 208 | 209 | except Exception, ex: 210 | logging.critical("Exception: " + str(ex)) 211 | lib.destroy() 212 | sys.exit(1) 213 | 214 | # Get things started 215 | if __name__ == '__main__': 216 | main(sys.argv[1:]) 217 | --------------------------------------------------------------------------------