<commit_before># import npyscreen
import time
import sys
import traceback

## tempcommand: temperature chamber controller base class
class tempcommand():
    ## @var commandset
    #defines commands and callback functions
    commandset = {}

    ## @var commandList
    #contains whole command list read from script
    commandList = []

    ## @var argumentList
    #contains whole argument list read from script
    argumentList = []

    ## constructor
    def __init__(self):
        self.commandset = {}

    ## parse()
    # makes whole command list from script, cut off after first EOF,
    # destruct loops(break_loop()) and execute them all(parse_list())
    # @param script script (command list) file
    # @param logfile log output file
    def parse(self, script, logfile):
        count_eof = 0
        self.make_list(script)
        if(self.commandList.count("EOF")>1):
            count_eof = self.commandList.index("EOF")
            self.commandList = self.commandList[:count_eof]
            self.argumentList = self.argumentList[:count_eof]
        if(self.commandList.count("FOR")!=self.commandList.count("LOOP")):
            print "error",commandlist.count("FOR"),argumentlist.count("LOOP")
        else:
            self.break_loop(self.commandList,self.argumentList)
            self.parse_list(self.commandList,self.argumentList,logfile)
        return True

    ## make_list()
    # called from parse()
    # makes command list from read script
    # @param script script(command list) file
    def make_list(self, script):
        for line in script.split('\n'):
            for words in line.split('//')[0].split(','):
                word = ["".join(words.split())]
                for command in word:
                    command = command.upper()
                    if command.split()==[]:continue
                    for comd, func in self.commandset.iteritems():
                        read = command.split(comd)
                        if(read[0])=='':
                            try:
                                self.commandList.append(comd)
                                self.argumentList.append(read[1])

                            except:
                                print(
                                "".join(traceback.format_tb(sys.exc_info()[2]))+": "\
                                +str(sys.exc_info()[1]))

                    else: continue
                    break

                else:
                    continue
                break
            else:
                continue
            break

        if(self.commandList.count("FOR")!=self.commandList.count("LOOP")):
            print "error",commandlist.count("FOR"),argumentlist.count("LOOP")

        return True

#0. list up index number(s) of both FOR and LOOP
#1. pop *biggest* FOR and get index number
#2. scan LOOP from smaller number
#3. find the best LOOP; the first LOOP which has bigger index number than FOR's one
#4. pop the LOOP
#5. destract the loop
#6. if FOR remains in the whole list, go to #1

    ## break_loop()
    # called from parse()
    # find FOR loop and cut then call _break_loop() to destruct
    # @param c_list command list
    # @param a_list argument list
    # @return destructed (c_list, a_list)
    def break_loop(self, c_list, a_list):
        c_temp = c_list[:]
        F_index = []
        L_index = []
        result = []
        c_result = []
        a_result = []
        """count FORs and LOOPs"""
        if(c_list.count("FOR") > 0): # if any FOR found
            for hoge in range(len(c_list)): # search in command list
                if c_list[hoge] == "FOR": # if FOR is found
                    F_index.append(hoge) # index added into FOR's list
                elif c_list[hoge] == "LOOP": # if LOOP is found
                    L_index.append(hoge) # index added into LOOP's list
            while(len(F_index) > 0): # while any FOR remains
                hoge = F_index.pop() # pop FOR's biggest index
                for foo in range(len(L_index)): # search over remaining LOOPs
                    if L_index[foo] > hoge: # if index(LOOP) > max_index(FOR)
                        break # break for loop

                foo = L_index.pop(foo) # pop hit LOOP index
                result.append([hoge,foo]) # result = [ [...], [...], [max_index(FOR), hit_index(LOOP)] ]
            result.reverse() # result = [ [smallest FOR], [2nd smallest], [...], ..., [largest FOR] ]
            result = result.pop() # result = [ largest FOR pair ]
            c_result,a_result = self._break_loop(   c_list[result[0]:result[1]],
                                                    a_list[result[0]:result[1]] )

            for hoge in range(len(c_list[result[0]:result[1]+1])):
                c_list.pop(result[0])
                a_list.pop(result[0])
            for hoge in range(len(c_result)):
                c_list.insert(result[0], c_result.pop())
                a_list.insert(result[0], a_result.pop())
            self.break_loop(c_list, a_list)

        return c_list, a_list
        pass

    ## _break_loop
    # called from break_loop()
    # destructs FOR loop into command and argument list
    # @param c_list command list
    # @param a_list argument list
    def _break_loop(self, c_list, a_list):
        c_result = []
        a_result = []
        var = a_list[0].split(";")
        a_lst = var[0].split("+")
        c_lst = var[1].split("|")
        for arg in a_lst:
            for cmd in c_lst:
                for comd, func in self.commandset.iteritems():
                    read = (str(cmd)+str(arg)).split(comd)
                    if(read[0])=='':
                        c_result.append(comd)
                        a_result.append(read[1])
            for hoge in c_list[1:]:
                c_result.append(hoge)
            for foo in a_list[1:]:
                a_result.append(foo)

        return (c_result,a_result)
        pass

    ## parse_list()
    # called from parse()
    # executes all listed commands
    # @param comlist command list
    # @param arglist argument list
    # @param logfile log output file
    def parse_list(self,comlist,arglist,logfile):
        execute = -1
        cnt = 0
        for command in comlist:
            try:
                execute = self.commandset[command][0](arglist[cnt])
            except:
                print("".join(traceback.format_tb(sys.exc_info()[2]))+": "
                    +str(sys.exc_info()[1]))

            logfile.write('\n')
            if execute==-1:break
            cnt+=1

        return True

    ## add_command
    # adds command and casllback functions as dictionary pair
    # @param command command; must be large character
    # @param func callback function; should be started with '_'
    def add_command(self,command,func):
        self.commandset[command] = [func]

    def _eof(self,dummy = -1):
        print 'EndOfFile'
        return -1

    commandset["EOF"] = [_eof]

    def _temp(self,temp = 30):
        print 'set temp: '+temp+' oC'
        return 0

    commandset["TEMP"] = [_temp]

    def _sample(self,dummy = -1):
        print 'Sample'
        return 0

    commandset["SAMPLE"] = [_sample]

    def _suspend(self,dummy = -1):
        print 'Suspend'
        return 0

    commandset["SUSPEND"] = [_suspend]

    def _volt(self,v = 3.0):
        print 'set voltage: '+v
        return 0

    commandset["VOLT"] = [_volt]

    def _delay(self,_wait = 1):
        print 'wait for: '+_wait+' minutes'
        return 0

    commandset["DELY"] = [_delay]

    def _kikusui(self,current = 0.001):
        print 'set current: '+current+' A'
        return 0

    commandset["KIKU"] = [_kikusui]

    def _base(self,baseaddr = 0x90):
        print 'set base address: 0x'+baseaddr
        return 0

    commandset["BASE"] = [_base]

    def _ulibase(self,argument):
        ulichan,ulibase= argument.split('=')
        print 'i2c slave address set: 0x%X of channel %d'%(int(ulibase,16),int(ulichan,16))
        return 0

    commandset["UBASE"] = [_ulibase]

    def _register(self,argument):
        i2creg,i2cdata = argument.split('=')
        print 'reg address = 0x%03X, data = 0x%02X' %( int(i2creg,16),int(i2cdata,16) )
        return 0

    commandset["REG"] = [_register]

    def _chanset(self,channels):
        print 'set channels @'+channels
        return 0

    commandset["CHAN"] = [_chanset]

    def _repeat(self,times = 1):
        print 'repeat '+times+' times'
        return 0

    commandset["REPEAT"] = [_repeat]

    def _loop(self,dummy = -1):
        print 'loop'
        return 0

    commandset["LOOP"] = [_loop]

if __name__ == '__main__':
    import tempcommand
    def _temp(temp = 30):
        print 'set temp: '+str(temp)+' oC'
        return 0

    def _for(argument = '1'):
        print argument
        var = argument.split(";")
        lst = var[0].split("+")
        for var[0] in lst:
            self.lpHeader.append(str(var[1])+str(var[0]))
        return 0

    def _loop(dummy = '-1'):
        if (self.isInLoop!=[]):#==True):
            self.isInLoop.pop()
            for head in self.lpHeader:
                self.parse(head,self._logfile)
                for commd in self.lpContain:
                    self.parse(commd,self._logfile)
        return 0

    def _sample(dummy = -1):
#        global parser
#        if (parser.isInLoop!=[]):
#            parser.lpContain.append("SAMPLE")
#            print 'Sample in loop'
#        else:
        print 'Sample'
        return 0

    def _register(argument):
        global parser
        i2creg,i2cdata = argument.split('=')
#        if (parser.isInLoop!=[]):
#            parser.lpContain.append("REG"+argument)
#            print 'reg address = 0x%03X, data = 0x%02X in inner loop' %( int(i2creg,16),int(i2cdata,16) )
#        else:
        print 'reg address = 0x%03X, data = 0x%02X' %( int(i2creg,16),int(i2cdata,16) )
        return 0

    def _chanset(channels):
        global parser
#        if (parser.isInLoop!=[]):
#            parser.lpContain.append("CHAN"+channels)
#            print 'set channels @'+channels
#        else:
        print 'set channels @'+channels
        return 0

    def _delay(_wait = 1):
        global parser
#        if (parser.isInLoop!=[]):
#            parser.lpContain.append("DELY"+_wait)
#            print 'wait for: '+_wait+' minutes'
#        else:
        print 'wait for: '+_wait+' minutes'
        return 0

    def _repeat(times = 1):
        print 'repeat '+times+' times'
        return 0

    try:
        parser = tempcommand.tempcommand()
        logfile = open("hoge.log",'a')
        parser.add_command("TEMP",parser._temp)
        parser.add_command("EOF",parser._eof)
        parser.add_command("FOR",_for)
        parser.add_command("SAMPLE",_sample)
        parser.add_command("LOOP",_loop)
        parser.add_command("REG",_register)
        parser.add_command("CHAN",_chanset)
        parser.add_command("DELY",_delay)
#        print "_command_",parser.commandList
#        print "_argument_",parser.argumentList
        parser.make_list(
            """
            chan105+110
            reg00=ff
            for -40+0+100; TEMP
                dely1
                sample
                for 00+02+04; reg00=
                    sample
                LOOP
                for 0c+0e; reg02=
                    for 00+02+04; reg01=|regAA=
                        sample
                    LOOP
                LOOP
                suspend
            LOOP
            suspend
            EOF
            sample
            """
        )
#        print parser.commandList
        parser.break_loop(parser.commandList,parser.argumentList)
        parser.parse_list(parser.commandList,parser.argumentList,logfile)
#        raw_input("hoge")
#        reverse=parser.commandList[:]
#        reverse.reverse()
#        print reverse
#        hitp=parser.commandList.index('FOR')
#        hitn=reverse.index('LOOP')
#        parser.parse(
#            """
#            for -40+-20+0+20+30+40+60+80+100+120+140; TEMP
#                dely1
#                chan105,reg00=ff,SAMPLE
#                chan106,regff=00,SAMPLE
#            loop
#            EOF
#            """,
#            logfile)
    except:
        raw_input(str(sys.exc_info()[1]))
    finally:
        print("-=-=- debug mode done. -=-=-")
<commit_msg>remove a comment out; add spaces<commit_after># import npyscreen
import time
import sys
import traceback

## tempcommand: temperature chamber controller base class
class tempcommand():
    ## @var commandset
    #defines commands and callback functions
    commandset = {}

    ## @var commandList
    #contains whole command list read from script
    commandList = []

    ## @var argumentList
    #contains whole argument list read from script
    argumentList = []

    ## constructor
    def __init__(self):
        self.commandset = {}

    ## parse()
    # makes whole command list from script, cut off after first EOF,
    # destruct loops(break_loop()) and execute them all(parse_list())
    # @param script script (command list) file
    # @param logfile log output file
    def parse(self, script, logfile):
        count_eof = 0
        self.make_list(script)
        if(self.commandList.count("EOF")>1):
            count_eof = self.commandList.index("EOF")
            self.commandList = self.commandList[:count_eof]
            self.argumentList = self.argumentList[:count_eof]
        if(self.commandList.count("FOR")!=self.commandList.count("LOOP")):
            print "error",commandlist.count("FOR"),argumentlist.count("LOOP")
        else:
            self.break_loop(self.commandList,self.argumentList)
            self.parse_list(self.commandList,self.argumentList,logfile)
        return True

    ## make_list()
    # called from parse()
    # makes command list from read script
    # @param script script(command list) file
    def make_list(self, script):
        for line in script.split('\n'):
            for words in line.split('//')[0].split(','):
                word = ["".join(words.split())]
                for command in word:
                    command = command.upper()
                    if command.split()==[]:continue
                    for comd, func in self.commandset.iteritems():
                        read = command.split(comd)
                        if(read[0])=='':
                            try:
                                self.commandList.append(comd)
                                self.argumentList.append(read[1])

                            except:
                                print(
                                "".join(traceback.format_tb(sys.exc_info()[2]))+": "\
                                +str(sys.exc_info()[1]))

                    else: continue
                    break

                else:
                    continue
                break
            else:
                continue
            break

        if(self.commandList.count("FOR")!=self.commandList.count("LOOP")):
            print "error",commandlist.count("FOR"),argumentlist.count("LOOP")

        return True

#0. list up index number(s) of both FOR and LOOP
#1. pop *biggest* FOR and get index number
#2. scan LOOP from smaller number
#3. find the best LOOP; the first LOOP which has bigger index number than FOR's one
#4. pop the LOOP
#5. destract the loop
#6. if FOR remains in the whole list, go to #1

    ## break_loop()
    # called from parse()
    # find FOR loop and cut then call _break_loop() to destruct
    # @param c_list command list
    # @param a_list argument list
    # @return destructed (c_list, a_list)
    def break_loop(self, c_list, a_list):
        c_temp = c_list[:]
        F_index = []
        L_index = []
        result = []
        c_result = []
        a_result = []
        """count FORs and LOOPs"""
        if(c_list.count("FOR") > 0): # if any FOR found
            for hoge in range(len(c_list)): # search in command list
                if c_list[hoge] == "FOR": # if FOR is found
                    F_index.append(hoge) # index added into FOR's list
                elif c_list[hoge] == "LOOP": # if LOOP is found
                    L_index.append(hoge) # index added into LOOP's list
            while(len(F_index) > 0): # while any FOR remains
                hoge = F_index.pop() # pop FOR's biggest index
                for foo in range(len(L_index)): # search over remaining LOOPs
                    if L_index[foo] > hoge: # if index(LOOP) > max_index(FOR)
                        break # break for loop

                foo = L_index.pop(foo) # pop hit LOOP index
                result.append([hoge,foo]) # result = [ [...], [...], [max_index(FOR), hit_index(LOOP)] ]
            result.reverse() # result = [ [smallest FOR], [2nd smallest], [...], ..., [largest FOR] ]
            result = result.pop() # result = [ largest FOR pair ]
            c_result,a_result = self._break_loop(   c_list[result[0]:result[1]],
                                                    a_list[result[0]:result[1]] )

            for hoge in range(len(c_list[result[0]:result[1]+1])):
                c_list.pop(result[0])
                a_list.pop(result[0])
            for hoge in range(len(c_result)):
                c_list.insert(result[0], c_result.pop())
                a_list.insert(result[0], a_result.pop())
            self.break_loop(c_list, a_list)

        return c_list, a_list
        pass

    ## _break_loop
    # called from break_loop()
    # destructs FOR loop into command and argument list
    # @param c_list command list
    # @param a_list argument list
    def _break_loop(self, c_list, a_list):
        c_result = []
        a_result = []
        var = a_list[0].split(";")
        a_lst = var[0].split("+")
        c_lst = var[1].split("|")
        for arg in a_lst:
            for cmd in c_lst:
                for comd, func in self.commandset.iteritems():
                    read = (str(cmd)+str(arg)).split(comd)
                    if(read[0])=='':
                        c_result.append(comd)
                        a_result.append(read[1])
            for hoge in c_list[1:]:
                c_result.append(hoge)
            for foo in a_list[1:]:
                a_result.append(foo)

        return (c_result,a_result)
        pass

    ## parse_list()
    # called from parse()
    # executes all listed commands
    # @param comlist command list
    # @param arglist argument list
    # @param logfile log output file
    def parse_list(self,comlist,arglist,logfile):
        execute = -1
        cnt = 0
        for command in comlist:
            try:
                execute = self.commandset[command][0](arglist[cnt])
            except:
                print("".join(traceback.format_tb(sys.exc_info()[2]))+": "
                    +str(sys.exc_info()[1]))

            logfile.write('\n')
            if execute==-1:break
            cnt+=1

        return True

    ## add_command
    # adds command and casllback functions as dictionary pair
    # @param command command; must be large character
    # @param func callback function; should be started with '_'
    def add_command(self,command,func):
        self.commandset[command] = [func]

    def _eof(self,dummy = -1):
        print 'EndOfFile'
        return -1

    commandset["EOF"] = [_eof]

    def _temp(self,temp = 30):
        print 'set temp: '+temp+' oC'
        return 0

    commandset["TEMP"] = [_temp]

    def _sample(self,dummy = -1):
        print 'Sample'
        return 0

    commandset["SAMPLE"] = [_sample]

    def _suspend(self,dummy = -1):
        print 'Suspend'
        return 0

    commandset["SUSPEND"] = [_suspend]

    def _volt(self,v = 3.0):
        print 'set voltage: '+v
        return 0

    commandset["VOLT"] = [_volt]

    def _delay(self,_wait = 1):
        print 'wait for: '+_wait+' minutes'
        return 0

    commandset["DELY"] = [_delay]

    def _kikusui(self,current = 0.001):
        print 'set current: '+current+' A'
        return 0

    commandset["KIKU"] = [_kikusui]

    def _base(self,baseaddr = 0x90):
        print 'set base address: 0x'+baseaddr
        return 0

    commandset["BASE"] = [_base]

    def _ulibase(self,argument):
        ulichan,ulibase = argument.split('=')
        print 'i2c slave address set: 0x%X of channel %d'%(int(ulibase,16),int(ulichan,16))
        return 0

    commandset["UBASE"] = [_ulibase]

    def _register(self,argument):
        i2creg,i2cdata = argument.split('=')
        print 'reg address = 0x%03X, data = 0x%02X' %( int(i2creg,16),int(i2cdata,16) )
        return 0

    commandset["REG"] = [_register]

    def _chanset(self,channels):
        print 'set channels @'+channels
        return 0

    commandset["CHAN"] = [_chanset]

    def _repeat(self,times = 1):
        print 'repeat '+times+' times'
        return 0

    commandset["REPEAT"] = [_repeat]

    def _loop(self,dummy = -1):
        print 'loop'
        return 0

    commandset["LOOP"] = [_loop]

if __name__ == '__main__':
    import tempcommand
    def _temp(temp = 30):
        print 'set temp: '+str(temp)+' oC'
        return 0

    def _for(argument = '1'):
        print argument
        var = argument.split(";")
        lst = var[0].split("+")
        for var[0] in lst:
            self.lpHeader.append(str(var[1])+str(var[0]))
        return 0

    def _loop(dummy = '-1'):
        if (self.isInLoop!=[]):#==True):
            self.isInLoop.pop()
            for head in self.lpHeader:
                self.parse(head,self._logfile)
                for commd in self.lpContain:
                    self.parse(commd,self._logfile)
        return 0

    def _sample(dummy = -1):
#        global parser
#        if (parser.isInLoop!=[]):
#            parser.lpContain.append("SAMPLE")
#            print 'Sample in loop'
#        else:
        print 'Sample'
        return 0

    def _register(argument):
        global parser
        i2creg,i2cdata = argument.split('=')
#        if (parser.isInLoop!=[]):
#            parser.lpContain.append("REG"+argument)
#            print 'reg address = 0x%03X, data = 0x%02X in inner loop' %( int(i2creg,16),int(i2cdata,16) )
#        else:
        print 'reg address = 0x%03X, data = 0x%02X' %( int(i2creg,16),int(i2cdata,16) )
        return 0

    def _chanset(channels):
        global parser
#        if (parser.isInLoop!=[]):
#            parser.lpContain.append("CHAN"+channels)
#            print 'set channels @'+channels
#        else:
        print 'set channels @'+channels
        return 0

    def _delay(_wait = 1):
        global parser
#        if (parser.isInLoop!=[]):
#            parser.lpContain.append("DELY"+_wait)
#            print 'wait for: '+_wait+' minutes'
#        else:
        print 'wait for: '+_wait+' minutes'
        return 0

    def _repeat(times = 1):
        print 'repeat '+times+' times'
        return 0

    try:
        parser = tempcommand.tempcommand()
        logfile = open("hoge.log",'a')
        parser.add_command("TEMP",parser._temp)
        parser.add_command("EOF",parser._eof)
        parser.add_command("FOR",_for)
        parser.add_command("SAMPLE",_sample)
        parser.add_command("LOOP",_loop)
        parser.add_command("REG",_register)
        parser.add_command("CHAN",_chanset)
        parser.add_command("DELY",_delay)
        # print "_command_",parser.commandList
        # print "_argument_",parser.argumentList
        parser.make_list(
            """
            chan105+110
            reg00=ff
            for -40+0+100; TEMP
                dely1
                sample
                for 00+02+04; reg00=
                    sample
                LOOP
                for 0c+0e; reg02=
                    for 00+02+04; reg01=|regAA=
                        sample
                    LOOP
                LOOP
                suspend
            LOOP
            suspend
            EOF
            sample
            """
        )
        # print parser.commandList
        parser.break_loop(parser.commandList,parser.argumentList)
        parser.parse_list(parser.commandList,parser.argumentList,logfile)
    except:
        raw_input(str(sys.exc_info()[1]))
    finally:
        print("-=-=- debug mode done. -=-=-")
<|endoftext|>


<commit_before>#!/usr/bin/env python
# Author: Donald Merand for Explo (http://www.explo.org)
# Some bits are from Adafruit (see README)

import logging, time, subprocess, os
import toml

import Adafruit_GPIO.SPI as SPI
import Adafruit_MAX31855.MAX31855 as MAX31855

# Define a function to convert celsius to fahrenheit.
def c_to_f(c):
  return c * 9.0 / 5.0 + 32.0

# Grab config information from the log file (TOML format)
with open("/home/pi/raspberry-pi-temperature-monitor/config.toml") as conffile:
  conf = toml.loads(conffile.read())

# Check for a parameter + use it, otherwise set a default value
# Returns a string value, typically used like:
#   some_param = config_check('some_param', 'default_value')
def config_check(param, default):
  if conf.get(param):
    return conf.get(param)
  else:
    return default

# Set up logging if applicable
LOGFORMAT = "%(asctime)s\t%(message)s"
if conf.get('log_file'):
  log_file_rotate_size = config_check('log_file_rotate_size', 10000000)
  if conf.get('log_level') == 'DEBUG':
    logging.basicConfig(filename=conf['log_file'], format=LOGFORMAT, level=logging.DEBUG)
  else:
    # Default to INFO-level logging
    logging.basicConfig(filename=conf['log_file'], format=LOGFORMAT, level=logging.INFO)
  print("Logging to {0}".format(conf['log_file']))
else:
  # Just log to STDOUT
  logging.basicConfig(level=logging.INFO, format=LOGFORMAT)

# Check if the log size is greater than our max allowable size.
# Send it to HipChat if it's too big, and clear it out
def rotate_log_file():
  if conf.get('log_file'):
    log_size = os.stat(conf.get('log_file')).st_size

    if log_size > log_file_rotate_size:
      # Store log in hipchat
      if conf.get('hipchat').get('token') and conf.get('hipchat').get('room'):
        subprocess.call(['/usr/local/bin/hipfile', "--token", conf['hipchat']['token'], "--room", conf['hipchat']['room'], "--path", conf.get('log_file'), "--message", "{0} Temperature Log".format(device_name)])
      # Empty log file
      with open(conf.get('log_file'), 'w'):
        pass

# Set some default values
device_name = config_check('device_name', 'Unknown Device')
# Make sure the temperature has been out of range since the last period, to
# avoid spurious one-off temperature readings causing broadcasts
last_temp = None
poll_rate = config_check('poll_rate', 10)
# Set our temperature sensor based on the desired connection method
if conf.get('pi').get('connect_method') == "HARDWARE":
  sensor = MAX31855.MAX31855(spi=SPI.SpiDev(conf['pi']['SPI_PORT'], conf['pi']['SPI_DEVICE']))
else:
  # Default to software SPI
  sensor = MAX31855.MAX31855(conf['pi']['CLK'], conf['pi']['CS'], conf['pi']['DO'])

# Grab our (wireless) IP address so that we can send a link to the webcam if
# the temp is too high/low
ip_command = "ifconfig | awk 'BEGIN{ORS=\"\"}/wlan0/{getline;gsub(/addr:/,\"\",$2);print $2}'"
my_ip = str(subprocess.check_output(ip_command, shell=True))

# Loop measurements every second.
while True:
  rotate_log_file

  # now do the temperature reading
  temp = sensor.readTempC()
  #internal = sensor.readInternalC()
  logging.info("{0:0.3F}*C\t{1:0.3F}*F".format(temp, c_to_f(temp)))

  if temp > conf['temp']['max']:
    if last_temp > conf['temp']['max']:
      warning_text = "{0} WARNING: {1} is hot, potential fire risk: {2:0.3F}*F. Webcam: http://{3}?action=stream".format(conf.get('hipchat').get('notify_names'), device_name, c_to_f(temp), my_ip)
      logging.warning(warning_text)
      if conf.get('hipchat').get('room'):
        subprocess.call(["/usr/local/bin/hipchat", "-r", conf['hipchat']['room'], warning_text])
    time.sleep(30) #seconds
  if temp < conf['temp']['min'] :
    if last_temp < conf['temp']['min']:
      warning_text = "{0} WARNING: {1} is being exposed to freezing temperatures: {2:0.3F}*F. Webcam: http://{3}?action=stream".format(conf.get('hipchat').get('notify_names'), device_name, c_to_f(temp), my_ip)
      logging.warning(warning_text)
      if conf.get('hipchat').get('room'):
        subprocess.call(["/usr/local/bin/hipchat", "-r", conf['hipchat']['room'], warning_text])
    time.sleep(60 * 10) # wait 10 more minutes in this case to be sure
  else:
    # Temperature is in normal range, store it, wait regular polling amount + try again
    last_temp = temp
    time.sleep(poll_rate)
<commit_msg>add bogus temp catch<commit_after>#!/usr/bin/env python
# Author: Donald Merand for Explo (http://www.explo.org)
# Some bits are from Adafruit (see README)

import logging, time, subprocess, os
import toml

import Adafruit_GPIO.SPI as SPI
import Adafruit_MAX31855.MAX31855 as MAX31855

# Define a function to convert celsius to fahrenheit.
def c_to_f(c):
  return c * 9.0 / 5.0 + 32.0

# Grab config information from the log file (TOML format)
with open("/home/pi/raspberry-pi-temperature-monitor/config.toml") as conffile:
  conf = toml.loads(conffile.read())

# Check for a parameter + use it, otherwise set a default value
# Returns a string value, typically used like:
#   some_param = config_check('some_param', 'default_value')
def config_check(param, default):
  if conf.get(param):
    return conf.get(param)
  else:
    return default

# Set up logging if applicable
LOGFORMAT = "%(asctime)s\t%(message)s"
if conf.get('log_file'):
  log_file_rotate_size = config_check('log_file_rotate_size', 10000000)
  if conf.get('log_level') == 'DEBUG':
    logging.basicConfig(filename=conf['log_file'], format=LOGFORMAT, level=logging.DEBUG)
  else:
    # Default to INFO-level logging
    logging.basicConfig(filename=conf['log_file'], format=LOGFORMAT, level=logging.INFO)
  print("Logging to {0}".format(conf['log_file']))
else:
  # Just log to STDOUT
  logging.basicConfig(level=logging.INFO, format=LOGFORMAT)

# Check if the log size is greater than our max allowable size.
# Send it to HipChat if it's too big, and clear it out
def rotate_log_file():
  if conf.get('log_file'):
    log_size = os.stat(conf.get('log_file')).st_size

    if log_size > log_file_rotate_size:
      # Store log in hipchat
      if conf.get('hipchat').get('token') and conf.get('hipchat').get('room'):
        subprocess.call(['/usr/local/bin/hipfile', "--token", conf['hipchat']['token'], "--room", conf['hipchat']['room'], "--path", conf.get('log_file'), "--message", "{0} Temperature Log".format(device_name)])
      # Empty log file
      with open(conf.get('log_file'), 'w'):
        pass

# Set some default values
device_name = config_check('device_name', 'Unknown Device')
# Make sure the temperature has been out of range since the last period, to
# avoid spurious one-off temperature readings causing broadcasts
last_temp = None
poll_rate = config_check('poll_rate', 10)
# Set our temperature sensor based on the desired connection method
if conf.get('pi').get('connect_method') == "HARDWARE":
  sensor = MAX31855.MAX31855(spi=SPI.SpiDev(conf['pi']['SPI_PORT'], conf['pi']['SPI_DEVICE']))
else:
  # Default to software SPI
  sensor = MAX31855.MAX31855(conf['pi']['CLK'], conf['pi']['CS'], conf['pi']['DO'])

# Grab our (wireless) IP address so that we can send a link to the webcam if
# the temp is too high/low
ip_command = "ifconfig | awk 'BEGIN{ORS=\"\"}/wlan0/{getline;gsub(/addr:/,\"\",$2);print $2}'"
my_ip = str(subprocess.check_output(ip_command, shell=True))

# Loop measurements every second.
while True:
  rotate_log_file

  # now do the temperature reading
  temp = sensor.readTempC()
  #internal = sensor.readInternalC()
  logging.info("{0:0.3F}*C\t{1:0.3F}*F".format(temp, c_to_f(temp)))

  if temp > conf['temp']['max']:
    if last_temp > conf['temp']['max']:
      warning_text = "{0} WARNING: {1} is hot, potential fire risk: {2:0.3F}*F. Webcam: http://{3}?action=stream".format(conf.get('hipchat').get('notify_names'), device_name, c_to_f(temp), my_ip)
      logging.warning(warning_text)
      if conf.get('hipchat').get('room'):
        subprocess.call(["/usr/local/bin/hipchat", "-r", conf['hipchat']['room'], warning_text])
    time.sleep(30) #seconds
  if temp < conf['temp']['min'] and temp > -25 :
    # for some reason the thermocouple reads^^ below -25C sometimes, which is
    # obviously bogus, so catch that too
    if last_temp < conf['temp']['min']:
      warning_text = "{0} WARNING: {1} is being exposed to freezing temperatures: {2:0.3F}*F. Webcam: http://{3}?action=stream".format(conf.get('hipchat').get('notify_names'), device_name, c_to_f(temp), my_ip)
      logging.warning(warning_text)
      if conf.get('hipchat').get('room'):
        subprocess.call(["/usr/local/bin/hipchat", "-r", conf['hipchat']['room'], warning_text])
    time.sleep(60 * 1) # wait 1 more minute in this case to be sure
  else:
    # Temperature is in normal range, store it, wait regular polling amount + try again
    last_temp = temp
    time.sleep(poll_rate)
<|endoftext|>


<commit_before>#!/usr/bin/env python

# test-client - Simple client for testing parts of Telepathy connection managers
#
# Copyright (C) 2005 Collabora Limited
# Copyright (C) 2005 Nokia Corporation
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import dbus
import dbus.glib

assert(getattr(dbus, 'version', (0,0,0)) >= (0,51,0))

import getpass
import gobject
import signal
import sys
import os

from telepathy import *

import telepathy.client

class ContactListChannel(telepathy.client.Channel):
    def __init__(self, conn, object_path, handle_type, handle):
        telepathy.client.Channel.__init__(self, conn._service_name, object_path)
        self.get_valid_interfaces().add(CHANNEL_TYPE_CONTACT_LIST)
        self._conn = conn
        self._handle_type = handle_type
        self._handle = handle
        self._name = handle

    def got_interfaces(self):
        self._conn[CONN_INTERFACE].InspectHandle(self._handle_type, self._handle, reply_handler=self.inspect_handle_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetMembers(reply_handler=self.get_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetLocalPendingMembers(reply_handler=self.get_local_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetRemotePendingMembers(reply_handler=self.get_remote_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].connect_to_signal('MembersChanged', self.members_changed_signal_cb)

    def inspect_handle_reply_cb(self, name):
        print "CLC", self._name, "is", name
        self._name = name
        if name == 'subscribe':
            gobject.idle_add(self.subscribe_list_idle_cb)
        elif name == 'publish':
            gobject.idle_add(self.publish_list_idle_cb)

    def subscribe_list_idle_cb(self):
#        handle = self._conn[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, 'test2@localhost')
#        self[CHANNEL_INTERFACE_GROUP].AddMembers([handle])
        return False

    def publish_list_idle_cb(self):
        return False

    def members_changed_signal_cb(self, message, added, removed, local_p, remote_p):
        print "MembersChanged on CLC", self._name
        print "Message: ", message
        print "Added: ", added
        print "Removed: ", removed
        print "Local Pending: ", local_p
        print "Remote Pending: ", remote_p
#        if added and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(added)
#        if removed and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(added)

#        if added:
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(added)
#        if local_p:
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(local_p)

    def get_members_reply_cb(self, members):
        print "got members on CLC %s: %s" % (self._name, members)
#        if members and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(members)
#        if members:
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(members)

    def get_local_pending_members_reply_cb(self, members):
        print "got local pending members on CLC %s: %s" % (self._name, members)
#        if members:
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(members)
#            print "sending addmembers"

    def get_remote_pending_members_reply_cb(self, members):
        print "got remote pending members on CLC %s: %s" % (self._name, members)

class StreamedMediaChannel(telepathy.client.Channel):
    def __init__(self, conn, object_path, handle_type, handle):
        telepathy.client.Channel.__init__(self, conn._service_name, object_path)
        self._conn = conn
        self.get_valid_interfaces().add(CHANNEL_TYPE_STREAMED_MEDIA)
        self[CHANNEL_TYPE_STREAMED_MEDIA].connect_to_signal('ReceivedMediaParameters', self.received_media_params_cb)
        self[CHANNEL_INTERFACE].connect_to_signal('Closed', self.closed_cb)

    def got_interfaces(self):
        print "SMC got interfaces"
        self[CHANNEL_INTERFACE_GROUP].GetMembers(reply_handler=self.get_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetLocalPendingMembers(reply_handler=self.get_local_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetRemotePendingMembers(reply_handler=self.get_remote_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].connect_to_signal('MembersChanged', self.members_changed_signal_cb)

    def received_media_params_cb(self, id, local, remote):
        print "Received media params for %s.\n   local SDP = %s\n  remote SDP = %s" % (id, local, remote)

    def closed_cb(self):
        print "Channel closed"

    def members_changed_signal_cb(self, reason, added, removed, local_pending, remote_pending):
        print "Members Changed"
        print "  added ",added," removed", removed
        print "  local pending",local_pending," remote pending ", remote_pending

        self[CHANNEL_INTERFACE_DTMF].SendDTMF(1, 160)

    def error_cb(self, exception):
        print "Exception received from asynchronous method call:"
        print exception

    def get_members_reply_cb(self, members):
        print "Channel has members", members

    def get_local_pending_members_reply_cb(self, members):
        print "Channel has local pending members", members
        print self[CHANNEL_INTERFACE].GetInterfaces()
        if members:
           if "SIPDEBUG" in os.environ and os.environ["SIPDEBUG"] == "transfer":
               print "getting handle for test2"
               handle = self._conn[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, 'sip:test2@192.168.1.101')
               print "got handle %d for %s" % (handle, 'sip:test2@192.168.1.101')
               self[CHANNEL_INTERFACE_TRANSFER].Transfer(members[0],handle)
           else:
              print "adding member"
              self[CHANNEL_INTERFACE_GROUP].AddMembers(members)

    def get_remote_pending_members_reply_cb(self, members):
        print "Channel has remote pending members", members

class TextChannel(telepathy.client.Channel):
    def __init__(self, conn, object_path, handle_type, handle):
        # FIXME: this is racy and buggy and smells, and is deprecated in
        # favour of the stuff in sdp-client.py
        telepathy.client.Channel.__init__(self, conn._service_name, object_path)
        self.get_valid_interfaces().add(CHANNEL_TYPE_TEXT)
        self[CHANNEL_TYPE_TEXT].connect_to_signal('Received', self.received_callback)
        self.doack = True

        self._handled_pending_message = None
        pending_messages = self[CHANNEL_TYPE_TEXT].ListPendingMessages()
        print pending_messages
        for msg in pending_messages:
            (id, timestamp, sender, type, message) = msg
            print "Handling pending message", id
            self.received_callback(id, timestamp, sender, type, message)
            self._handled_pending_message = id

    def received_callback(self, id, timestamp, sender, type, message):
        if self._handled_pending_message != None:
            if id > self._handled_pending_message:
                print "Now handling messages directly"
                self._handled_pending_message = None
            else:
                print "Skipping already handled message", id
                return

        print "Received", id, timestamp, sender, type, message
        self[CHANNEL_TYPE_TEXT].Send(CHANNEL_TEXT_MESSAGE_TYPE_NORMAL, 'got message ' + str(id) + '(' + message + ')')
        if self.doack:
            print "Acknowledging...", id
            self[CHANNEL_TYPE_TEXT].AcknowledgePendingMessage(id)

class TestConnection(telepathy.client.Connection):
    def __init__(self, service_name, object_path, mainloop):
        telepathy.client.Connection.__init__(self, service_name, object_path)

        self._mainloop = mainloop
        self._service_name = service_name

        self._status = CONNECTION_STATUS_CONNECTING
        self._channels = {}

        print "calling GetStatus async"
        # handle race condition when connecting completes
        # before the signal handlers are registered
        self[CONN_INTERFACE].GetStatus(reply_handler=self.get_status_reply_cb, error_handler=self.error_cb)
        print "called GetStatus"

        print 'connecting to StatusChanged'
        self[CONN_INTERFACE].connect_to_signal('StatusChanged', self.status_changed_signal_cb)
        print 'connecting to NewChannel'
        self[CONN_INTERFACE].connect_to_signal('NewChannel', self.new_channel_signal_cb)

    def error_cb(self, exception):
        print "Exception received from asynchronous method call:"
        print exception

    def get_status_reply_cb(self, status):
        print "get_status_reply_cb", status
        self.status_changed_signal_cb(status, CONNECTION_STATUS_REASON_NONE_SPECIFIED)

    def new_channel_signal_cb(self, obj_path, chan_type, handle_type, handle, suppress_handler):
        if obj_path in self._channels:
            return

        print 'NewChannel', obj_path, chan_type, handle_type, handle, suppress_handler

        channel = None

        if chan_type == CHANNEL_TYPE_TEXT:
            channel = TextChannel(self, obj_path, handle_type, handle)
        elif chan_type == CHANNEL_TYPE_CONTACT_LIST:
            channel = ContactListChannel(self, obj_path, handle_type, handle)
        elif chan_type == CHANNEL_TYPE_STREAMED_MEDIA:
            channel = StreamedMediaChannel(self, obj_path, handle_type, handle)

        if channel != None:
            self._channels[obj_path] = channel
        else:
            print 'Unknown channel type', handle_type

    def connected_cb(self):
        if CONN_INTERFACE_STREAMED_MEDIA in self.get_valid_interfaces():
            self[CONN_INTERFACE_STREAMED_MEDIA].SetMediaParameters(
"v=0\r\nm=audio 0 RTP/AVP 3 0 8\r\na=rtpmap:3 GSM/8000\r\na=rtpmap  PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\n")
        if "SIPDEBUG" in os.environ and os.environ["SIPDEBUG"][:5] == "call:":
            handle = self[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, os.environ["SIPDEBUG"][5:])
            print "got handle %d for %s" % (handle, os.environ["SIPDEBUG"][5:])
            print "calling RequestChannel"
            obj = self[CONN_INTERFACE].RequestChannel(CHANNEL_TYPE_STREAMED_MEDIA, CONNECTION_HANDLE_TYPE_CONTACT, handle, True)
            print "called RequestChannel, got ", obj
        elif "SIPDEBUG" in os.environ and os.environ["SIPDEBUG"][:8] == "forward:":
            handle = self[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, os.environ["SIPDEBUG"][8:])
            print "got handle %d for %s" % (handle, os.environ["SIPDEBUG"][8:])
            #print self[CONN_INTERFACE_PRESENCE].GetStatuses()
            self[CONN_INTERFACE_FORWARDING].SetForwardingHandle(handle)
        return False

    def presence_update_signal_cb(self, presence):
        print "got presence update:", presence

    def get_interfaces_reply_cb(self, interfaces):
        self.get_valid_interfaces().update(interfaces)
        #self[CONN_INTERFACE_PRESENCE].connect_to_signal('PresenceUpdate', self.presence_update_signal_cb)
        gobject.idle_add(self.connected_cb)

    def status_changed_signal_cb(self, status, reason):
        if self._status == status:
            return
        else:
            self._status = status

        print 'StatusChanged', status, reason

        if status == CONNECTION_STATUS_CONNECTED:
            print "connection connected"
            self[CONN_INTERFACE].GetInterfaces(reply_handler=self.get_interfaces_reply_cb, error_handler=self.error_cb)
        if status == CONNECTION_STATUS_DISCONNECTED:
            print "connection terminated"
            self._mainloop.quit()

if __name__ == '__main__':
    reg = telepathy.client.ManagerRegistry()
    reg.LoadManagers()

    protos=reg.GetProtos()

    if len(protos) == 0:
        print "Sorry, no connection managers found!"
        sys.exit(1)

    if len(sys.argv) > 2:
        protocol = sys.argv[2]
    else:
        protocol=''

    while (protocol not in protos):
        protocol = raw_input('Protocol (one of: %s) [%s]: ' % (' '.join(protos),protos[0]))
        if protocol == '':
            protocol = protos[0]

    if len(sys.argv) > 1:
        manager = sys.argv[1]
    else:
        manager = ''
    managers = reg.GetManagers(protocol)

    while (manager not in managers):
        manager = raw_input('Manager (one of: %s) [%s]: ' % (' '.join(managers),managers[0]))
        if manager == '':
            manager = managers[0]

    mgr_bus_name = reg.GetBusName(manager)
    mgr_object_path = reg.GetObjectPath(manager)

    cmdline_params = dict((p.split('=') for p in sys.argv[3:]))
    params={}

    for (name, (type, default)) in reg.GetParams(manager, protocol)[0].iteritems():
        if name in cmdline_params:
            params[name] = dbus.Variant(cmdline_params[name],type)
        elif name == 'password':
            params[name] = dbus.Variant(getpass.getpass(),type)
        else:
            params[name] = dbus.Variant(raw_input(name+': '),type)

    mgr = telepathy.client.ConnectionManager(mgr_bus_name, mgr_object_path)
    print "using params:",params
    bus_name, object_path = mgr[CONN_MGR_INTERFACE].Connect(protocol, params)
    print "done connect"
    mainloop = gobject.MainLoop()
    connection = TestConnection(bus_name, object_path, mainloop)
    print "created connection"

    def quit_cb():
        connection[CONN_INTERFACE].Disconnect()
        mainloop.quit()

    def sigterm_cb():
        gobject.idle_add(quit_cb)

    signal.signal(signal.SIGTERM, sigterm_cb)

    while mainloop.is_running():
        try:
            mainloop.run()
        except KeyboardInterrupt:
            quit_cb()
<commit_msg>list channels at test-client startup<commit_after>#!/usr/bin/env python

# test-client - Simple client for testing parts of Telepathy connection managers
#
# Copyright (C) 2005 Collabora Limited
# Copyright (C) 2005 Nokia Corporation
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import dbus
import dbus.glib

assert(getattr(dbus, 'version', (0,0,0)) >= (0,51,0))

import getpass
import gobject
import signal
import sys
import os

from telepathy import *

import telepathy.client

class ContactListChannel(telepathy.client.Channel):
    def __init__(self, conn, object_path, handle_type, handle):
        telepathy.client.Channel.__init__(self, conn._service_name, object_path)
        self.get_valid_interfaces().add(CHANNEL_TYPE_CONTACT_LIST)
        self._conn = conn
        self._handle_type = handle_type
        self._handle = handle
        self._name = handle

    def got_interfaces(self):
        self._conn[CONN_INTERFACE].InspectHandle(self._handle_type, self._handle, reply_handler=self.inspect_handle_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetMembers(reply_handler=self.get_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetLocalPendingMembers(reply_handler=self.get_local_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetRemotePendingMembers(reply_handler=self.get_remote_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].connect_to_signal('MembersChanged', self.members_changed_signal_cb)

    def inspect_handle_reply_cb(self, name):
        print "CLC", self._name, "is", name
        self._name = name
        if name == 'subscribe':
            gobject.idle_add(self.subscribe_list_idle_cb)
        elif name == 'publish':
            gobject.idle_add(self.publish_list_idle_cb)

    def subscribe_list_idle_cb(self):
#        handle = self._conn[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, 'test2@localhost')
#        self[CHANNEL_INTERFACE_GROUP].AddMembers([handle])
        return False

    def publish_list_idle_cb(self):
        return False

    def members_changed_signal_cb(self, message, added, removed, local_p, remote_p):
        print "MembersChanged on CLC", self._name
        print "Message: ", message
        print "Added: ", added
        print "Removed: ", removed
        print "Local Pending: ", local_p
        print "Remote Pending: ", remote_p
#        if added and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(added)
#        if removed and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(added)

#        if added:
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(added)
#        if local_p:
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(local_p)

    def get_members_reply_cb(self, members):
        print "got members on CLC %s: %s" % (self._name, members)
#        if members and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(members)
#        if members:
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(members)

    def get_local_pending_members_reply_cb(self, members):
        print "got local pending members on CLC %s: %s" % (self._name, members)
#        if members:
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(members)
#            print "sending addmembers"

    def get_remote_pending_members_reply_cb(self, members):
        print "got remote pending members on CLC %s: %s" % (self._name, members)

class StreamedMediaChannel(telepathy.client.Channel):
    def __init__(self, conn, object_path, handle_type, handle):
        telepathy.client.Channel.__init__(self, conn._service_name, object_path)
        self._conn = conn
        self.get_valid_interfaces().add(CHANNEL_TYPE_STREAMED_MEDIA)
        self[CHANNEL_TYPE_STREAMED_MEDIA].connect_to_signal('ReceivedMediaParameters', self.received_media_params_cb)
        self[CHANNEL_INTERFACE].connect_to_signal('Closed', self.closed_cb)

    def got_interfaces(self):
        print "SMC got interfaces"
        self[CHANNEL_INTERFACE_GROUP].GetMembers(reply_handler=self.get_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetLocalPendingMembers(reply_handler=self.get_local_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetRemotePendingMembers(reply_handler=self.get_remote_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].connect_to_signal('MembersChanged', self.members_changed_signal_cb)

    def received_media_params_cb(self, id, local, remote):
        print "Received media params for %s.\n   local SDP = %s\n  remote SDP = %s" % (id, local, remote)

    def closed_cb(self):
        print "Channel closed"

    def members_changed_signal_cb(self, reason, added, removed, local_pending, remote_pending):
        print "Members Changed"
        print "  added ",added," removed", removed
        print "  local pending",local_pending," remote pending ", remote_pending

        self[CHANNEL_INTERFACE_DTMF].SendDTMF(1, 160)

    def error_cb(self, exception):
        print "Exception received from asynchronous method call:"
        print exception

    def get_members_reply_cb(self, members):
        print "Channel has members", members

    def get_local_pending_members_reply_cb(self, members):
        print "Channel has local pending members", members
        print self[CHANNEL_INTERFACE].GetInterfaces()
        if members:
           if "SIPDEBUG" in os.environ and os.environ["SIPDEBUG"] == "transfer":
               print "getting handle for test2"
               handle = self._conn[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, 'sip:test2@192.168.1.101')
               print "got handle %d for %s" % (handle, 'sip:test2@192.168.1.101')
               self[CHANNEL_INTERFACE_TRANSFER].Transfer(members[0],handle)
           else:
              print "adding member"
              self[CHANNEL_INTERFACE_GROUP].AddMembers(members)

    def get_remote_pending_members_reply_cb(self, members):
        print "Channel has remote pending members", members

class TextChannel(telepathy.client.Channel):
    def __init__(self, conn, object_path, handle_type, handle):
        # FIXME: this is racy and buggy and smells, and is deprecated in
        # favour of the stuff in sdp-client.py
        telepathy.client.Channel.__init__(self, conn._service_name, object_path)
        self.get_valid_interfaces().add(CHANNEL_TYPE_TEXT)
        self[CHANNEL_TYPE_TEXT].connect_to_signal('Received', self.received_callback)
        self.doack = True

        self._handled_pending_message = None
        pending_messages = self[CHANNEL_TYPE_TEXT].ListPendingMessages()
        print pending_messages
        for msg in pending_messages:
            (id, timestamp, sender, type, message) = msg
            print "Handling pending message", id
            self.received_callback(id, timestamp, sender, type, message)
            self._handled_pending_message = id

    def received_callback(self, id, timestamp, sender, type, message):
        if self._handled_pending_message != None:
            if id > self._handled_pending_message:
                print "Now handling messages directly"
                self._handled_pending_message = None
            else:
                print "Skipping already handled message", id
                return

        print "Received", id, timestamp, sender, type, message
        self[CHANNEL_TYPE_TEXT].Send(CHANNEL_TEXT_MESSAGE_TYPE_NORMAL, 'got message ' + str(id) + '(' + message + ')')
        if self.doack:
            print "Acknowledging...", id
            self[CHANNEL_TYPE_TEXT].AcknowledgePendingMessage(id)

class TestConnection(telepathy.client.Connection):
    def __init__(self, service_name, object_path, mainloop):
        telepathy.client.Connection.__init__(self, service_name, object_path)

        self._mainloop = mainloop
        self._service_name = service_name

        self._status = CONNECTION_STATUS_CONNECTING
        self._channels = {}

        print "calling GetStatus async"
        # handle race condition when connecting completes
        # before the signal handlers are registered
        self[CONN_INTERFACE].GetStatus(reply_handler=self.get_status_reply_cb, error_handler=self.error_cb)
        print "called GetStatus"

        print 'connecting to StatusChanged'
        self[CONN_INTERFACE].connect_to_signal('StatusChanged', self.status_changed_signal_cb)
        print 'connecting to NewChannel'
        self[CONN_INTERFACE].connect_to_signal('NewChannel', self.new_channel_signal_cb)

    def error_cb(self, exception):
        print "Exception received from asynchronous method call:"
        print exception

    def get_status_reply_cb(self, status):
        print "get_status_reply_cb", status
        self.status_changed_signal_cb(status, CONNECTION_STATUS_REASON_NONE_SPECIFIED)

    def list_channels_reply_cb(self, channels):
        for (obj_path, channel_type, handle_type, handle) in channels:
            self.new_channel_signal_cb(obj_path, channel_type, handle_type, handle, False)

    def new_channel_signal_cb(self, obj_path, chan_type, handle_type, handle, suppress_handler):
        if obj_path in self._channels:
            return

        print 'NewChannel', obj_path, chan_type, handle_type, handle, suppress_handler

        channel = None

        if chan_type == CHANNEL_TYPE_TEXT:
            channel = TextChannel(self, obj_path, handle_type, handle)
        elif chan_type == CHANNEL_TYPE_CONTACT_LIST:
            channel = ContactListChannel(self, obj_path, handle_type, handle)
        elif chan_type == CHANNEL_TYPE_STREAMED_MEDIA:
            channel = StreamedMediaChannel(self, obj_path, handle_type, handle)

        if channel != None:
            self._channels[obj_path] = channel
        else:
            print 'Unknown channel type', handle_type

    def connected_cb(self):
        if CONN_INTERFACE_STREAMED_MEDIA in self.get_valid_interfaces():
            self[CONN_INTERFACE_STREAMED_MEDIA].SetMediaParameters(
"v=0\r\nm=audio 0 RTP/AVP 3 0 8\r\na=rtpmap:3 GSM/8000\r\na=rtpmap  PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\n")
        if "SIPDEBUG" in os.environ and os.environ["SIPDEBUG"][:5] == "call:":
            handle = self[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, os.environ["SIPDEBUG"][5:])
            print "got handle %d for %s" % (handle, os.environ["SIPDEBUG"][5:])
            print "calling RequestChannel"
            obj = self[CONN_INTERFACE].RequestChannel(CHANNEL_TYPE_STREAMED_MEDIA, CONNECTION_HANDLE_TYPE_CONTACT, handle, True)
            print "called RequestChannel, got ", obj
        elif "SIPDEBUG" in os.environ and os.environ["SIPDEBUG"][:8] == "forward:":
            handle = self[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, os.environ["SIPDEBUG"][8:])
            print "got handle %d for %s" % (handle, os.environ["SIPDEBUG"][8:])
            #print self[CONN_INTERFACE_PRESENCE].GetStatuses()
            self[CONN_INTERFACE_FORWARDING].SetForwardingHandle(handle)
        return False

    def presence_update_signal_cb(self, presence):
        print "got presence update:", presence

    def get_interfaces_reply_cb(self, interfaces):
        self.get_valid_interfaces().update(interfaces)
        self[CONN_INTERFACE].ListChannels(reply_handler=self.list_channels_reply_cb, error_handler=self.error_cb)
        #self[CONN_INTERFACE_PRESENCE].connect_to_signal('PresenceUpdate', self.presence_update_signal_cb)
        gobject.idle_add(self.connected_cb)

    def status_changed_signal_cb(self, status, reason):
        if self._status == status:
            return
        else:
            self._status = status

        print 'StatusChanged', status, reason

        if status == CONNECTION_STATUS_CONNECTED:
            print "connection connected"
            self[CONN_INTERFACE].GetInterfaces(reply_handler=self.get_interfaces_reply_cb, error_handler=self.error_cb)
        if status == CONNECTION_STATUS_DISCONNECTED:
            print "connection terminated"
            self._mainloop.quit()

if __name__ == '__main__':
    reg = telepathy.client.ManagerRegistry()
    reg.LoadManagers()

    protos=reg.GetProtos()

    if len(protos) == 0:
        print "Sorry, no connection managers found!"
        sys.exit(1)

    if len(sys.argv) > 2:
        protocol = sys.argv[2]
    else:
        protocol=''

    while (protocol not in protos):
        protocol = raw_input('Protocol (one of: %s) [%s]: ' % (' '.join(protos),protos[0]))
        if protocol == '':
            protocol = protos[0]

    if len(sys.argv) > 1:
        manager = sys.argv[1]
    else:
        manager = ''
    managers = reg.GetManagers(protocol)

    while (manager not in managers):
        manager = raw_input('Manager (one of: %s) [%s]: ' % (' '.join(managers),managers[0]))
        if manager == '':
            manager = managers[0]

    mgr_bus_name = reg.GetBusName(manager)
    mgr_object_path = reg.GetObjectPath(manager)

    cmdline_params = dict((p.split('=') for p in sys.argv[3:]))
    params={}

    for (name, (type, default)) in reg.GetParams(manager, protocol)[0].iteritems():
        if name in cmdline_params:
            params[name] = dbus.Variant(cmdline_params[name],type)
        elif name == 'password':
            params[name] = dbus.Variant(getpass.getpass(),type)
        else:
            params[name] = dbus.Variant(raw_input(name+': '),type)

    mgr = telepathy.client.ConnectionManager(mgr_bus_name, mgr_object_path)
    print "using params:",params
    bus_name, object_path = mgr[CONN_MGR_INTERFACE].Connect(protocol, params)
    print "done connect"
    mainloop = gobject.MainLoop()
    connection = TestConnection(bus_name, object_path, mainloop)
    print "created connection"

    def quit_cb():
        connection[CONN_INTERFACE].Disconnect()
        mainloop.quit()

    def sigterm_cb():
        gobject.idle_add(quit_cb)

    signal.signal(signal.SIGTERM, sigterm_cb)

    while mainloop.is_running():
        try:
            mainloop.run()
        except KeyboardInterrupt:
            quit_cb()
<|endoftext|>


<commit_before>#!/usr/bin/env python

import dbus
import dbus.glib

assert(getattr(dbus, 'version', (0,0,0)) >= (0,51,0))

import getpass
import gobject
import signal
import sys

from telepathy import *

import telepathy.client

class ContactListChannel(telepathy.client.Channel):
    def __init__(self, conn, object_path, handle):
        telepathy.client.Channel.__init__(self, conn._service_name, object_path)
        self.get_valid_interfaces().add(CHANNEL_TYPE_CONTACT_LIST)
        self._conn = conn
        self._handle = handle
        self._name = handle

    def got_interfaces(self):
        self._conn[CONN_INTERFACE].InspectHandle(self._handle, reply_handler=self.inspect_handle_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE].GetMembers(reply_handler=self.get_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetLocalPendingMembers(reply_handler=self.get_local_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetRemotePendingMembers(reply_handler=self.get_remote_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].connect_to_signal('MembersChanged', self.members_changed_signal_cb)

    def inspect_handle_reply_cb(self, type, name):
        print "CLC", self._name, "is", name
        self._name = name
        if name == 'subscribe':
            gobject.idle_add(self.subscribe_list_idle_cb)
        elif name == 'publish':
            gobject.idle_add(self.publish_list_idle_cb)

    def subscribe_list_idle_cb(self):
#        handle = self._conn[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, 'test2@localhost')
#        self[CHANNEL_INTERFACE_GROUP].AddMembers([handle])
        return False

    def publish_list_idle_cb(self):
        return False

    def members_changed_signal_cb(self, message, added, removed, local_p, remote_p):
        print "MembersChanged on CLC", self._name
        print "Message: ", message
        print "Added: ", added
        print "Removed: ", removed
        print "Local Pending: ", local_p
        print "Remote Pending: ", remote_p
#        if added and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(added)
#        if removed and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(added)

#        if added:
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(added)
#        if local_p:
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(local_p)

    def get_members_reply_cb(self, members):
        print "got members on CLC %s: %s" % (self._name, members)
#        if members and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(members)
#        if members:
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(members)

    def get_local_pending_members_reply_cb(self, members):
        print "got local pending members on CLC %s: %s" % (self._name, members)
#        if members:
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(members)
#            print "sending addmembers"

    def get_remote_pending_members_reply_cb(self, members):
        print "got remote pending members on CLC %s: %s" % (self._name, members)

class StreamedMediaChannel(telepathy.client.Channel):
    def __init__(self, service_name, object_path, handle):
        telepathy.client.Channel.__init__(self, service_name, object_path)
        self.get_valid_interfaces().add(CHANNEL_TYPE_STREAMED_MEDIA)
        self[CHANNEL_TYPE_STREAMED_MEDIA].connect_to_signal('ReceivedMediaParameters', self.received_media_params_cb)
        self[CHANNEL_INTERFACE].connect_to_signal('Closed', self.closed_cb)
        self[CHANNEL_INTERFACE_GROUP].connect_to_signal('MembersChanged', self.members_changed_cb)
        self.doack = True

    def received_media_params_cb(self, id, local, remote):
        print "Received media params for %s.\n   local SDP = %s\n  remote SDP = %s" % (id, local, remote)

    def closed_cb(self):
        print "Channel closed"
    def members_changed_cb(self, reason, added, removed, local_pending, local_received):
        print "Members Changed"
        print "  added ",added," removed", removed
        print "  local pending",local_pending," local remote", local_remote

class TextChannel(telepathy.client.Channel):
    def __init__(self, conn, object_path, handle):
        telepathy.client.Channel.__init__(self, conn._service_name, object_path)
        self.get_valid_interfaces().add(CHANNEL_TYPE_TEXT)
        self[CHANNEL_TYPE_TEXT].connect_to_signal('Received', self.received_callback)
        self.doack = True

        self._handled_pending_message = None
        pending_messages = self.text.ListPendingMessages()
        print pending_messages
        for msg in pending_messages:
            (id, timestamp, sender, type, message) = msg
            print "Handling pending message", id
            self.received_callback(id, timestamp, sender, type, message)
            self._handled_pending_message = id

    def received_callback(self, id, timestamp, sender, type, message):
        if self._handled_pending_message != None:
            if id > self._handled_pending_message:
                print "Now handling messages directly"
                self._handled_pending_message = None
            else:
                print "Skipping already handled message", id
                return

        print "Received", id, timestamp, sender, type, message
        self.text.Send(CHANNEL_TEXT_MESSAGE_TYPE_NORMAL, 'got message ' + str(id) + '(' + message + ')')
        if self.doack:
            print "Acknowledging...", id
            self.text.AcknowledgePendingMessage(id)

class TestConnection(telepathy.client.Connection):
    def __init__(self, service_name, object_path, mainloop):
        telepathy.client.Connection.__init__(self, service_name, object_path)

        self._mainloop = mainloop
        self._service_name = service_name

        self._status = CONNECTION_STATUS_CONNECTING
        self._channels = {}

        print "calling GetStatus async"
        # handle race condition when connecting completes
        # before the signal handlers are registered
        self[CONN_INTERFACE].GetStatus(reply_handler=self.get_status_reply_cb, error_handler=self.error_cb)
        print "called GetStatus"

        print 'connecting to StatusChanged'
        self[CONN_INTERFACE].connect_to_signal('StatusChanged', self.status_changed_signal_cb)
        print 'connecting to NewChannel'
        self[CONN_INTERFACE].connect_to_signal('NewChannel', self.new_channel_signal_cb)

    def error_cb(self, exception):
        print "Exception received from asynchronous method call:"
        print exception

    def get_status_reply_cb(self, status):
        self.status_changed_signal_cb(status, CONNECTION_STATUS_REASON_NONE_SPECIFIED)

    def new_channel_signal_cb(self, obj_path, type, handle, supress_handler):
        if obj_path in self._channels:
            return

        print 'NewChannel', obj_path, type, handle, supress_handler

        channel = None

        if type == CHANNEL_TYPE_TEXT:
            channel = TextChannel(self, obj_path, handle)
        elif type == CHANNEL_TYPE_CONTACT_LIST:
            channel = ContactListChannel(self._service_name, obj_path, handle)

        if channel != None:
            self._channels[obj_path] = channel
        else:
            print 'Unknown channel type', type

    def connected_cb(self):
        self[CONN_INTERFACE_STREAMED_MEDIA].SetMediaParameters(
"v=0\r\nm=audio 0 RTP/AVP 3 0 8\r\na=rtpmap:3 GSM/8000\r\na=rtpmap  PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\n")

        handle = self[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, 'sip:test2@192.168.1.101')
        print "got handle %d for %s" % (handle, 'sip:test2@192.168.1.101')
        print "calling RequestChannel"
        obj = self[CONN_INTERFACE].RequestChannel(CHANNEL_TYPE_STREAMED_MEDIA, handle, True)
        print "called RequestChannel, got ", obj
        #print self[CONN_INTERFACE_PRESENCE].GetStatuses()
        return False

    def presence_update_signal_cb(self, presence):
        print "got presence update:", presence

    def get_interfaces_reply_cb(self, interfaces):
        self.get_valid_interfaces().update(interfaces)
        self[CONN_INTERFACE_PRESENCE].connect_to_signal('PresenceUpdate', self.presence_update_signal_cb)
        gobject.idle_add(self.connected_cb)

    def status_changed_signal_cb(self, status, reason):
        if self._status == status:
            return
        else:
            self._status = status

        print 'StatusChanged', status, reason

        if status == CONNECTION_STATUS_CONNECTED:
            self[CONN_INTERFACE].GetInterfaces(reply_handler=self.get_interfaces_reply_cb, error_handler=self.error_cb)
        if status == CONNECTION_STATUS_DISCONNECTED:
            print "connection terminated"
            self._mainloop.quit()

if __name__ == '__main__':
    reg = telepathy.client.ManagerRegistry()
    reg.LoadManagers()

    protocol=''
    protos=reg.GetProtos()

    if len(protos) == 0:
        print "Sorry, no connection managers found!"
        sys.exit(1)

    if len(sys.argv) > 2:
        protocol = sys.argv[2]
    else:
        while (protocol not in protos):
            protocol = raw_input('Protocol (one of: %s) [%s]: ' % (' '.join(protos),protos[0]))
            if protocol == '':
                protocol = protos[0]

    manager=''
    managers=reg.GetManagers(protocol)

    while (manager not in managers):
        if len(sys.argv) > 1:
            manager = sys.argv[1]
        else:
            manager = raw_input('Manager (one of: %s) [%s]: ' % (' '.join(managers),managers[0]))
            if manager == '':
                manager = managers[0]

    mgr_bus_name = reg.GetBusName(manager)
    mgr_object_path = reg.GetObjectPath(manager)

    cmdline_params = dict((p.split('=') for p in sys.argv[3:]))
    params={}

    for (name, (type, default)) in reg.GetParams(manager, protocol)[0].iteritems():
        if name in cmdline_params:
            params[name] = dbus.Variant(cmdline_params[name],type)
        elif name == 'password':
            params[name] = dbus.Variant(getpass.getpass(),type)
        else:
            params[name] = dbus.Variant(raw_input(name+': '),type)

    mgr = telepathy.client.ConnectionManager(mgr_bus_name, mgr_object_path)
    bus_name, object_path = mgr[CONN_MGR_INTERFACE].Connect(protocol, params)

    mainloop = gobject.MainLoop()
    connection = TestConnection(bus_name, object_path, mainloop)

    def quit_cb():
        connection[CONN_INTERFACE].Disconnect()
        mainloop.quit()

    def sigterm_cb():
        gobject.idle_add(quit_cb)

    signal.signal(signal.SIGTERM, sigterm_cb)

    while mainloop.is_running():
        try:
            mainloop.run()
        except KeyboardInterrupt:
            quit_cb()
<commit_msg>added some debugging traces<commit_after>#!/usr/bin/env python

import dbus
import dbus.glib

assert(getattr(dbus, 'version', (0,0,0)) >= (0,51,0))

import getpass
import gobject
import signal
import sys

from telepathy import *

import telepathy.client

class ContactListChannel(telepathy.client.Channel):
    def __init__(self, conn, object_path, handle):
        telepathy.client.Channel.__init__(self, conn._service_name, object_path)
        self.get_valid_interfaces().add(CHANNEL_TYPE_CONTACT_LIST)
        self._conn = conn
        self._handle = handle
        self._name = handle

    def got_interfaces(self):
        self._conn[CONN_INTERFACE].InspectHandle(self._handle, reply_handler=self.inspect_handle_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE].GetMembers(reply_handler=self.get_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetLocalPendingMembers(reply_handler=self.get_local_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].GetRemotePendingMembers(reply_handler=self.get_remote_pending_members_reply_cb, error_handler=self.error_cb)
        self[CHANNEL_INTERFACE_GROUP].connect_to_signal('MembersChanged', self.members_changed_signal_cb)

    def inspect_handle_reply_cb(self, type, name):
        print "CLC", self._name, "is", name
        self._name = name
        if name == 'subscribe':
            gobject.idle_add(self.subscribe_list_idle_cb)
        elif name == 'publish':
            gobject.idle_add(self.publish_list_idle_cb)

    def subscribe_list_idle_cb(self):
#        handle = self._conn[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, 'test2@localhost')
#        self[CHANNEL_INTERFACE_GROUP].AddMembers([handle])
        return False

    def publish_list_idle_cb(self):
        return False

    def members_changed_signal_cb(self, message, added, removed, local_p, remote_p):
        print "MembersChanged on CLC", self._name
        print "Message: ", message
        print "Added: ", added
        print "Removed: ", removed
        print "Local Pending: ", local_p
        print "Remote Pending: ", remote_p
#        if added and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(added)
#        if removed and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(added)

#        if added:
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(added)
#        if local_p:
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(local_p)

    def get_members_reply_cb(self, members):
        print "got members on CLC %s: %s" % (self._name, members)
#        if members and self._name == 'subscribe':
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(members)
#        if members:
#            self[CHANNEL_INTERFACE_GROUP].RemoveMembers(members)

    def get_local_pending_members_reply_cb(self, members):
        print "got local pending members on CLC %s: %s" % (self._name, members)
#        if members:
#            self[CHANNEL_INTERFACE_GROUP].AddMembers(members)
#            print "sending addmembers"

    def get_remote_pending_members_reply_cb(self, members):
        print "got remote pending members on CLC %s: %s" % (self._name, members)

class StreamedMediaChannel(telepathy.client.Channel):
    def __init__(self, service_name, object_path, handle):
        telepathy.client.Channel.__init__(self, service_name, object_path)
        self.get_valid_interfaces().add(CHANNEL_TYPE_STREAMED_MEDIA)
        self[CHANNEL_TYPE_STREAMED_MEDIA].connect_to_signal('ReceivedMediaParameters', self.received_media_params_cb)
        self[CHANNEL_INTERFACE].connect_to_signal('Closed', self.closed_cb)
        self[CHANNEL_INTERFACE_GROUP].connect_to_signal('MembersChanged', self.members_changed_cb)
        self.doack = True

    def received_media_params_cb(self, id, local, remote):
        print "Received media params for %s.\n   local SDP = %s\n  remote SDP = %s" % (id, local, remote)

    def closed_cb(self):
        print "Channel closed"
    def members_changed_cb(self, reason, added, removed, local_pending, local_received):
        print "Members Changed"
        print "  added ",added," removed", removed
        print "  local pending",local_pending," local remote", local_remote

class TextChannel(telepathy.client.Channel):
    def __init__(self, conn, object_path, handle):
        telepathy.client.Channel.__init__(self, conn._service_name, object_path)
        self.get_valid_interfaces().add(CHANNEL_TYPE_TEXT)
        self[CHANNEL_TYPE_TEXT].connect_to_signal('Received', self.received_callback)
        self.doack = True

        self._handled_pending_message = None
        pending_messages = self.text.ListPendingMessages()
        print pending_messages
        for msg in pending_messages:
            (id, timestamp, sender, type, message) = msg
            print "Handling pending message", id
            self.received_callback(id, timestamp, sender, type, message)
            self._handled_pending_message = id

    def received_callback(self, id, timestamp, sender, type, message):
        if self._handled_pending_message != None:
            if id > self._handled_pending_message:
                print "Now handling messages directly"
                self._handled_pending_message = None
            else:
                print "Skipping already handled message", id
                return

        print "Received", id, timestamp, sender, type, message
        self.text.Send(CHANNEL_TEXT_MESSAGE_TYPE_NORMAL, 'got message ' + str(id) + '(' + message + ')')
        if self.doack:
            print "Acknowledging...", id
            self.text.AcknowledgePendingMessage(id)

class TestConnection(telepathy.client.Connection):
    def __init__(self, service_name, object_path, mainloop):
        telepathy.client.Connection.__init__(self, service_name, object_path)

        self._mainloop = mainloop
        self._service_name = service_name

        self._status = CONNECTION_STATUS_CONNECTING
        self._channels = {}

        print "calling GetStatus async"
        # handle race condition when connecting completes
        # before the signal handlers are registered
        self[CONN_INTERFACE].GetStatus(reply_handler=self.get_status_reply_cb, error_handler=self.error_cb)
        print "called GetStatus"

        print 'connecting to StatusChanged'
        self[CONN_INTERFACE].connect_to_signal('StatusChanged', self.status_changed_signal_cb)
        print 'connecting to NewChannel'
        self[CONN_INTERFACE].connect_to_signal('NewChannel', self.new_channel_signal_cb)

    def error_cb(self, exception):
        print "Exception received from asynchronous method call:"
        print exception

    def get_status_reply_cb(self, status):
        print "get_status_reply_cb", status
        self.status_changed_signal_cb(status, CONNECTION_STATUS_REASON_NONE_SPECIFIED)

    def new_channel_signal_cb(self, obj_path, type, handle, supress_handler):
        if obj_path in self._channels:
            return

        print 'NewChannel', obj_path, type, handle, supress_handler

        channel = None

        if type == CHANNEL_TYPE_TEXT:
            channel = TextChannel(self, obj_path, handle)
        elif type == CHANNEL_TYPE_CONTACT_LIST:
            channel = ContactListChannel(self._service_name, obj_path, handle)

        if channel != None:
            self._channels[obj_path] = channel
        else:
            print 'Unknown channel type', type

    def connected_cb(self):
        self[CONN_INTERFACE_STREAMED_MEDIA].SetMediaParameters(
"v=0\r\nm=audio 0 RTP/AVP 3 0 8\r\na=rtpmap:3 GSM/8000\r\na=rtpmap  PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\n")

        handle = self[CONN_INTERFACE].RequestHandle(CONNECTION_HANDLE_TYPE_CONTACT, 'sip:test2@192.168.1.101')
        print "got handle %d for %s" % (handle, 'sip:test2@192.168.1.101')
        print "calling RequestChannel"
        obj = self[CONN_INTERFACE].RequestChannel(CHANNEL_TYPE_STREAMED_MEDIA, handle, True)
        print "called RequestChannel, got ", obj
        #print self[CONN_INTERFACE_PRESENCE].GetStatuses()
        return False

    def presence_update_signal_cb(self, presence):
        print "got presence update:", presence

    def get_interfaces_reply_cb(self, interfaces):
        self.get_valid_interfaces().update(interfaces)
        self[CONN_INTERFACE_PRESENCE].connect_to_signal('PresenceUpdate', self.presence_update_signal_cb)
        gobject.idle_add(self.connected_cb)

    def status_changed_signal_cb(self, status, reason):
        if self._status == status:
            return
        else:
            self._status = status

        print 'StatusChanged', status, reason

        if status == CONNECTION_STATUS_CONNECTED:
            print "connection connected"
            self[CONN_INTERFACE].GetInterfaces(reply_handler=self.get_interfaces_reply_cb, error_handler=self.error_cb)
        if status == CONNECTION_STATUS_DISCONNECTED:
            print "connection terminated"
            self._mainloop.quit()

if __name__ == '__main__':
    reg = telepathy.client.ManagerRegistry()
    reg.LoadManagers()

    protocol=''
    protos=reg.GetProtos()

    if len(protos) == 0:
        print "Sorry, no connection managers found!"
        sys.exit(1)

    if len(sys.argv) > 2:
        protocol = sys.argv[2]
    else:
        while (protocol not in protos):
            protocol = raw_input('Protocol (one of: %s) [%s]: ' % (' '.join(protos),protos[0]))
            if protocol == '':
                protocol = protos[0]

    manager=''
    managers=reg.GetManagers(protocol)

    while (manager not in managers):
        if len(sys.argv) > 1:
            manager = sys.argv[1]
        else:
            manager = raw_input('Manager (one of: %s) [%s]: ' % (' '.join(managers),managers[0]))
            if manager == '':
                manager = managers[0]

    mgr_bus_name = reg.GetBusName(manager)
    mgr_object_path = reg.GetObjectPath(manager)

    cmdline_params = dict((p.split('=') for p in sys.argv[3:]))
    print "got commandline params: ",cmdline_params
    params={}

    for (name, (type, default)) in reg.GetParams(manager, protocol)[0].iteritems():
        if name in cmdline_params:
            params[name] = dbus.Variant(cmdline_params[name],type)
        elif name == 'password':
            params[name] = dbus.Variant(getpass.getpass(),type)
        else:
            params[name] = dbus.Variant(raw_input(name+': '),type)

    mgr = telepathy.client.ConnectionManager(mgr_bus_name, mgr_object_path)
    print "using params:",params
    bus_name, object_path = mgr[CONN_MGR_INTERFACE].Connect(protocol, params)
    print "done connect"
    mainloop = gobject.MainLoop()
    connection = TestConnection(bus_name, object_path, mainloop)
    print "created connection"
    def quit_cb():
        connection[CONN_INTERFACE].Disconnect()
        mainloop.quit()

    def sigterm_cb():
        gobject.idle_add(quit_cb)

    signal.signal(signal.SIGTERM, sigterm_cb)

    while mainloop.is_running():
        try:
            mainloop.run()
        except KeyboardInterrupt:
            quit_cb()
<|endoftext|>


<commit_before>#!/usr/bin/env python

import unittest
import subprocess
import time
import sys

import psutil

from test_psutil import kill, PYTHON, DEVNULL

def sh(cmd):
    """Execute a shell command and return its output."""
    if not sys.platform.lower().startswith("linux"):
        cmd = cmd.replace(" --no-headers ", " ")
    p = subprocess.Popen(cmd, shell=1, stdout=subprocess.PIPE)
    output = p.communicate()[0].strip()
    if not sys.platform.lower().startswith("linux"):
        output = output.split()[1]
    return output

class PosixSpecificTestCase(unittest.TestCase):
    """Compare psutil results against 'ps' command line utility."""

    # for ps -o arguments see: http://unixhelp.ed.ac.uk/CGI/man-cgi?ps

    def setUp(self):
        self.pid = subprocess.Popen(PYTHON, stdout=DEVNULL, stderr=DEVNULL).pid

    def tearDown(self):
        kill(self.pid)

    def test_process_parent_pid(self):
        ppid_ps = sh("ps --no-headers -o ppid -p %s" %self.pid)
        ppid_psutil = psutil.Process(self.pid).ppid
        self.assertEqual(ppid_ps, str(ppid_psutil))

    def test_process_uid(self):
        uid_ps = sh("ps --no-headers -o euid -p %s" %self.pid)
        uid_psutil = psutil.Process(self.pid).uid
        self.assertEqual(uid_ps, str(uid_psutil))

    def test_process_gid(self):
        gid_ps = sh("ps --no-headers -o egid -p %s" %self.pid)
        gid_psutil = psutil.Process(self.pid).uid
        self.assertEqual(gid_ps, str(gid_psutil))

    def test_process_username(self):
        username_ps = sh("ps --no-headers -o user -p %s" %self.pid)
        username_psutil = psutil.Process(self.pid).username
        self.assertEqual(username_ps, username_psutil)

    def test_process_groupname(self):
        groupname_ps = sh("ps --no-headers -o egroup -p %s" %self.pid)
        groupname_psutil = psutil.Process(self.pid).groupname
        self.assertEqual(groupname_ps, groupname_psutil)

    def test_process_rss_memory(self):
        # give python interpreter some time to properly initialize
        # so that the results are the same
        time.sleep(0.1)
        rss_ps = sh("ps --no-headers -o rss -p %s" %self.pid)
        rss_psutil = psutil.Process(self.pid).get_memory_info()[0] / 1024
        self.assertEqual(rss_ps, str(rss_psutil))

    def test_process_vsz_memory(self):
        # give python interpreter some time to properly initialize
        # so that the results are the same
        time.sleep(0.1)
        vsz_ps = sh("ps --no-headers -o vsz -p %s" %self.pid)
        vsz_psutil = psutil.Process(self.pid).get_memory_info()[1] / 1024
        self.assertEqual(vsz_ps, str(vsz_psutil))

    def test_process_create_time(self):
        start_ps = sh("ps --no-headers -o start -p %s" %self.pid)
        start_psutil = psutil.Process(self.pid).create_time
        start_psutil = time.strftime("%H:%M:%S", time.localtime(start_psutil))
        self.assertEqual(start_ps, start_psutil)
<commit_msg>used -o args which works with Linux and BSD thanks to aliases provided by Linux. Only one test is failing on BSD now.<commit_after>#!/usr/bin/env python

import unittest
import subprocess
import time
import sys

import psutil

from test_psutil import kill, PYTHON, DEVNULL

def sh(cmd):
    """Execute a shell command and return its output."""
    if not sys.platform.lower().startswith("linux"):
        cmd = cmd.replace(" --no-headers ", " ")
    p = subprocess.Popen(cmd, shell=1, stdout=subprocess.PIPE)
    output = p.communicate()[0].strip()
    if not sys.platform.lower().startswith("linux"):
        output = output.split()[1]
    return output

class PosixSpecificTestCase(unittest.TestCase):
    """Compare psutil results against 'ps' command line utility."""

    # for ps -o arguments see: http://unixhelp.ed.ac.uk/CGI/man-cgi?ps

    def setUp(self):
        self.pid = subprocess.Popen(PYTHON, stdout=DEVNULL, stderr=DEVNULL).pid

    def tearDown(self):
        kill(self.pid)

    def test_process_parent_pid(self):
        ppid_ps = sh("ps --no-headers -o ppid -p %s" %self.pid)
        ppid_psutil = psutil.Process(self.pid).ppid
        self.assertEqual(ppid_ps, str(ppid_psutil))

    def test_process_uid(self):
        uid_ps = sh("ps --no-headers -o uid -p %s" %self.pid)
        uid_psutil = psutil.Process(self.pid).uid
        self.assertEqual(uid_ps, str(uid_psutil))

    def test_process_gid(self):
        gid_ps = sh("ps --no-headers -o rgid -p %s" %self.pid)
        gid_psutil = psutil.Process(self.pid).uid
        self.assertEqual(gid_ps, str(gid_psutil))

    def test_process_username(self):
        username_ps = sh("ps --no-headers -o user -p %s" %self.pid)
        username_psutil = psutil.Process(self.pid).username
        self.assertEqual(username_ps, username_psutil)

    def test_process_groupname(self):
        groupname_ps = sh("ps --no-headers -o rgroup -p %s" %self.pid)
        groupname_psutil = psutil.Process(self.pid).groupname
        self.assertEqual(groupname_ps, groupname_psutil)

    def test_process_rss_memory(self):
        # give python interpreter some time to properly initialize
        # so that the results are the same
        time.sleep(0.1)
        rss_ps = sh("ps --no-headers -o rss -p %s" %self.pid)
        rss_psutil = psutil.Process(self.pid).get_memory_info()[0] / 1024
        self.assertEqual(rss_ps, str(rss_psutil))

    def test_process_vsz_memory(self):
        # give python interpreter some time to properly initialize
        # so that the results are the same
        time.sleep(0.1)
        vsz_ps = sh("ps --no-headers -o vsz -p %s" %self.pid)
        vsz_psutil = psutil.Process(self.pid).get_memory_info()[1] / 1024
        self.assertEqual(vsz_ps, str(vsz_psutil))

    def test_process_create_time(self):
        start_ps = sh("ps --no-headers -o start -p %s" %self.pid)
        start_psutil = psutil.Process(self.pid).create_time
        start_psutil = time.strftime("%H:%M:%S", time.localtime(start_psutil))
        self.assertEqual(start_ps, start_psutil)
<|endoftext|>