def main(argv=None): if argv is None: argv = sys.argv argparser = argparse.ArgumentParser( description="Linphone console interface in Python.") argparser.add_argument( '--config', default=None, help="Path to the linphonerc configuration file to use.") argparser.add_argument( '--factory_config', default=None, help="Path to the linphonerc factory configuration file to use.") argparser.add_argument( '--log', default=None, help= "Path to the file used for logging (default is the standard output).") argparser.add_argument( '--trace', action='store_true', help="Output linphone Python module tracing logs (for debug purposes)." ) args = argparser.parse_args() setup_log(args.log, args.trace) linphone.set_log_handler(log_handler) d = Daemon() d.run(args)
def __init__(self, username='', password='', whitelist=[]): self.openDoor = False self.callerId = "" self.timeOpenDoor = 0 self.maxTimeOpenedDoor = 2 #seconds self.quit = False self.f = IFTTT_Farolas(self.testing_lights(), True) self.whitelist = whitelist callbacks = { 'call_state_changed': self.call_state_changed, } # Configure the linphone core logging.basicConfig(level=logging.INFO, filename='/tmp/sipPuerta.log', filemode='w') linphone.set_log_handler(self.log_handler) self.core = linphone.Core.new(callbacks, None, None) self.core.disable_chat(linphone.Reason.NotImplemented) self.core.echo_cancellation_enabled = False self.core.video_capture_enabled = False self.core.video_display_enabled = False self.core.mic_enabled = False self.ring_during_incoming_early_media = False self.core.stun_server = 'stun.linphone.org' self.core.firewall_policy = linphone.FirewallPolicy.PolicyUseIce self.configure_sip_account(username, password)
def __init__(self, username='', password='', whitelist=[], camera='', snd_capture='', snd_playback=''): self.quit = False self.whitelist = whitelist callbacks = linphone.Factory.get().create_core_cbs() callbacks.call_state_changed = self.call_state_changed # Configure the linphone core logging.basicConfig(level=logging.INFO) signal.signal(signal.SIGINT, self.signal_handler) linphone.set_log_handler(self.log_handler) self.core = linphone.Factory.get().create_core(callbacks, None, None) self.core.max_calls = 1 self.core.echo_cancellation_enabled = False self.core.video_capture_enabled = True self.core.video_display_enabled = False self.core.nat_policy.stun_server = 'stun.linphone.org' self.core.nat_policy.ice_enabled = True if len(camera): self.core.video_device = camera if len(snd_capture): self.core.capture_device = snd_capture if len(snd_playback): self.core.playback_device = snd_playback self.configure_sip_account(username, password)
def __init__(self, username='', password='', snd_capture='', snd_playback=''): self.quit = False callbacks = { 'call_state_changed': self.call_state_changed, } # Configure the linphone core logging.basicConfig(level=logging.INFO) signal.signal(signal.SIGINT, self.signal_handler) linphone.set_log_handler(self.log_handler) self.core = linphone.Core.new(callbacks, None, None) self.core.max_calls = 4 self.core.echo_cancellation_enabled = False self.core.video_capture_enabled = False self.core.video_display_enabled = False self.core.stun_server = 'stun.linphone.org' self.core.firewall_policy = linphone.FirewallPolicy.PolicyUseIce if len(snd_capture): self.core.capture_device = snd_capture if len(snd_playback): self.core.playback_device = snd_playback # Only enable PCMU and PCMA audio codecs for codec in self.core.audio_codecs: if codec.mime_type == "PCMA" or codec.mime_type == "PCMU": self.core.enable_payload_type(codec, True) else: self.core.enable_payload_type(codec, False) self.configure_sip_account(username, password)
def __init__(self): self.quit = False self.make_call = False callbacks = linphone.Factory.get().create_core_cbs() callbacks.call_state_changed = self.call_state_changed callbacks.dtmf_received = self.dtmf_received logger = logging.getLogger() logger.setLevel(logging.INFO) self.logfile = logging.FileHandler(os.environ['LOG_PATH']) logger.addHandler(self.logfile) signal.signal(signal.SIGINT, self.signal_handler) signal.signal(signal.SIGUSR1, self.signal_handler) linphone.set_log_handler(self.log_handler) self.core = linphone.Factory.get().create_core(callbacks, None, None) self.core.video_capture_enabled = True self.core.video_display_enabled = False self.core.video_device = os.environ['VIDEO_DEVICE'] self.core.capture_device = os.environ['SOUND_DEVICE'] self.core.ringback = '{}/call.wav'.format(os.environ['SOUNDS_PATH']) self.configure_account()
def __init__(self, config): """ SIP client using liblinphone for underlying technologies :param config: A Config object to retrieve setting information from """ self.config = config logging.basicConfig(level=logging.INFO) def global_state_changed(*args, **kwargs): print "global_state_changed: %r %r" % (args, kwargs) def registration_state_changed(core, call, state, message): print "registration_state_changed: " + str(state) + ", " + message callbacks = { 'global_state_changed': global_state_changed, 'registration_state_changed': registration_state_changed, } self.core = linphone.Core.new(callbacks, None, None) def log_handler(level, msg): """ Handles logging for linphone :param level: level of logging message (ex. INFO, DEBUG, ERROR) :param msg: message to be logged :return: None """ # Choose the appropriate logging handle debug_method = getattr(logging, level) # debug_method(msg) linphone.set_log_handler(log_handler) self.core.video_capture_enabled = False # remove both of these if we get video implemented self.core.video_display_enabled = False
def __init__(self, filename): logging.Logger.__init__(self, filename) handler = logging.FileHandler(filename) handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname)s: %(message)s', '%H:%M:%S') handler.setFormatter(formatter) self.addHandler(handler) linphone.set_log_handler(self.log_handler)
def main(argv = None): if argv is None: argv = sys.argv argparser = argparse.ArgumentParser(description="Linphone console interface in Python.") argparser.add_argument('--config', default=None, help="Path to the linphonerc configuration file to use.") argparser.add_argument('--factory_config', default=None, help="Path to the linphonerc factory configuration file to use.") argparser.add_argument('--log', default=None, help="Path to the file used for logging (default is the standard output).") argparser.add_argument('--trace', action='store_true', help="Output linphone Python module tracing logs (for debug purposes).") args = argparser.parse_args() setup_log(args.log, args.trace) linphone.set_log_handler(log_handler) d = Daemon() d.run(args)
def __init__(self, username='', password='', whitelist=[], camera='', snd_capture='', snd_playback=''): self.quit = False GPIO.setmode( GPIO.BCM) # set pin numbering mode using GPIO.setmode(GPIO.BCM) GPIO.setup(CALL_BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) self.whitelist = whitelist callbacks = { 'call_state_changed': self.call_state_changed, 'dtmf_received': self.dtmf_received, } # Configure the linphone core logging.basicConfig(level=logging.INFO) signal.signal(signal.SIGINT, self.signal_handler) linphone.set_log_handler(self.log_handler) self.core = linphone.Core.new(callbacks, None, None) self.core.max_calls = 1 self.core.echo_cancellation_enabled = False self.core.video_capture_enabled = True self.core.video_display_enabled = False self.core.stun_server = host self.core.firewall_policy = linphone.FirewallPolicy.PolicyUseIce if len(camera): self.core.video_device = camera if len(snd_capture): self.core.capture_device = snd_capture if len(snd_playback): self.core.playback_device = snd_playback # Only enable PCMU and PCMA audio codecs for codec in self.core.audio_codecs: if codec.mime_type == 'PCMA' or codec.mime_type == 'PCMU': self.core.enable_payload_type(codec, True) else: self.core.enable_payload_type(codec, False) # Only enable VP8 video codec for codec in self.core.video_codecs: if codec.mime_type == 'VP8': self.core.enable_payload_type(codec, True) else: self.core.enable_payload_type(codec, False) self.configure_sip_account(username, password)
def __init__(self): EventEmitter.__init__(self) linphone.set_log_handler(self._logHandler) callbacks = {'call_state_changed': self._callStateHandler} self.core = linphone.Core.new(callbacks, None, None) self.core.max_calls = 1 self.core.ring = '/usr/share/sounds/linphone/rings/oldphone.wav' self.core.ring_level = 100 self.core.echo_cancellation_enabled = False self.core.echo_limiter_enabled = False self.core.video_capture_enabled = False self.core.video_display_enabled = False self.core.video_preview_enabled = False
def __init__(self): self.quit = False callbacks = { 'call_state_changed': self.call_state_changed, } # Configure the linphone core logging.basicConfig(level=logging.INFO) signal.signal(signal.SIGINT, self.signal_handler) linphone.set_log_handler(self.log_handler) self.core = linphone.Core.new(callbacks, None, None) self.core.max_calls = 1 self.core.start_dtmf_stream() self.core.echo_cancellation_enabled = False self.core.use_info_for_dtmf = False self.core.use_rfc2833_for_dtmf = True # Only enable PCMU and PCMA audio codecs for codec in self.core.audio_codecs: print codec.mime_type self.configure_sip_account()
def run(self): linphone.set_log_handler(self.log_handler) callbacks = { 'global_state_changed': self.global_state_changed, 'registration_state_changed': self.registration_state_changed, 'call_state_changed': self.call_state_changed } # Create a linphone core and iterate every 20 ms self.core = linphone.Core.new(callbacks, None, None) self.core.use_files = True self.core.play_file = os.path.dirname( os.path.realpath(__file__)) + '/how-can-i-help-you.wav' self.new_recording_file() while True: self.core.iterate() time.sleep(0.02)
def main(): logging.basicConfig(level=logging.INFO) app = QApplication(sys.argv) def log_handler(level, msg): method = getattr(logging, level) method(msg) def global_state_changed(*args, **kwargs): logging.warning("global_state_changed: %r %r" % (args,kwargs)) def registration_state_changed(core, call, state, message): logging.warning("registration_state_changed: " + str(state) + ", " + message) callbacks = { 'global_state_changed': global_state_changed, 'registration_state_changed': registration_state_changed, } linphone.set_log_handler(log_handler) core = linphone.Core.new(callbacks, None, None) 3cx = linphone.Address.new("sip:[email protected]") proxy_cfg = core.create_proxy_config() core.provisioning_uri = "https://shookke.fl.3cx.us/provisioning/wuvqph5halzuac4" proxy_cfg.identity_address = 3cx proxy_cfg.server_addr = "sip:shookke.fl.3cx.us" proxy_cfg.register_enabled = True core.add_proxy_config(proxy_cfg) iterate_timer = QTimer() iterate_timer.timeout.connect(core.iterate) stop_timer = QTimer() stop_timer.timeout.connect(app.quit) iterate_timer.start(20) stop_timer.start(5000) exitcode = app.exec_() sys.exit(exitcode)
def __init__(self): self.quit_flag = False callbacks = {'call_state_changed': self.call_state_changed} # Configure the linphone core signal.signal(signal.SIGINT, self.signal_handler) linphone.set_log_handler(self.log_handler) if "LINPHONE_CFG" in environ: linphone_cfg = environ.get("LINPHONE_CFG") else: linphone_cfg = "/home/pi/.linphonerc" self.core = linphone.Core.new(callbacks, linphone_cfg, None) if "DB_PATH" in environ: db_path = environ.get("DB_PATH") else: db_path = 'kids_phone_conf/db.kids_phone.sqlite' logging.info("Opening db from {db_path}.".format(db_path=db_path)) self.phonebook_db = sqlite3.connect(db_path, check_same_thread=False) self.core.video_capture_enabled = False self.core.video_display_enabled = False self.core.max_calls = 1 self.core.ringer_device = 'ALSA: bcm2835 ALSA' self.core.capture_device = 'ALSA: C-Media USB Headphone Set' self.core.playback_device = 'ALSA: C-Media USB Headphone Set' #self.core.ringer_device='ALSA: default device' self.core.ring = '/usr/share/sounds/linphone/rings/oldphone.wav' self.state = linphone.CallState.Idle # Setup blinker for LED blinker.setup_and_start(modes=BLINK_MODES) # Setup cradle handler cradle.setup(self.cradle_up_handler, self.cradle_down_handler) fetap_keypad.setup(key_handler=self.call)
def main(): logging.basicConfig(level=logging.INFO) app = QApplication(sys.argv) def log_handler(level, msg): method = getattr(logging, level) method(msg) def global_state_changed(*args, **kwargs): logging.warning("global_state_changed: %r %r" % (args, kwargs)) def registration_state_changed(core, call, state, message): logging.warning("registration_state_changed: " + str(state) + ", " + message) callbacks = { 'global_state_changed': global_state_changed, 'registration_state_changed': registration_state_changed, } linphone.set_log_handler(log_handler) core = linphone.Core.new(callbacks, None, None) proxy_cfg = core.create_proxy_config() proxy_cfg.identity = "sip:[email protected]" proxy_cfg.server_addr = "sip:test.linphone.org" proxy_cfg.register_enabled = True core.add_proxy_config(proxy_cfg) iterate_timer = QTimer() iterate_timer.timeout.connect(core.iterate) stop_timer = QTimer() stop_timer.timeout.connect(app.quit) iterate_timer.start(20) stop_timer.start(5000) exitcode = app.exec_() sys.exit(exitcode)
def __init__(self, whitelist=[]): self.quit = False self.whitelist = whitelist callbacks = linphone.Factory.get().create_core_cbs() callbacks.call_state_changed = self.call_state_changed callbacks.registration_state_changed = self.call_state_changed callbacks.message_received = self.message_received path = os.path.dirname(os.path.abspath(__file__)) logger = logging.getLogger() logger.setLevel(logging.INFO) self.logfile = logging.FileHandler(path + '/linphonecam.log') logger.addHandler(self.logfile) signal.signal(signal.SIGINT, self.signal_handler) linphone.set_log_handler(self.log_handler) self.quit_when_registered = False self.core = linphone.Factory.get().create_core(callbacks, path + '/config.rc', None) self.path = path
conf = DoorPi().config def log_handler(level, msg): if ('pylinphone_Core_instance_method_iterate' in msg or 'pylinphone_Core_get_current_call' in msg or 'pylinphone_Call_from_native_ptr' in msg or ': keep alive sent to [' in msg): return method = getattr(logger, level) method(msg) if logger.getEffectiveLevel() <= 5: lin.set_log_handler(log_handler) def get(*args, **kwargs): return LinPhone(*args, **kwargs) class LinPhone(SipphoneAbstractBaseClass): @property def name(self): return 'linphone wrapper' @property def lib(self): return self.__Lib @property def core(self): return self.__Lib
from doorpi.sipphone.linphone_lib.CallBacks import LinphoneCallbacks from doorpi.sipphone.linphone_lib.Player import LinphonePlayer from doorpi.sipphone.linphone_lib.Recorder import LinphoneRecorder from doorpi.media.CreateDialTone import generate_dial_tone conf = DoorPi().config def log_handler(level, msg): if "pylinphone_Core_instance_method_iterate" in msg: return if "pylinphone_Core_get_current_call" in msg: return if "pylinphone_Call_from_native_ptr" in msg: return if ": keep alive sent to [" in msg: return method = getattr(logger, level) method(msg) if logger.getEffectiveLevel() <= 5: lin.set_log_handler(log_handler) def get(*args, **kwargs): return LinPhone(*args, **kwargs) class LinPhone(SipphoneAbstractBaseClass): @property def name(self): return 'linphone wrapper' @property def lib(self): return self.__Lib @property def core(self): return self.__Lib @property def recorder(self): return self.__recorder __recorder = None
from doorpi.sipphone.linphone_lib.Recorder import LinphoneRecorder from doorpi.media.CreateDialTone import generate_dial_tone conf = DoorPi().config def log_handler(level, msg): if "pylinphone_Core_instance_method_iterate" in msg: return if "pylinphone_Core_get_current_call" in msg: return if "pylinphone_Call_from_native_ptr" in msg: return if ": keep alive sent to [" in msg: return method = getattr(logger, level) method(msg) if logger.getEffectiveLevel() <= 5: lin.set_log_handler(log_handler) def get(*args, **kwargs): return LinPhone(*args, **kwargs) class LinPhone(SipphoneAbstractBaseClass): @property def name(self): return 'linphone wrapper' @property def lib(self): return self.__Lib
def __init__(self, username='', password='', whitelist=(), camera='', snd_capture='', snd_playback=''): # type: (string, string, list, string, string, string) -> object """ Main class, params are what you'd expect based on the names. :param username: :param password: :param whitelist: :param camera: :param snd_capture: :param snd_playback: """ logging.debug("__init__") logging.info( "Initializaing {product} System version {version}...".format( product=PRODUCTNAME, version=__version__)) # logging.debug("setting audio_dscp") # Pulling my values from "Commonly used DSCP Values" table in this article: # https://en.wikipedia.org/wiki/Differentiated_services # self.core.audio_dscp = 26 # self.core.video_dscp = 46 # 46 = High Priority Expedited Forwarding (EF) - TODO: Can this be lowered??? self.lastMessageTicks = time.time( ) # Wait one "cycle" so everything gets initialized self.lastEmailTicks = time.time() # via the TCP/IP (UDP/TLS/DTLS). self.dirname = '/var/log/jampi' if not os.path.exists(self.dirname): os.makedirs(self.dirname) # Initialize email self.smtp = smtplib.SMTP() # Initialize the motion detector. This is for the Zilog ePIR ZDot SBC. It has more features via serial mode, # so that's what we'll use here. GPIO.setwarnings(False) # Disable "this channel already in use", etc. GPIO.setmode(GPIO.BCM) # GPIO.setup(CAMLEDPIN, GPIO.OUT, initial=False) self.port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=2) s = "Waiting for motion sensor to come online...." print s logging.debug(s) # time.sleep(10) # Arduino example says need delays between commands for proper operation. (I suspect for 9600 bps it needs time.) time.sleep(5) self.imageDir = os.getcwd() # self.imageDir = os.path.join(os.getcwd(), 'security-images') if not os.path.exists(self.imageDir): os.makedirs(self.imageDir) self.videoDir = os.getcwd() # self.videoDir = os.path.join(os.getcwd(), 'security-videos') if not os.path.exists(self.videoDir): os.makedirs(self.videoDir) if 0 != PIRPIN: # Assume newer PIR device, signal hooked to PIRPIN logging.info("Sensor online... Turning on motion sensor...") logging.debug('calling GPIO.setup(PIRPIN, ...)') GPIO.setup(PIRPIN, GPIO.IN, GPIO.PUD_DOWN) # GPIO.add_event_detect(PIRPIN, GPIO.RISING, self.motion_detected, bouncetime=2000) # add rising edge detection on a channel print "Waiting for it to stabilize..." time.sleep(5) # while GPIO.input(PIRPIN)==1: # Current_State = 0 logging.info("PIR sensor is ready.") elif 0 != MDPIN: # let the ePIR sensor wake up. # time.sleep(10) # Arduino example says need delays between commands for proper operation. (I suspect for 9600 bps it needs time.) ch = 'U' while ch == 'U': # Repeat loop if not stablized. (ePIR replies with the character 'U' until the device becomes stable) # time.sleep(1) ch = self.port.read( 1 ) # Sends status command to ePIR and assigns reply from ePIR to variable ch. (READ ONLY function) logging.debug('ch = %s' % (ch, )) ch = readLineCR(self.port) s = "ePIR" if PIRPIN: s = "PIR" time.sleep(1) # print "%s sensor device online..." % (s, ) self.port.write('CM') # If we don't do this, the next readLineCR() will get garbage and will take an undetermined amount of time! time.sleep(1) result = readLineCR(self.port) if len(result) > 1: result = result[-1] if result == 'R': print 'ePIR reset!' elif result == 'M' or result == 'N': print 'Motion detection mode confirmed.' else: logging.debug('Result = "%s"' % (result, )) logging.debug("ch = '%s'\r\nDevice Ready" % (ch, )) logging.info("\nePIR sensor ready.") if 0 != LEDPIN: GPIO.setup( LEDPIN, GPIO.OUT ) # This light blinks when motion detected. Connect with long wires to monitor! # If the video and chat are not enough notifications. :) if 0 != LEDPINDOORBELL: GPIO.setup(LEDPINDOORBELL, GPIO.OUT) GPIO.output(LEDPINDOORBELL, 1) # Keep this LED ON. if 0 != MDPIN: GPIO.setup(MDPIN, GPIO.IN) self.doorbell_sound = None if 0 != BUTTONPIN: GPIO.setup(BUTTONPIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # try: # Background music is loaded here. # #pygame.mixer.pre_init(48000, -16, 2, 4096) # pygame.init() # pygame.mixer.init(44100, -16, 2, 2048) # self.doorbell_sound = pygame.mixer.Sound(doorBellSoundOgg) # except pygame.error, message: # logging.error("Cannot load doorbell sound: {doorbellsound}\r\n{exception}".format( # doorbellsound=doorBellSoundOgg, exception=traceback.format_exc())) global blinkCamLed val1 = blinkCamLed # Only time we force a blinking LED is during initialization, so you know it's ready. blinkCamLed = True if LEDPINDOORBELL: self.flash_led(ledpin=LEDPINDOORBELL) else: self.flash_led() blinkCamLed = val1 # Other member variables: self.imgStream = io.BytesIO() # time.sleep(2) #Allow time for ePIR warming-up self.quit = False self.username = "" self.current_call = None self.whitelist = whitelist callbacks = { 'call_state_changed': self.call_state_changed, } # Initialize & Configure the linphone core logging.basicConfig(level=logging.INFO) signal.signal(signal.SIGINT, self.signal_handler) linphone.set_log_handler(log_handler) self.core = linphone.Core.new(callbacks, None, None) self.core.max_calls = 3 self.core.video_adaptive_jittcomp_enabled = False self.core.adaptive_rate_control_enabled = False # self.core.quality_reporting_enabled = False # This fails straight away. self.core.echo_cancellation_enabled = False self.core.video_capture_enabled = True self.core.video_display_enabled = False # This will only show up on a composite/HDMI monitor. self.core.keep_alive_enabled = True # This is the default at time of writing. self.core.mic_enabled = True self.core.ringback = doorBellSoundWav # This causes terrible distortion on my system # self.core.ring = doorBellSoundWav # TODO: Use a separate sound for this. tr = self.core.sip_transports # assert_equals(tr.udp_port, 5060) # default config # assert_equals(tr.tcp_port, 5060) # default config tr.udp_port = 5063 tr.tcp_port = 5067 tr.tls_port = 32737 tr.dtls_port = 32738 self.core.sip_transports = tr tr = self.core.sip_transports logging.debug('Transports = UDP: %s, TCP %s, TLS %s, DTLS %s' % \ (tr.udp_port, tr.tcp_port, tr.tls_port, tr.dtls_port)) # tr = self.core.sip_transports # tr.dtls_port = 5060 # tr.tcp_port = 5061 # tr.udp_port = 5062 # tr.tls_port = 5063 # self.core.sip_transports = tr self.core.stun_server = 'stun.linphone.org' self.core.firewall_policy = linphone.FirewallPolicy.PolicyUseIce if len(camera): self.core.video_device = camera if len(snd_capture): self.core.capture_device = snd_capture if len(snd_playback): self.core.playback_device = snd_playback # Only enable PCMU, PCMA and speex audio codecs for codec in self.core.audio_codecs: if codec.mime_type in [ "PCMA", "PCMU" ]: # [, "speex", "opus", "VP8", "H264", "opus", "VP8", "H264"]: # Overkill! , "SILK" self.core.enable_payload_type(codec, True) logging.info("Adding codec %s..." % (codec.mime_type, )) else: self.core.enable_payload_type(codec, False) # Only enable VP8 video codecs for codec in self.core.video_codecs: if codec.mime_type in ["VP8"]: logging.info("Adding codec %s..." % (codec.mime_type, )) self.core.enable_payload_type(codec, True) else: self.core.enable_payload_type(codec, False) logging.debug("Configuring SIP account...") self.configure_sip_account(username, password) if talkToEm: espeak.synth('Security system is now on line.') time.sleep(3) self.configured = False
def log_handler(level, msg): if "pylinphone_Core_instance_method_iterate" in msg: return if "pylinphone_Core_get_current_call" in msg: return if "pylinphone_Call_from_native_ptr" in msg: return if ": keep alive sent to [" in msg: return method = getattr(logger, level) method(msg) if logger.getEffectiveLevel() <= 5: lin.set_log_handler(log_handler) def get(*args, **kwargs): return LinPhone(*args, **kwargs) class LinPhone(SipphoneAbstractBaseClass): @property def name(self): return "linphone wrapper" @property def lib(self): return self.__Lib
def __init__(self, username='', password='', whitelist=(), camera='', snd_capture='', snd_playback=''): # type: (string, string, list, string, string, string) -> object """ Main class, params are what you'd expect based on the names. :param username: :param password: :param whitelist: :param camera: :param snd_capture: :param snd_playback: """ logging.debug("__init__") logging.info( "Initializaing {product} System version {version}...".format(product=PRODUCTNAME, version=__version__)) # logging.debug("setting audio_dscp") # Pulling my values from "Commonly used DSCP Values" table in this article: # https://en.wikipedia.org/wiki/Differentiated_services # self.core.audio_dscp = 26 # self.core.video_dscp = 46 # 46 = High Priority Expedited Forwarding (EF) - TODO: Can this be lowered??? self.lastMessageTicks = time.time() # Wait one "cycle" so everything gets initialized self.lastEmailTicks = time.time() # via the TCP/IP (UDP/TLS/DTLS). self.dirname = '/var/log/jampi' if not os.path.exists(self.dirname): os.makedirs(self.dirname) # Initialize email self.smtp = smtplib.SMTP() # Initialize the motion detector. This is for the Zilog ePIR ZDot SBC. It has more features via serial mode, # so that's what we'll use here. GPIO.setwarnings(False) # Disable "this channel already in use", etc. GPIO.setmode(GPIO.BCM) # GPIO.setup(CAMLEDPIN, GPIO.OUT, initial=False) self.port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=2) s = "Waiting for motion sensor to come online...." print s logging.debug(s) # time.sleep(10) # Arduino example says need delays between commands for proper operation. (I suspect for 9600 bps it needs time.) time.sleep(5) self.imageDir = os.getcwd() # self.imageDir = os.path.join(os.getcwd(), 'security-images') if not os.path.exists(self.imageDir): os.makedirs(self.imageDir) self.videoDir = os.getcwd() # self.videoDir = os.path.join(os.getcwd(), 'security-videos') if not os.path.exists(self.videoDir): os.makedirs(self.videoDir) if 0 != PIRPIN: # Assume newer PIR device, signal hooked to PIRPIN logging.info("Sensor online... Turning on motion sensor...") logging.debug('calling GPIO.setup(PIRPIN, ...)') GPIO.setup(PIRPIN, GPIO.IN, GPIO.PUD_DOWN) # GPIO.add_event_detect(PIRPIN, GPIO.RISING, self.motion_detected, bouncetime=2000) # add rising edge detection on a channel print "Waiting for it to stabilize..." time.sleep(5) # while GPIO.input(PIRPIN)==1: # Current_State = 0 logging.info("PIR sensor is ready.") elif 0 != MDPIN: # let the ePIR sensor wake up. # time.sleep(10) # Arduino example says need delays between commands for proper operation. (I suspect for 9600 bps it needs time.) ch = 'U' while ch == 'U': # Repeat loop if not stablized. (ePIR replies with the character 'U' until the device becomes stable) # time.sleep(1) ch = self.port.read( 1) # Sends status command to ePIR and assigns reply from ePIR to variable ch. (READ ONLY function) logging.debug('ch = %s' % (ch,)) ch = readLineCR(self.port) s = "ePIR" if PIRPIN: s = "PIR" time.sleep(1) # print "%s sensor device online..." % (s, ) self.port.write('CM') # If we don't do this, the next readLineCR() will get garbage and will take an undetermined amount of time! time.sleep(1) result = readLineCR(self.port) if len(result) > 1: result = result[-1] if result == 'R': print 'ePIR reset!' elif result == 'M' or result == 'N': print 'Motion detection mode confirmed.' else: logging.debug('Result = "%s"' % (result,)) logging.debug("ch = '%s'\r\nDevice Ready" % (ch,)) logging.info("\nePIR sensor ready.") if 0 != LEDPIN: GPIO.setup(LEDPIN, GPIO.OUT) # This light blinks when motion detected. Connect with long wires to monitor! # If the video and chat are not enough notifications. :) if 0 != LEDPINDOORBELL: GPIO.setup(LEDPINDOORBELL, GPIO.OUT) GPIO.output(LEDPINDOORBELL, 1) # Keep this LED ON. if 0 != MDPIN: GPIO.setup(MDPIN, GPIO.IN) self.doorbell_sound = None if 0 != BUTTONPIN: GPIO.setup(BUTTONPIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # try: # Background music is loaded here. # #pygame.mixer.pre_init(48000, -16, 2, 4096) # pygame.init() # pygame.mixer.init(44100, -16, 2, 2048) # self.doorbell_sound = pygame.mixer.Sound(doorBellSoundOgg) # except pygame.error, message: # logging.error("Cannot load doorbell sound: {doorbellsound}\r\n{exception}".format( # doorbellsound=doorBellSoundOgg, exception=traceback.format_exc())) global blinkCamLed val1 = blinkCamLed # Only time we force a blinking LED is during initialization, so you know it's ready. blinkCamLed = True if LEDPINDOORBELL: self.flash_led(ledpin=LEDPINDOORBELL) else: self.flash_led() blinkCamLed = val1 # Other member variables: self.imgStream = io.BytesIO() # time.sleep(2) #Allow time for ePIR warming-up self.quit = False self.username = "" self.current_call = None self.whitelist = whitelist callbacks = { 'call_state_changed': self.call_state_changed, } # Initialize & Configure the linphone core logging.basicConfig(level=logging.INFO) signal.signal(signal.SIGINT, self.signal_handler) linphone.set_log_handler(log_handler) self.core = linphone.Core.new(callbacks, None, None) self.core.max_calls = 3 self.core.video_adaptive_jittcomp_enabled = False self.core.adaptive_rate_control_enabled = False # self.core.quality_reporting_enabled = False # This fails straight away. self.core.echo_cancellation_enabled = False self.core.video_capture_enabled = True self.core.video_display_enabled = False # This will only show up on a composite/HDMI monitor. self.core.keep_alive_enabled = True # This is the default at time of writing. self.core.mic_enabled = True self.core.ringback = doorBellSoundWav # This causes terrible distortion on my system # self.core.ring = doorBellSoundWav # TODO: Use a separate sound for this. tr = self.core.sip_transports # assert_equals(tr.udp_port, 5060) # default config # assert_equals(tr.tcp_port, 5060) # default config tr.udp_port = 5063 tr.tcp_port = 5067 tr.tls_port = 32737 tr.dtls_port = 32738 self.core.sip_transports = tr tr = self.core.sip_transports logging.debug('Transports = UDP: %s, TCP %s, TLS %s, DTLS %s' % \ (tr.udp_port, tr.tcp_port, tr.tls_port, tr.dtls_port)) # tr = self.core.sip_transports # tr.dtls_port = 5060 # tr.tcp_port = 5061 # tr.udp_port = 5062 # tr.tls_port = 5063 # self.core.sip_transports = tr self.core.stun_server = 'stun.linphone.org' self.core.firewall_policy = linphone.FirewallPolicy.PolicyUseIce if len(camera): self.core.video_device = camera if len(snd_capture): self.core.capture_device = snd_capture if len(snd_playback): self.core.playback_device = snd_playback # Only enable PCMU, PCMA and speex audio codecs for codec in self.core.audio_codecs: if codec.mime_type in ["PCMA", "PCMU"]: # [, "speex", "opus", "VP8", "H264", "opus", "VP8", "H264"]: # Overkill! , "SILK" self.core.enable_payload_type(codec, True) logging.info("Adding codec %s..." % (codec.mime_type,)) else: self.core.enable_payload_type(codec, False) # Only enable VP8 video codecs for codec in self.core.video_codecs: if codec.mime_type in ["VP8"]: logging.info("Adding codec %s..." % (codec.mime_type,)) self.core.enable_payload_type(codec, True) else: self.core.enable_payload_type(codec, False) logging.debug("Configuring SIP account...") self.configure_sip_account(username, password) if talkToEm: espeak.synth('Security system is now on line.') time.sleep(3) self.configured = False
def linphonetester_log_handler(level, msg): import logging method = getattr(logging.getLogger("linphonetester"), level) if not msg.strip().startswith('[PYLINPHONE]'): msg = '[CORE] ' + msg method(msg) linphonetester_logger = logging.getLogger("linphonetester") handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname)s: %(message)s', '%H:%M:%S') handler.setFormatter(formatter) linphonetester_logger.addHandler(handler) linphone.set_log_handler(linphonetester_log_handler) def create_address(domain): addr = linphone.Address.new(None) assert addr != None addr.username = test_username assert_equals(addr.username, test_username) if domain is None: domain = test_route addr.domain = domain assert_equals(addr.domain, domain) addr.display_name = None addr.display_name = "Mr Tester" assert_equals(addr.display_name, "Mr Tester") return addr
def __init__(self, ENVIRON, snd_playback=''): #add callee parameter to the environment, for outgoing calls ENVIRON["callee"] = None self.TOPDIR = ENVIRON["topdir"] filename = os.path.join(self.TOPDIR, "static/sqlite/robotAI.sqlite") #get the module configuration info if os.path.isfile(filename): config = getConfigData(self.TOPDIR, "Phone") if "ERROR" in config: logger.debug("Error getting the sensor configuration: " + config["ERROR"]) else: debugFlag = getConfig(config, "Phone_2debug") self.camera = getConfig(config, "Phone_camera") self.snd_capture = getConfig(config, "Phone_snd_capture") self.admin = getConfig(config, "Phone_admin") username = getConfig(config, "Phone_account") password = getConfig(config, "Phone_password") self.ENVIRON = ENVIRON #self.SENSORQ = SENSORQ #self.MIC = MIC self.quit = False callbacks = {'call_state_changed': self.call_state_changed} #--------------------------------------- # Configure the linphone core #--------------------------------------- # Set debug level based on details in config DB self.logger = logging.getLogger(__name__) if debugFlag == 'TRUE': self.logger.level = logging.DEBUG logging.basicConfig(level=logging.DEBUG) else: self.logger.level = logging.INFO #logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.WARNING) linphone.set_log_handler(self.log_handler) signal.signal(signal.SIGINT, self.signal_handler) self.core = linphone.Core.new(callbacks, None, None) self.core.max_calls = 1 self.core.echo_cancellation_enabled = True self.core.video_capture_enabled = True self.core.keep_alive_enabled = True self.core.video_display_enabled = False self.core.stun_server = 'stun.linphone.org' self.core.ring = self.TOPDIR + "/static/audio/oldphone.wav" self.logger.debug("self.core.ring = " + self.core.ring) self.core.ringback = self.TOPDIR + "/static/audio/ringback.wav" self.logger.debug("self.core.ringback = " + self.core.ringback) # self.core.ice_enabled = True #if len(self.camera): # self.logger.debug("Camera = " + self.camera) # self.core.video_device = self.camera #if len(self.snd_capture): # self.logger.debug("Capture = " + self.snd_capture) # self.core.capture_device = self.snd_capture if len(snd_playback): self.logger.debug("Playback = " + snd_playback) self.core.playback_device = snd_playback # Only enable PCMU and PCMA audio codecs #--------------------------------------- for codec in self.core.audio_codecs: if codec.mime_type == "PCMA" or codec.mime_type == "PCMU": self.core.enable_payload_type(codec, True) else: self.core.enable_payload_type(codec, False) # Only enable VP8 video codec #--------------------------------------- for codec in self.core.video_codecs: if codec.mime_type == "VP8": self.core.enable_payload_type(codec, True) else: self.core.enable_payload_type(codec, False) self.configure_sip_account(username, password)
def __init__(self, main_log_level=logging.ERROR, module_log_level=logging.ERROR, button_pin=-1, ding_dong_file=None, username='', password='', trusted=[], camera='', sound_capture='', sound_playback=''): self.quit = False self.trusted = trusted self.ding_dong_file = ding_dong_file logging.basicConfig( format='%(levelname)s-%(name)s: %(asctime)s: %(message)s', level=module_log_level) self.logger = logging.getLogger('SmartDoorbell') self.logger.setLevel(main_log_level) signal.signal(signal.SIGINT, self.signal_handler) self.logger.debug('main_log_level = %d', main_log_level) self.logger.debug('module_log_level = %d', module_log_level) self.logger.debug('button_pin = %d', button_pin) self.logger.debug('ding_dong_file = %s', ding_dong_file) self.logger.debug('username = %s', username) self.logger.debug('password = %s', password) self.logger.debug('trusted = %s', trusted) self.logger.debug('camera = %s', camera) self.logger.debug('sound_capture = %s', sound_capture) self.logger.debug('sound_playback = %s', sound_playback) # Configure the GPIO h/w for push button detection (if button is connected - value >=0) self.button_pin = button_pin if self.button_pin >= 0: GPIO.setmode(GPIO.BCM) GPIO.setup(self.button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Configure the linphone core linphone.set_log_handler(self.log_handler) callbacks = { 'call_state_changed': self.call_state_changed, } self.core = linphone.Core.new(callbacks, None, None) self.core.max_calls = 1 self.core.echo_cancellation_enabled = False self.core.video_capture_enabled = True self.core.video_display_enabled = False if len(camera): self.core.video_device = camera if len(sound_capture): self.core.capture_device = sound_capture if len(sound_playback): self.core.playback_device = sound_playback # Only enable PCMU and PCMA audio codecs for codec in self.core.audio_codecs: if codec.mime_type == "PCMA" or codec.mime_type == "PCMU": self.core.enable_payload_type(codec, True) else: self.core.enable_payload_type(codec, False) # Only enable VP8 video codec for codec in self.core.video_codecs: if codec.mime_type == "VP8": self.core.enable_payload_type(codec, True) else: self.core.enable_payload_type(codec, False) # Configure the SIP account proxy_cfg = self.core.create_proxy_config() proxy_cfg.identity_address = self.core.create_address( 'sip:{username}@sip.linphone.org'.format(username=username)) proxy_cfg.server_addr = 'sip:sip.linphone.org;transport=tls' proxy_cfg.register_enabled = True self.core.add_proxy_config(proxy_cfg) auth_info = self.core.create_auth_info(username, None, password, None, None, 'sip.linphone.org') self.core.add_auth_info(auth_info)
def __init__(self): self.logger = logging.getLogger() handler = JournalHandler(SYSLOG_IDENTIFIER='gwnphone') self.logger.addHandler(handler) self.logger.setLevel(logging.INFO) self.settings_service = dbus.SystemBus().get_object( 'com.getwellnetwork.plc.clerk1', '/com/getwellnetwork/plc/clerk1/Settings') try: self.rdp_service = dbus.SessionBus().get_object( 'com.getwellnetwork.plc.rdp1', '/com/getwellnetwork/plc/rdp1/Rdp') dbus.SessionBus().add_signal_receiver( self._ext_dnd, signal_name='Launched', member_keyword='sig_name', dbus_interface='com.getwellnetwork.plc.rdp1.Rdp1') dbus.SessionBus().add_signal_receiver( self._ext_dnd, signal_name='Destroyed', member_keyword='sig_name', dbus_interface='com.getwellnetwork.plc.rdp1.Rdp1') except Exception as e: self.rdp_service = None self.logger.error('no rdp service available') self.conf_path = {} self.conf_path['port'] = 'config.phone.port' self.conf_path['server'] = 'config.phone.server' self.conf_path['phone_number'] = 'config.location.phone_number' self.conf_path[ 'username'] = '******' self.conf_path[ 'password'] = '******' try: phone_conf = self.settings_service.get_dbus_method( 'ReadAll', 'com.getwellnetwork.plc.clerk1.Settings1')('config.phone') location_conf = self.settings_service.get_dbus_method( 'ReadAll', 'com.getwellnetwork.plc.clerk1.Settings1')('config.location') self.port = phone_conf[self.conf_path['port']] self.server = phone_conf[self.conf_path['server']] self.phone_number = location_conf[self.conf_path['phone_number']] self.username = location_conf.get(self.conf_path['username']) if not self.username: self.username = self.phone_number[-4:] self.password = location_conf.get(self.conf_path['password']) if not self.password: self.password = '******' except Exception as e: self.logger.error( 'not configured for phone use, exiting: {}'.format(e)) sys.exit(0) self.dial_tone_timer = None self.factory = linphone.Factory.get() linphone.set_log_handler(log_handler) # PLC-5817 individual audio codecs are enabled and disabled from this static config file self.core = self.factory.create_core( None, None, '/usr/share/gwn-phone/gwn-phone.conf') self.callbacks = self.factory.create_core_cbs() self.callbacks.call_state_changed = self._call_state_changed self.callbacks.global_state_changed = self._global_state_changed self.callbacks.registration_state_changed = self._registration_state_changed self.core.add_callbacks(self.callbacks) auth_info = self.core.create_auth_info(self.username, None, self.password, None, None, self.server) self.core.add_auth_info(auth_info) self.proxy_cfg = self.core.create_proxy_config() self.proxy_cfg.identity_address = linphone.Address.new( 'sip:{}@{}'.format(self.username, self.server)) self.proxy_cfg.identity_address.port = int(self.port) self.proxy_cfg.server_addr = 'sip:{}:{}'.format(self.server, self.port) self.sip_proxy = '{}:{}'.format(self.server, self.port) self.proxy_cfg.register_enabled = True self.core.add_proxy_config(self.proxy_cfg) self.core.ring_during_incoming_early_media = False self.core.remote_ringback_tone = None # set user agent string to make debugging at the SIP packet level easier self.core.set_user_agent('gwn-phone', '0.0.16') self.core.ringback = '/usr/share/gwn-phone/sound/ringback.wav' self.dial_tone = '/usr/share/gwn-phone/sound/dial_tone.wav' self.registration_state = linphone.RegistrationState._None self.core.ring = None self.core.terminate_all_calls() self.current_call = None self.core.max_calls = 1 self.dnd = False self.dnd_ext = False self.core.use_info_for_dtmf = False self.core.use_rfc2833_for_dtmf = False sound_dev = self.core.sound_devices[0] self.core.playback_device = sound_dev self.core.capture_device = sound_dev self.core.ringer_device = sound_dev self.core.mic_enabled = True self.iterate_timer = gobject.timeout_add(100, self._iterate) bus_name = dbus.service.BusName(BUSNAME, bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name=bus_name, object_path=OBJECTPATH) self.logger.info('connected to session bus')
def main(): logging.basicConfig(level=logging.INFO) app = QApplication(sys.argv) def log_handler(level, msg): method = getattr(logging, level) method(msg) def global_state_changed(*args, **kwargs): logging.warning("global_state_changed: %r %r" % (args, kwargs)) def registration_state_changed(core, call, state, message): logging.warning("registration_state_changed: " + str(state) + ", " + message) def call_state_changed(core, call, state, message): logging.warning("call_state_changed: " + str(state) + ", " + message) if state == linphone.CallState.IncomingReceived: dialer.call_incoming(call) if state == linphone.CallState.OutgoingProgress: dialer.call_state = state if state == linphone.CallState.Connected: dialer.call = call dialer.call_state = state if state == linphone.CallState.End: dialer.num_bar.setText('') if state == linphone.CallState.Released: dialer.incoming_terminated() callbacks = { 'global_state_changed': global_state_changed, 'registration_state_changed': registration_state_changed, 'call_state_changed': call_state_changed, } linphone.set_log_handler(log_handler) core = linphone.Core.new(callbacks, None, None) address = linphone.Address.new("sip:[email protected]") auth = linphone.AuthInfo.new(None, None, None, None, None, None) auth.username = "******" auth.passwd = "g2RfaXrwNg" auth.userid = "zlE7Ln8bvD" core.add_auth_info(auth) proxy_cfg = core.create_proxy_config() core.provisioning_uri = "https://shookke.fl.3cx.us/provisioning/wuvqph5halzuac4" proxy_cfg.identity_address = address proxy_cfg.server_addr = "sip:shookke.fl.3cx.us" proxy_cfg.register_enabled = True core.add_proxy_config(proxy_cfg) core.terminate_all_calls() audio = core.sound_devices #core.playback_device = audio[1] core.mic_gain_db = 11.0 core.ring = '/usr/local/lib/python2.7/dist-packages/linphone/share/sounds/linphone/rings/orig.wav' print(audio) iterate_timer = QTimer() iterate_timer.timeout.connect(core.iterate) #stop_timer = QTimer() #stop_timer.timeout.connect(app.quit) iterate_timer.start(20) #stop_timer.start(60000) dialer = Dialer(core) exitcode = app.exec_() sys.exit(exitcode)
def initLinphone(self): callbacks = linphone.Factory().get().create_core_cbs() callbacks.call_state_changed = self.call_state_changed linphone.set_log_handler(self.log_handler) self.core_ = linphone.Factory().get().create_core( callbacks, None, None) self.core_.max_calls = 1 self.core_.echo_cancellation_enabled = False self.core_.video_capture_enabled = False self.core_.video_display_enabled = False # STUN server should be independent of provider, so we # hardcode it here. self.core_.nat_policy.stun_server = 'stun.linphone.org' self.core_.nat_policy.ice_enabled = True # Manually configure ringback tone, so we can be sure that # it is found. self.core_.remote_ringback_tone = RING_BACK self.core_.ringback = RING_BACK logging.info('Setting up SIP configuration.') self.standard_gateway_ = '' # We keep track of usernames configured for the various gateways, # and accept incoming calls only if there is a match. self.accepted_usernames_ = set() for provider in self.config_.sections(): username = self.config_.get(provider, 'Username') self.accepted_usernames_.add(username) password = self.config_.get(provider, 'Password') sip_gateway = self.config_.get(provider, 'Gateway') is_default = False try: is_default = self.config_.getboolean(provider, 'default') except: pass user_id = None try: user_id = self.config_.get(provider, 'Userid') except: pass proxy_config = self.core_.create_proxy_config() proxy_config.identity_address = self.core_.create_address( 'sip:{username}@{sip_gateway}'.format(username=username, sip_gateway=sip_gateway)) proxy_config.server_addr = 'sip:{sip_gateway}'.format( sip_gateway=sip_gateway) proxy_config.register_enabled = True self.core_.add_proxy_config(proxy_config) logging.info( 'Registering {username}@{sip_gateway},default={is_default}'. format(username=username, sip_gateway=sip_gateway, is_default=is_default)) if is_default or not self.standard_gateway_: # If we have a default, use it. Otherwise, just pick the first one. self.core_.default_proxy_config = proxy_config self.standard_gateway_ = sip_gateway auth_info = self.core_.create_auth_info(username, user_id, password, None, None, sip_gateway) self.core_.add_auth_info(auth_info) # No prospective call yet. self.current_call_ = None
self.core.default_proxy_config = proxy_cfg auth = self.core.create_auth_info("taubsi78", "taubsi78", "aquarium", "", "", "") self.core.add_auth_info(auth) def registration_changed(self, core, call, state, message): print("Registration State: " + str(state) + ":" + message) def call_changed(self, core, call, state, message): print("Call State: " + str(state) + ":" + message) if (state == linphone.CallState.OutgoingProgress): self.phone.trans(self.phone.outgoing) if (state == linphone.CallState.End or state == linphone.CallState.Error): self.phone.trans(self.phone.call_closed) def iterate(self): self.core.iterate() def call(self, addr): self.core.invite(addr) def log_handler(level, msg): method = getattr(logging, level) method(msg) linphone.set_log_handler(log_handler)