-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathevent.py
More file actions
76 lines (65 loc) · 2.56 KB
/
event.py
File metadata and controls
76 lines (65 loc) · 2.56 KB
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
#!/usr/bin/env python
##
## This file is part of the OpenSIPS Python Package
## (see https://github.com/OpenSIPS/python-opensips).
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
""" Module that implements OpenSIPS Event behavior """
from threading import Thread, Event
from ..mi import OpenSIPSMIException
class OpenSIPSEventException(Exception):
""" Exceptions generated by OpenSIPS Events """
class OpenSIPSEvent():
""" Implementation of the OpenSIPS Event """
def __init__(self, handler, name: str, callback, expire=None):
self._handler = handler
self.name = name
self.callback = callback
self.thread = None
self.thread_stop = Event()
self.thread_stop.clear()
try:
self.socket = self._handler.__new_socket__()
self._handler.__mi_subscribe__(self.name, self.socket.create(), expire)
self._handler.events[self.name] = self
self.thread = Thread(target=self.handle, args=(callback,))
self.thread.start()
except OpenSIPSEventException as e:
raise e
except OpenSIPSMIException as e:
raise e
except ValueError as e:
raise OpenSIPSEventException("Invalid arguments for socket creation: {}".format(e))
def handle(self, callback):
""" Handles the event callbacks """
while not self.thread_stop.is_set():
data = self.socket.read()
if data:
callback(data)
def unsubscribe(self):
""" Unsubscribes the event """
try:
self._handler.__mi_unsubscribe__(self.name, self.socket.sock_name)
self.stop()
del self._handler.events[self.name]
except OpenSIPSEventException as e:
raise e
except OpenSIPSMIException as e:
raise e
def stop(self):
""" Stops the current event processing """
self.thread_stop.set()
self.thread.join()
self.socket.destroy()