Esempio n. 1
0
def main():
    
    log.setLevel(logging.INFO)
    #log.setLevel(logging.DEBUG)
    # create console handler 
    ch = logging.StreamHandler()
    #logging.basicConfig()
    # create formatter
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    # add formatter to ch
    ch.setFormatter(formatter)
    # add ch to logger
    log.addHandler(ch)

    cfgfile = ""
    if len(sys.argv) <= 1:
        files = os.listdir(os.getcwd())        
        files = filter(lambda x: os.path.splitext(x)[1]=='.conf',files)
        
        if len(files)==0:
            log.critical("No config file found!")
            exit(-1)
        else:
            cfgfile = files[0]            
            log.warn ("Using auto detecting config file: '%s'", cfgfile)            
    else:
        cfgfile = sys.argv[1]
        log.info("Reading config file '%s'", cfgfile)
                    
    try:
        config = ConfigParser.ConfigParser()
        config.read (cfgfile)        
    except:
        log.exception("failed to read config file")
        exit(-2)
    
    port = config.get('wattnode', 'port')
    
    req_opts = ['address', 'ctamps', 'averaging']    
        
    wnconfig = {}
    for n in req_opts:
        wnconfig[n] = config.getint('wattnode', n)    
        
    log.info ("Opening '%s', config = %s" % (port,wnconfig))
    p = SerialModbusClient(); 
    p.open(port)
    
    serno = p.doRequest(
            makeReadReg(
                wnconfig['address'], 1700,2),decodeInt32) [0]
                
    # turn off averaging
    p.doRequest(makeWriteReg(wnconfig['address'],1607,wnconfig['averaging']))
    
    # setup for 15A ct
    p.doRequest(makeWriteReg(wnconfig['address'],1602,wnconfig['ctamps']))  
    
    log.info ("starting server")
               
    try:
        serve(p)        
    except KeyboardInterrupt:            
        print "Shutting down"
    except:
        log.critical(traceback.format_exc())            

    p.close()    
Esempio n. 2
0
def main():
    log, tty = createLogger('/home/alan/pywattnode.log')#createLogger('/var/log/pywattnode.log')
    config = readConfig(log, '/etc/pywattnode.conf')

    port_prefix = config.get('wattnode', 'port')

    count = config.getint('wattnode', 'count')

    wnconfig = []
    req_opts = ['address', 'ctamps', 'averaging', 'phase', 'ctdirections']
    for i in range (1, count+1):
        cfg = {}
        for n in req_opts:
            cfg[n] = config.getint('wattnode%d'%(i), n)
        wnconfig.append(cfg)

    

#---- main run loop
    while True:
        for port in detectDev(log, port_prefix):
            log.info ("Opening '%s', config = %s" % (port,wnconfig))
            p = None
            try:
                p = SerialModbusClient(log)

                success = False
                serno = None
                while success == False:
                    try:
                        p.open(port)

                        log.info ("Reading wattnode serial numbers...")

                        for i in range(0, len(wnconfig)):
                            #read serial no
                            serno = p.doRequest(
                                                makeReadReg(
                                                wnconfig[i]['address'], 1700,2),decodeInt32) [0]
                            log.info ("Got wattnode serial number: %d", serno)

                            log.info ("Configuring averaging (%d)..."%(wnconfig[i]['averaging']))
                            # turn off averaging
                            p.doRequest(makeWriteReg(wnconfig[i]['address'],1607,wnconfig[i]['averaging']))

                            log.info ("Configuring CT amps (%d)..."%(wnconfig[i]['ctamps']))
                            # setup for 15A ct
                            p.doRequest(makeWriteReg(wnconfig[i]['address'],1602,wnconfig[i]['ctamps']))

                            log.info ("Configuring CT direction (%d)..."%(wnconfig[i]['ctdirections']))
                            p.doRequest(makeWriteReg(wnconfig[i]['address'],1606,wnconfig[i]['ctdirections']))

                            log.info ("Configuring phase offset (%d)..."%(wnconfig[i]['phase']))
                            p.doRequest(makeWriteReg(wnconfig[i]['address'],1618,wnconfig[i]['phase']))

                        success = True

                    except serial.SerialException, msg:
                        log.error("Failed to open port, will retry: %s", msg)
                        time.sleep(15)
                    except ModbusException, msg:
                        log.error("Modbus error during init, will retry: %s", msg)
                        time.sleep(15)

                log.info ("Setup complete, starting logger")

                try:
                    runlog(p, wnconfig, config, log, tty, serno)
                except KeyboardInterrupt:
                    log.critical("Shutting down")
                    p.close()
                    exit(1)
                except SystemExit:
                    log.critical("Exit() called, shutting down")
                    p.close()
                    raise
                except Exception as x:
                    log.critical(x)
                    log.critical(traceback.format_exc())
Esempio n. 3
0
def main():
    log, tty = createLogger(
        '/home/alan/pywattnode.log')  #createLogger('/var/log/pywattnode.log')
    config = readConfig(log, '/etc/pywattnode.conf')

    port_prefix = config.get('wattnode', 'port')

    count = config.getint('wattnode', 'count')

    wnconfig = []
    req_opts = ['address', 'ctamps', 'averaging', 'phase', 'ctdirections']
    for i in range(1, count + 1):
        cfg = {}
        for n in req_opts:
            cfg[n] = config.getint('wattnode%d' % (i), n)
        wnconfig.append(cfg)

#---- main run loop
    while True:
        for port in detectDev(log, port_prefix):
            log.info("Opening '%s', config = %s" % (port, wnconfig))
            p = None
            try:
                p = SerialModbusClient(log)

                success = False
                serno = None
                while success == False:
                    try:
                        p.open(port)

                        log.info("Reading wattnode serial numbers...")

                        for i in range(0, len(wnconfig)):
                            #read serial no
                            serno = p.doRequest(
                                makeReadReg(wnconfig[i]['address'], 1700, 2),
                                decodeInt32)[0]
                            log.info("Got wattnode serial number: %d", serno)

                            log.info("Configuring averaging (%d)..." %
                                     (wnconfig[i]['averaging']))
                            # turn off averaging
                            p.doRequest(
                                makeWriteReg(wnconfig[i]['address'], 1607,
                                             wnconfig[i]['averaging']))

                            log.info("Configuring CT amps (%d)..." %
                                     (wnconfig[i]['ctamps']))
                            # setup for 15A ct
                            p.doRequest(
                                makeWriteReg(wnconfig[i]['address'], 1602,
                                             wnconfig[i]['ctamps']))

                            log.info("Configuring CT direction (%d)..." %
                                     (wnconfig[i]['ctdirections']))
                            p.doRequest(
                                makeWriteReg(wnconfig[i]['address'], 1606,
                                             wnconfig[i]['ctdirections']))

                            log.info("Configuring phase offset (%d)..." %
                                     (wnconfig[i]['phase']))
                            p.doRequest(
                                makeWriteReg(wnconfig[i]['address'], 1618,
                                             wnconfig[i]['phase']))

                        success = True

                    except serial.SerialException, msg:
                        log.error("Failed to open port, will retry: %s", msg)
                        time.sleep(15)
                    except ModbusException, msg:
                        log.error("Modbus error during init, will retry: %s",
                                  msg)
                        time.sleep(15)

                log.info("Setup complete, starting logger")

                try:
                    runlog(p, wnconfig, config, log, tty, serno)
                except KeyboardInterrupt:
                    log.critical("Shutting down")
                    p.close()
                    exit(1)
                except SystemExit:
                    log.critical("Exit() called, shutting down")
                    p.close()
                    raise
                except Exception as x:
                    log.critical(x)
                    log.critical(traceback.format_exc())