def __init__(self, configFile, simulation):
     if os.path.exists(configFile):
         self.config = CustomConfigObj(configFile)
     else:
         print "Configuration file not found: %s" % configFile
         sys.exit(1)
     self.simulation = simulation
     self.battery_monitor = BatteryVoltageMonitor()
     self.alarmStatus = AlarmRegister()
     self.driver = None
     self.inst_mgr = None
     self.logger = None
    plt.show()
    #pylab.close()


if (tkMessageBox.askokcancel(title="Saving Calibration factor", message="Save the Calibration value, OK or Cancel") == 1):
    tkMessageBox.showinfo(title="Saving Calibration factor", message="You selected OK option")

    #
    # Open the configuration file and read the slope and intercept values
    #
    now = datetime.datetime.now()
    src = 'C:\Picarro\G2000\InstrConfig\Calibration\InstrCal\InstrCal_Air.ini'
    n = "_old_%s-%s-%s_%s%s%s.ini" % (now.year,now.month,now.day,now.hour,now.minute,now.second)
    dst = src.replace(".ini",n)
    shutil.copy(src,dst)
    config = CustomConfigObj('C:\Picarro\G2000\InstrConfig\Calibration\InstrCal\InstrCal_Air.ini')
    old_inter1816 = config.getfloat("Data", "delta_18o_intercept", 0)
    old_slope1816 = config.getfloat("Data", "delta_18o_slope", 1)
    old_interDH = config.getfloat("Data", "delta_d_intercept", 0)
    old_slopeDH = config.getfloat("Data", "delta_d_slope", 1)

    fname = directory + "\\" + basename + "_CalibrationValues.txt"
    print fname
    txtfile = open(fname, "wt")
    lines = []

    lines.append("*****Slope and Intercept values before Calibration*****")
    lines.append("\n\nSlope for 18_16 before calibration = %10s" % old_slope1816)
    lines.append("\nIntercept for 18_16 before calibration = %10s" % old_inter1816)
    lines.append("\nSlope for D_H before calibration = %10s" % old_slopeDH)
    lines.append("\nIntercept for D_H before calibration = %10s" % old_interDH)
files = open('C:\Picarro\G2000\InstrConfig\Calibration\InstrCal\Beta2000_HotBoxCal.ini', 'r')
filedata = files.read()
files.close()

#
#Save a copy of the HotBoxCal.ini to backup the Squish data
#
files = open('C:\Picarro\G2000\InstrConfig\Calibration\InstrCal\Beta2000_HotBoxCal_presquish_' + y + '_' + t + '.ini', "w")
files.write(filedata) 
files.close()

#
# Ask the user to enter the squish value
#
squish = float(raw_input("Enter the squish value for the instrument: "))
config = CustomConfigObj('C:\Picarro\G2000\InstrConfig\Calibration\InstrCal\Beta2000_HotBoxCal.ini')

#
# Read the FSR value from the hotboxcal.ini
#
old_fsr = config.getfloat("AUTOCAL", "CAVITY_FSR", 0)

#
# Compute the Squish value and update the value in the hotboxcal.ini file
#
new_fsr = (1+squish)*old_fsr
config.set("AUTOCAL", "CAVITY_FSR", new_fsr)
config.write()

print "\nThe corrected Squish value is: " + str(new_fsr)
# Label the axes
pylab.axis(v)
pylab.xlabel('Measured value')
pylab.ylabel('Expected value')
pylab.title('CH4 Calibration')
pylab.draw()

# Save the matlab plot in the location specified by fname
fname = 'Z:\Standard Tests\HKDS\CH4_Calibration\CH4_cal'
pylab.savefig(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None)
pylab.close()

#Save the slope and intercept in the N2 cal file
config = CustomConfigObj('C:\Picarro\G2000\InstrConfig\Calibration\InstrCal\InstrCal_LCT_N2.ini')
# Update the intercept value
config.getfloat("Data", "ch4_conc_intercept", 0)
config.set("Data", "ch4_conc_intercept", intercept)
config.write()
# Update the slope value
config.getfloat("Data", "ch4_conc_slope", 1)
config.set("Data", "ch4_conc_slope", slope)
config.write()

#Save the slope and intercept in the ZA cal file
config = CustomConfigObj('C:\Picarro\G2000\InstrConfig\Calibration\InstrCal\InstrCal_LCT_Air.ini')
# Update the intercept value
config.getfloat("Data", "ch4_conc_intercept", 0)
config.set("Data", "ch4_conc_intercept", intercept)
config.write()
class BackpackServer(object):
    def __init__(self, configFile, simulation):
        if os.path.exists(configFile):
            self.config = CustomConfigObj(configFile)
        else:
            print "Configuration file not found: %s" % configFile
            sys.exit(1)
        self.simulation = simulation
        self.battery_monitor = BatteryVoltageMonitor()
        self.alarmStatus = AlarmRegister()
        self.driver = None
        self.inst_mgr = None
        self.logger = None

    def loadConfig(self):
        self.setup = {
            'host': self.config.get('Setup', "Host_IP", "0.0.0.0"),
            'port': self.config.getint('Setup', "Port", 3000),
            'debug': self.config.getboolean('Setup', "Debug_Mode", True)
        }
        self.userlog = self.config.get('Setup', "UserLog_Files")
        self.battery_monitor.pointsTriggerAlarm = self.config.getint(
            "BatteryMonitor", "Points_Trigger_Alarm", 10)
        self.battery_monitor.pointsCancelAlarm = self.config.getint(
            "BatteryMonitor", "Points_Cancel_Alarm", 3)
        self.battery_monitor.voltageThreshold = self.config.getfloat(
            "BatteryMonitor", "Voltage_Threshold", 18.9)
        if self.simulation:
            self.simulation_dict = {}
            if self.config.has_option('Simulation', 'Replay_Data'):
                replay_data = self.config.get('Simulation', 'Replay_Data', '')
                self.simulation_dict["Files"] = replay_data.split(',')
                for f in self.simulation_dict["Files"]:
                    if not os.path.exists(f):
                        raise Exception("Data file not found: %s" % f)
                self.simulation_dict["CurrentFile"] = self.simulation_dict[
                    "Files"][0]
                self.simulation_dict["CurrentFileIndex"] = 0
                fp = open(self.simulation_dict["Files"][0], 'r')
                self.simulation_dict["CurrentFileHeader"] = fp.readline(
                ).split()
                self.simulation_dict["CurrentFileHandle"] = fp
            else:
                self.simulation_dict["CH4"] = self.config.get(
                    'Simulation', 'CH4', '')
                self.simulation_dict["CO2"] = self.config.get(
                    'Simulation', 'CO2', '')
                self.simulation_dict["H2O"] = self.config.get(
                    'Simulation', 'H2O', '')
                self.simulation_dict["Battery"] = self.config.get(
                    'Simulation', 'BatteryVoltage', '')
                self.simulation_env = {
                    func: getattr(math, func)
                    for func in dir(math) if not func.startswith("__")
                }
                self.simulation_max_index = self.config.getint(
                    'Simulation', 'Max_Index', 100)
                self.simulation_index_increment = 1

    def getData(self, startRow):
        if self.simulation:
            return self.simulate_data(startRow)
        name = self._getFileName()
        if name is not None:
            fp = file(name, 'rb')
        else:
            return {'filename': ''}
        fp.seek(0, 0)
        header = fp.readline().split()
        data = dict(EPOCH_TIME=[], CH4=[], CO2=[], H2O=[])
        lineLength = fp.tell()
        fp.seek(0, 2)
        if fp.tell() < startRow * lineLength:
            startRow = 1
        fp.seek(startRow * lineLength, 0)
        for line in fp:
            if len(line) != lineLength:
                break
            vals = line.split()
            if len(vals) != len(header):
                break
            for col, val in zip(header, vals):
                if col in data:
                    data[col].append(float(val))
                if col == "Battery_Voltage":
                    self.alarmStatus.setAlarm(
                        "battery_voltage",
                        self.battery_monitor.checkValue(float(val)))
            startRow += 1
        fp.close()
        result = {
            "next_row": startRow,
            "file_name": name,
            "alarm": self.alarmStatus.register,
            "data": data
        }
        return result

    def _getFileName(self):
        try:
            year = max(os.listdir(self.userlog))
            month = max(os.listdir(os.path.join(self.userlog, year)))
            day = max(os.listdir(os.path.join(self.userlog, year, month)))
            names = sorted(
                glob.glob(os.path.join(self.userlog, year, month, day,
                                       "*.dat")))
            return names[-1]
        except:
            return None

    def simulate_data(self, startRow):
        if "Files" in self.simulation_dict:  # replay data from files
            data = dict(EPOCH_TIME=[], CH4=[], CO2=[], H2O=[])
            fp = self.simulation_dict["CurrentFileHandle"]
            buf = fp.readline()
            while len(buf) == 0:  # reach the end of file
                fp.close()
                self.simulation_dict["CurrentFileIndex"] += 1
                if self.simulation_dict["CurrentFileIndex"] >= len(
                        self.simulation_dict["Files"]):
                    self.simulation_dict["CurrentFileIndex"] = 0
                self.simulation_dict["CurrentFile"] = self.simulation_dict[
                    "Files"][self.simulation_dict["CurrentFileIndex"]]
                fp = open(self.simulation_dict["CurrentFile"], "r")
                self.simulation_dict["CurrentFileHeader"] = fp.readline(
                ).split()
                self.simulation_dict["CurrentFileHandle"] = fp
                buf = fp.readline()
            vals = buf.split()
            for col, val in zip(self.simulation_dict["CurrentFileHeader"],
                                vals):
                if col == "Battery_Voltage":
                    self.alarmStatus.setAlarm(
                        "battery_voltage",
                        self.battery_monitor.checkValue(float(val)))
                elif col in data:
                    data[col].append(float(val))
            result = {
                "next_row": -1,
                "file_name": self.simulation_dict["CurrentFile"],
                "alarm": self.alarmStatus.register,
                "data": data
            }
        else:  # calculate data from predefined functions
            data = {}
            for k in self.simulation_dict:
                if k == "Battery":
                    self.alarmStatus.setAlarm(
                        "battery_voltage",
                        self.battery_monitor.checkValue(
                            self.run_simulation_expression(
                                self.simulation_dict[k], startRow)))
                else:
                    data[k] = [
                        self.run_simulation_expression(self.simulation_dict[k],
                                                       startRow)
                    ]
            data["EPOCH_TIME"] = [time.time()]
            if startRow == self.simulation_max_index:
                self.simulation_index_increment = -1
            elif startRow == 1:
                self.simulation_index_increment = 1
            result = {
                "next_row": startRow + self.simulation_index_increment,
                "file_name": "simulation",
                "alarm": self.alarmStatus.register,
                "data": data
            }
        return result

    def run_simulation_expression(self, expression, startRow):
        if len(expression) > 0:
            self.simulation_env["x"] = startRow
            exec "simulation_result=" + expression in self.simulation_env
            return self.simulation_env["simulation_result"]
        else:
            return 0.0

    def act_on_command(self, command):
        if command == "shutdown":
            if self.simulation:
                print "Shut down analyzer per request of the user."
            else:
                self.inst_mgr.INSTMGR_ShutdownRpc(
                    2)  # Turn Off Analyzer in Current State
        elif command == "restartUserlog":
            if self.simulation:
                print "Restart userlog per request of the user."
            else:
                self.logger.startUserLogs(["DataLog_User_Minimal"], True)
        elif command == "about":
            if self.simulation:
                print "Version information requested."
                return {
                    'host release': 'mobile-2.4.2.24 (3102146b)',
                    'config - app version no': '1.0.5',
                    'config - instr version no': '9fa0b2b'
                }
            else:
                return self.driver.allVersions()

    def run(self):
        self.loadConfig()