def open(self, port='/dev/ttyUSB0', baudrate=9600): mdbus.SerialModbusClient.open(self,port,baudrate) self.scalar = [1]*6 self.ctValue = [0]*6 for meter in range(0,6): #self.ident(meter) #model = self.getModelName(meter) #mnum = self.getModelNumber(meter) #self.log.debug("Model name: %s Model number: %s"%(model,mnum)) addr = self.baseAddress + meter #ensure DENT format #self.doRequest( # mdbus.makeWriteReg( # addr, 4525, 0)) #self.ident(meter) #self.log ("setScaling to 1") #self.setScaling(meter, 1) #self.log.info('addr is %d'%addr) tmp = self.doRequest( mdbus.makeReadReg( addr, 4300, 2, fnc=3), mdbus.decodeInt16) self.ctValue[meter] = tmp[0] self.scalar[meter] = tmp[1] self.log.info("Meter %d using CT: %d and data scalar: %d"%\ (meter, self.ctValue[meter], self.scalar[meter]))
def getVolts(self, meter): addr = self.baseAddress + meter r = [] res = self.doRequest(mdbus.makeReadReg(addr, 4058, 3, fnc=3), mdbus.decodeInt16) return [PowerScoutClient.V_scalar[self.scalar[meter]] * i for i in res]
def getPf (self,meter): addr = self.baseAddress + meter r = [] res = self.doRequest( mdbus.makeReadReg( addr, 4049, 3, fnc=3),mdbus.decodeInt16) return res
def open(self, port='/dev/ttyUSB0', baudrate=9600): mdbus.SerialModbusClient.open(self, port, baudrate) self.scalar = [1] * 6 self.ctValue = [0] * 6 for meter in range(0, 6): #self.ident(meter) #model = self.getModelName(meter) #mnum = self.getModelNumber(meter) #self.log.debug("Model name: %s Model number: %s"%(model,mnum)) addr = self.baseAddress + meter #ensure DENT format #self.doRequest( # mdbus.makeWriteReg( # addr, 4525, 0)) #self.ident(meter) #self.log ("setScaling to 1") #self.setScaling(meter, 1) #self.log.info('addr is %d'%addr) tmp = self.doRequest(mdbus.makeReadReg(addr, 4300, 2, fnc=3), mdbus.decodeInt16) self.ctValue[meter] = tmp[0] self.scalar[meter] = tmp[1] self.log.info("Meter %d using CT: %d and data scalar: %d"%\ (meter, self.ctValue[meter], self.scalar[meter]))
def readAll(self, meter): addr = self.baseAddress + meter #print PowerScoutClient.reg_names #print "reading", len(PowerScoutClient.reg_names), 'starting from', PowerScoutClient.base_reg data = self.doRequest( mdbus.makeReadReg(addr, PowerScoutClient.base_reg, len(PowerScoutClient.reg_names), fnc=3), mdbus.decodeInt16) res = {} for i in range(0, len(PowerScoutClient.reg_names)): if 'LSW' == PowerScoutClient.reg_names[i][-3:]: name = PowerScoutClient.reg_names[i][:-4] if not name in res: res[name] = 0 res[name] += data[i] elif 'MSW' == PowerScoutClient.reg_names[i][-3:]: name = PowerScoutClient.reg_names[i][:-4] if not name in res: res[name] = 0 res[name] += (data[i] << 16) else: res[PowerScoutClient.reg_names[i]] = data[i] self._scale(res, meter) return res
def getVolts(self,meter): addr = self.baseAddress + meter r = [] res = self.doRequest( mdbus.makeReadReg( addr, 4058, 3, fnc=3),mdbus.decodeInt16) return [PowerScoutClient.V_scalar[self.scalar[meter]]*i for i in res]
def getVerisPower(self,meter): """returns power in watts for each of L1, L2, and L3""" addr = self.baseAddress + meter r = [] res = self.doRequest( mdbus.makeReadReg( #addr, 4009, 3, fnc=3),mdbus.decodeInt16) addr, 9, 3, fnc=3),mdbus.decodeInt16) return [1000.0*PowerScoutClient.veris_kW_scalar[self.scalar[meter]]*i for i in res]
def getPower(self, meter): """returns power in watts for each of L1, L2, and L3""" addr = self.baseAddress + meter r = [] res = self.doRequest( mdbus.makeReadReg( #addr, 4009, 3, fnc=3),mdbus.decodeInt16) addr, 4028, 3, fnc=3), mdbus.decodeInt16) return [ PowerScoutClient.kW_scalar[self.scalar[meter]] * i for i in res ]
def readAll (self, meter): addr = self.baseAddress + meter #print PowerScoutClient.reg_names #print "reading", len(PowerScoutClient.reg_names), 'starting from', PowerScoutClient.base_reg data = self.doRequest( mdbus.makeReadReg( addr, PowerScoutClient.base_reg, len(PowerScoutClient.reg_names), fnc=3), mdbus.decodeInt16) res = {} for i in range (0, len(PowerScoutClient.reg_names)): if 'LSW' == PowerScoutClient.reg_names[i][-3:]: name = PowerScoutClient.reg_names[i][:-4] if not name in res: res[name] = 0 res[name] += data[i] elif 'MSW' == PowerScoutClient.reg_names[i][-3:]: name = PowerScoutClient.reg_names[i][:-4] if not name in res: res[name] = 0 res[name] += (data[i]<<16) else: res[PowerScoutClient.reg_names[i]] = data[i] self._scale(res, meter) return res
def runlog(p, wnconfig, config, log, tty, serno): dbtype = config.get('db', 'dbtype') if dbtype == 'mysql': db= mysql_dblogger(config, log) elif dbtype == 'couchdb': db= couch_dblogger(config, log) elif dbtype == 'plotwatt': from plotwatt import dblogger as plotwatt_dblogger db = plotwatt_dblogger(config, log) elif dbtype == 'opentsdb': from opentsdb_wn import dblogger db = dblogger(config, serno) else: raise Exception("dbtype ('%s') not supported."%(dbtype)) log.info('database connected') mq = None try: period_sec = timedelta(seconds = config.getint('wattnode', 'period_sec')) mq = mqClient(config, serno) #regs = [] #for i in range(0, len(wnconfig)): #t = config.get('wattnode%d'%(i+1), 'regs') #t = [int(i) for i in t.split(',')] #regs.append (t) while True: start = datetime.utcnow() output = "" for i in range(0, len(wnconfig)): basic = p.doRequest(makeReadReg(wnconfig[i]['address'], 1000, 34), decodeBasicFp) adv = p.doRequest(makeReadReg(wnconfig[i]['address'], 1100, 76), decodeAdvancedFp) # merge the dicts data = dict (basic, **adv) data['address']= wnconfig[i]['address'] data['time'] = start #for key,value in data.iteritems(): #log.info("%20s = %9.3f"%('address',data['address'])) #for key in __wattNodeBasicVars: # log.info("%20s = %9.3f"%(key,data[key])) output += "\n%20s = %9d\n"%('address',data['address']) for i in range(0, len(__wattNodeBasicVars), 4): output += "".join ( ["%20s = %9.3f"%(key,data[key]) for key in __wattNodeBasicVars[i:i+4]]) output += "\n" #output += "\n".join( ["%20s = %9.3f"%(key,data[key]) for key in __wattNodeBasicVars]) output += "\n" for i in range(0, len(__wattNodeAdvancedVars), 4): output += "".join ( ["%20s = %9.3f"%(key,data[key]) for key in __wattNodeAdvancedVars[i:i+4]]) output += "\n" #output += "\n".join( ["%20s = %9.3f"%(key,data[key]) for key in __wattNodeAdvancedVars]) db.logit(data) mq.pub(data) #if tty: #log.info(output) sleep = period_sec - (datetime.utcnow() - start) sleep_s = (sleep.days * 86400) + sleep.seconds + (sleep.microseconds / 1000000.0) log.info('took %s seconds; sleep time is %f seconds', period_sec - sleep, sleep_s) if sleep_s > 0: time.sleep(sleep_s) else: log.warning('took %s seconds; not meeting timing spec.', period_sec - sleep) finally: db.close() if mq: mq.close()
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()
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())
def getModelNumber(self, meter): addr = self.baseAddress + meter return self.doRequest(mdbus.makeReadReg(addr, 4205, 5, fnc=3), mdbus.decodeAscii)
def getSystemPower(self,meter): addr = self.baseAddress + meter res = self.doRequest(mdbus.makeReadReg( addr, 4002, 1, fnc=3),mdbus.decodeInt16)[0] return res
def getPf(self, meter): addr = self.baseAddress + meter r = [] res = self.doRequest(mdbus.makeReadReg(addr, 4049, 3, fnc=3), mdbus.decodeInt16) return res
def getSystemPower(self, meter): addr = self.baseAddress + meter res = self.doRequest(mdbus.makeReadReg(addr, 4002, 1, fnc=3), mdbus.decodeInt16)[0] return res
def getModelNumber(self,meter): addr = self.baseAddress + meter return self.doRequest( mdbus.makeReadReg( addr, 4205, 5, fnc=3),mdbus.decodeAscii)
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())
def runlog(p, wnconfig, config, log, tty, serno): dbtype = config.get('db', 'dbtype') if dbtype == 'mysql': db = mysql_dblogger(config, log) elif dbtype == 'couchdb': db = couch_dblogger(config, log) elif dbtype == 'plotwatt': from plotwatt import dblogger as plotwatt_dblogger db = plotwatt_dblogger(config, log) elif dbtype == 'opentsdb': from opentsdb_wn import dblogger db = dblogger(config, serno) else: raise Exception("dbtype ('%s') not supported." % (dbtype)) log.info('database connected') mq = None try: period_sec = timedelta(seconds=config.getint('wattnode', 'period_sec')) mq = mqClient(config, serno) #regs = [] #for i in range(0, len(wnconfig)): #t = config.get('wattnode%d'%(i+1), 'regs') #t = [int(i) for i in t.split(',')] #regs.append (t) while True: start = datetime.utcnow() output = "" for i in range(0, len(wnconfig)): basic = p.doRequest( makeReadReg(wnconfig[i]['address'], 1000, 34), decodeBasicFp) adv = p.doRequest( makeReadReg(wnconfig[i]['address'], 1100, 76), decodeAdvancedFp) # merge the dicts data = dict(basic, **adv) data['address'] = wnconfig[i]['address'] data['time'] = start #for key,value in data.iteritems(): #log.info("%20s = %9.3f"%('address',data['address'])) #for key in __wattNodeBasicVars: # log.info("%20s = %9.3f"%(key,data[key])) output += "\n%20s = %9d\n" % ('address', data['address']) for i in range(0, len(__wattNodeBasicVars), 4): output += "".join([ "%20s = %9.3f" % (key, data[key]) for key in __wattNodeBasicVars[i:i + 4] ]) output += "\n" #output += "\n".join( ["%20s = %9.3f"%(key,data[key]) for key in __wattNodeBasicVars]) output += "\n" for i in range(0, len(__wattNodeAdvancedVars), 4): output += "".join([ "%20s = %9.3f" % (key, data[key]) for key in __wattNodeAdvancedVars[i:i + 4] ]) output += "\n" #output += "\n".join( ["%20s = %9.3f"%(key,data[key]) for key in __wattNodeAdvancedVars]) db.logit(data) mq.pub(data) #if tty: #log.info(output) sleep = period_sec - (datetime.utcnow() - start) sleep_s = (sleep.days * 86400) + sleep.seconds + ( sleep.microseconds / 1000000.0) log.info('took %s seconds; sleep time is %f seconds', period_sec - sleep, sleep_s) if sleep_s > 0: time.sleep(sleep_s) else: log.warning('took %s seconds; not meeting timing spec.', period_sec - sleep) finally: db.close() if mq: mq.close()