def EstablishConnection(self, comportobj, guihandle, dbfilelocation):
        global trc
        trc.FunctionEntry("EstablishConnection")
        self.ser = comportobj
        self.toCancel = False
        self.guicallback = guihandle

        myparser = CurrentCostDataParser()

        #
        # we create our own connection to the database here
        #
        # we need our own connection to the database because we are running
        #  in a background thread, and pysqlite (used to implement the database)
        #  cannot reuse a connection across multiple threads
        # the connection is relatively low cost, so having two connections open
        #  - one for the GUI thread and one for this background worker thread -
        #  doesn't seem like a burdensome extravagance :-)
        #
        dbconnection = CurrentCostDB()
        dbconnection.InitialiseDB(dbfilelocation)

        #
        # look for the current reading in the data
        #
        line = ""
        receivedHistory = False
        while self.toCancel == False:
            try:
                line = self.ser.readUpdate()

                # try to parse the XML
                currentcoststruct = myparser.parseCurrentCostXML(line)

                if currentcoststruct != None:
                    if 'hist' in currentcoststruct['msg']:
                        # we have received history data - parse and store the CurrentCost
                        #  data in the datastore
                        # the parser will return the number of updates still expected
                        #  (0 if this was the last or only expected update)
                        myparser.storeTimedCurrentCostData(dbconnection)
                        receivedHistory = True
                    elif receivedHistory == True:
                        # we received live data only
                        # if we have received un-graphed history data, we refresh the
                        # graphs now
                        trc.Trace(
                            "finished receiving history data - need to redraw graphs"
                        )
                        self.guicallback.updateGraphs()
                        receivedHistory = False

            except Exception, exception:
                if self.toCancel == False:
                    self.guicallback.exitOnError(
                        'Error reading from COM port: ' + str(exception))
                    trc.Error("Error when closing COM port")
                    trc.Error(str(exception))
                    trc.FunctionExit("EstablishConnection")
                    return
def run(s, db):
    trc = CurrentCostTracer()
    trc.EnableTrace(True)
    trc.InitialiseTraceFile()

    myparser = CurrentCostDataParser()
    while True:
        try:
            line = s.readline()
        except Exception, why:
            print why
            sleep(1)
        else:
            if line:
                line = line.strip()
                currentcoststruct = myparser.parseCurrentCostXML(line)
                if currentcoststruct:
                    print currentcoststruct
                    if currentcoststruct["msg"].has_key("ch1"):
                        w1 = int(currentcoststruct["msg"]["ch1"]["watts"])
                        w2 = int(currentcoststruct["msg"]["ch2"]["watts"])
                        w3 = int(currentcoststruct["msg"]["ch3"]["watts"])
                        t = (w1**2 + w2**2 + w3**2)**0.5
                        print "watts are :", t
                    if currentcoststruct["msg"].has_key("hist"):
                        print "storing history data"
                        myparser.storeTimedCurrentCostData(db)
def run(s, db):
    trc = CurrentCostTracer()
    trc.EnableTrace(True)
    trc.InitialiseTraceFile()

    myparser = CurrentCostDataParser()
    while True:
        try:
            line = s.readline()
        except Exception, why:
            print why
            sleep(1)
        else:
            if line:
                line = line.strip()
                currentcoststruct = myparser.parseCurrentCostXML(line)
                if currentcoststruct:
                    print currentcoststruct
                    if currentcoststruct["msg"].has_key("ch1"):
                        w1 = int(currentcoststruct["msg"]["ch1"]["watts"])
                        w2 = int(currentcoststruct["msg"]["ch2"]["watts"])
                        w3 = int(currentcoststruct["msg"]["ch3"]["watts"])
                        t = (w1**2 + w2**2 + w3**2 ) **0.5
                        print "watts are :", t
                    if currentcoststruct["msg"].has_key("hist"):
                        print "storing history data"
                        myparser.storeTimedCurrentCostData(db)
    def EstablishConnection(self, comportobj, guihandle, dbfilelocation):
        global trc
        trc.FunctionEntry("EstablishConnection")
        self.ser = comportobj
        self.toCancel = False
        self.guicallback = guihandle

        myparser = CurrentCostDataParser()

        #
        # we create our own connection to the database here
        # 
        # we need our own connection to the database because we are running
        #  in a background thread, and pysqlite (used to implement the database) 
        #  cannot reuse a connection across multiple threads
        # the connection is relatively low cost, so having two connections open 
        #  - one for the GUI thread and one for this background worker thread - 
        #  doesn't seem like a burdensome extravagance :-)
        # 
        dbconnection = CurrentCostDB()
        dbconnection.InitialiseDB(dbfilelocation)


        #
        # look for the current reading in the data
        # 
        line = ""
        receivedHistory = False
        while self.toCancel == False:
            try:
                line = self.ser.readUpdate()

                # try to parse the XML
                currentcoststruct = myparser.parseCurrentCostXML(line)
        
                if currentcoststruct != None:
                    if 'hist' in currentcoststruct['msg']:
                        # we have received history data - parse and store the CurrentCost 
                        #  data in the datastore
                        # the parser will return the number of updates still expected 
                        #  (0 if this was the last or only expected update)
                        myparser.storeTimedCurrentCostData(dbconnection)
                        receivedHistory = True
                    elif receivedHistory == True:
                        # we received live data only
                        # if we have received un-graphed history data, we refresh the
                        # graphs now
                        trc.Trace("finished receiving history data - need to redraw graphs")
                        self.guicallback.updateGraphs()
                        receivedHistory = False
                
            except Exception, exception:
                if self.toCancel == False:
                    self.guicallback.exitOnError('Error reading from COM port: ' + str(exception))
                    trc.Error("Error when closing COM port")
                    trc.Error(str(exception))
                    trc.FunctionExit("EstablishConnection")
                    return
def ReadCC(src, bmirror):
    # objects to parse and store the data
    ccdb_ch1 = CurrentCostDataStore()

    # create the parser class
    myparser = CurrentCostDataParser()

    fm = None
    if bmirror:
        i = 0
        fn = "mirrored%03d.data"
        while (os.path.isfile(fn % i)):
            i += 1
        fm = open(fn % i, "w")

    while True:
        # read a line of XML from the CurrentCost meter
        try:
	    line = src.readline()
        except EOFError:
            break
        if fm:
            fm.write(line)
        line = line.rstrip('\r\n')
        if not line:
            break
        if line[0] != '<':
            line = line[1:]
            assert line[0] == '<'

        # get a Python array representation of the XML
        currentcoststruct = myparser.parseCurrentCostXML(line)
        assert currentcoststruct
    
        # examine the reply and print some useful bits from it
        if 'msg' not in currentcoststruct:
            print 'Unknown message format'
        else:
            if 'src' in currentcoststruct['msg']:
                if 'sver' in currentcoststruct['msg']['src']:
                    print 'data from CurrentCost meter : version ' + currentcoststruct['msg']['src']['name'] + '-v' + currentcoststruct['msg']['src']['sver']
                else:
                    print 'data from CurrentCost meter : version ' + currentcoststruct['msg']['src']
            if 'hist' in currentcoststruct['msg']:
                print 'received history data'
                SaveHistoryData(currentcoststruct)
            if 'ch1' in currentcoststruct['msg']:
                print 'received update for channel 1'
            if 'ch2' in currentcoststruct['msg']:
                print 'received update for channel 2'
            if 'ch3' in currentcoststruct['msg']:
                print 'received update for channel 3'

        # store the CurrentCost data in the datastore
        myparser.storeTimedCurrentCostData(ccdb_ch1)