Example #1
0
def main():
    """ Main loop """
    il800 = intellemetrics_il800.IL800(
        "/dev/serial/by-id/" + "usb-Prolific_Technology_Inc." + "_USB-Serial_Controller_D-if00-port0"
    )
    sqm160 = inficon_sqm160.InficonSQM160("/dev/serial/by-id/usb-1a86_USB2.0-Ser_-if00-port0")

    qcm1 = QcmReader(il800)
    qcm1.start()

    qcm2 = QcmReader(sqm160)
    qcm2.start()

    time.sleep(2.5)

    codenames = [
        "pvd309_qcm1_rate",
        "pvd309_qcm1_thickness",
        "pvd309_qcm1_frequency",
        "pvd309_qcm2_rate",
        "pvd309_qcm2_thickness",
        "pvd309_qcm2_frequency",
    ]

    loggers = {}
    loggers[codenames[0]] = ValueLogger(qcm1, comp_val=0.01, comp_type="lin", channel=0)
    loggers[codenames[1]] = ValueLogger(qcm1, comp_val=0.1, comp_type="lin", channel=1)
    loggers[codenames[2]] = ValueLogger(qcm1, comp_val=1, comp_type="lin", channel=2)
    loggers[codenames[3]] = ValueLogger(qcm2, comp_val=0.3, comp_type="lin", channel=0)
    loggers[codenames[4]] = ValueLogger(qcm2, comp_val=0.1, comp_type="lin", channel=1)
    loggers[codenames[5]] = ValueLogger(qcm2, comp_val=1, comp_type="lin", channel=2)
    for name in codenames:
        loggers[name].daemon = True
        loggers[name].start()

    livesocket = LiveSocket("pvd309 qcm logger", codenames)
    livesocket.start()

    socket = DateDataPullSocket("pvd309 qcm", codenames, timeouts=[1.0] * len(codenames))
    socket.start()

    db_logger = ContinuousLogger(
        table="dateplots_pvd309",
        username=credentials.user,
        password=credentials.passwd,
        measurement_codenames=codenames,
    )
    db_logger.start()

    while qcm1.isAlive() and qcm2.isAlive():
        time.sleep(0.25)
        for name in codenames:
            value = loggers[name].read_value()
            livesocket.set_point_now(name, value)
            socket.set_point_now(name, value)
            if loggers[name].read_trigged():
                print(name + ": " + str(value))
                db_logger.enqueue_point_now(name, value)
                loggers[name].clear_trigged()
Example #2
0
def main():
    """The main method for the pressure logger"""

    # Open communication to the pressure measurement unit
    tpg = TPG262(port='/dev/ttyUSB0', baudrate=9600)
    LOGGER.info('Initiated driver to TPG 262')

    # Get a continuous logger
    codenames = ['thetaprobe_pressure_loadlock', 'thetaprobe_pressure_uvgun']
    db_logger = ContinuousLogger(table='dateplots_thetaprobe',
                                 username=credentials.USERNAME,
                                 password=credentials.PASSWORD,
                                 measurement_codenames=codenames)
    db_logger.start()
    LOGGER.info('Initiated and started database logger')

    livesocket = LiveSocket(codenames, 0.2)
    livesocket.start()

    loadlock_last = {'value': 1E20, 'time': 0}
    uvgun_last = {'value': 1E20, 'time': 0}

    try:
        while True:
            # get the values: returns:
            # (value1, (status_code1, status_message1),
            # value2, (status_code2, status_message2))
            value_ll, code_ll, value_uv, code_uv = tpg.pressure_gauges()
            livesocket.set_point_now('thetaprobe_pressure_loadlock', value_ll)
            livesocket.set_point_now('thetaprobe_pressure_uvgun', value_uv)

            ### Load lock
            if code_ll[0] in [0, 1]:  # If measurement is OK or underranged
                if logging_criteria(value_ll, loadlock_last):
                    LOGGER.info('Add value {} for load lock'.format(value_ll))
                    now_ll = db_logger.enqueue_point_now(
                        'thetaprobe_pressure_loadlock',
                        value_ll)
                    loadlock_last['value'] = value_ll
                    loadlock_last['time'] = now_ll

            ### UV gun
            if code_uv[0] in [0, 1]:  # If measurement is OK or underranged
                if logging_criteria(value_uv, uvgun_last):
                    LOGGER.info('Add value {} for UV gun'.format(value_uv))
                    now_uv = db_logger.enqueue_point_now(
                        'thetaprobe_pressure_uvgun',
                        value_uv)
                    uvgun_last['value'] = value_uv
                    uvgun_last['time'] = now_uv
    except KeyboardInterrupt:
        LOGGER.info('Keyboard interrupt. Shutting down')
        db_logger.stop()
        livesocket.stop()
        LOGGER.info('Database logger stoppped. Exiting!')
Example #3
0
def main():
    """The main method for the pressure logger"""

    # Open communication to the pressure measurement unit
    tpg = TPG262(port='/dev/ttyUSB0', baudrate=9600)
    LOGGER.info('Initiated driver to TPG 262')

    # Get a continuous logger
    codenames = ['thetaprobe_pressure_loadlock']
    db_logger = ContinuousLogger(table='dateplots_thetaprobe',
                                 username=credentials.USERNAME,
                                 password=credentials.PASSWORD,
                                 measurement_codenames=codenames)
    db_logger.start()
    LOGGER.info('Initiated and started database logger')

    name = 'Thetaprobe pressure load lock and UV gun'
    livesocket = LiveSocket(name, codenames, 0.2)
    livesocket.start()

    loadlock_last = {'value': 1E20, 'time': 0}

    try:
        while True:
            # get the values: returns:
            # (value1, (status_code1, status_message1),
            # value2, (status_code2, status_message2))
            try:
                value_ll, code_ll = tpg.pressure_gauge(gauge=1)
            except (IOError, ValueError):
                LOGGER.info(
                    'Serial communication failed. Sleep 10 and try again.')
                time.sleep(10)
                continue
            livesocket.set_point_now('thetaprobe_pressure_loadlock', value_ll)

            ### Load lock
            if code_ll[0] in [0, 1]:  # If measurement is OK or underranged
                if logging_criteria(value_ll, loadlock_last):
                    LOGGER.info('Add value {} for load lock'.format(value_ll))
                    now_ll = db_logger.enqueue_point_now(
                        'thetaprobe_pressure_loadlock', value_ll)
                    loadlock_last['value'] = value_ll
                    loadlock_last['time'] = now_ll

    except KeyboardInterrupt:
        LOGGER.info('Keyboard interrupt. Shutting down')
        db_logger.stop()
        livesocket.stop()
        LOGGER.info('Database logger stoppped. Exiting!')
Example #4
0
def main():
    """Main function"""
    chiller_port = '/dev/serial/by-id/'
    chiller_port += 'usb-Prolific_Technology_Inc._USB-Serial_Controller-if00-port0'

    LOG.info('Using chiller port %s', chiller_port)
    reader = ChillerReader(chiller_port)
    reader.start()
    LOG.info('ChillerReader started')

    codenames = [
        'sputterchamber_chiller_temperature', 'sputterchamber_chiller_flow',
        'sputterchamber_chiller_temperature_ambient',
        'sputterchamber_chiller_pressure',
        'sputterchamber_chiller_temperature_setpoint'
    ]
    LOG.debug('Using codenames %s', codenames)
    loggers = {}
    for i in range(0, len(codenames)):
        loggers[codenames[i]] = ValueLogger(reader, comp_val=0.1, channel=i)
        loggers[codenames[i]].start()

    live_socket_name = 'Sputterchamber chiller'
    live_socket = LiveSocket(live_socket_name, codenames, 2)
    live_socket.start()
    LOG.info('Live socket init and started with name "%s"', live_socket_name)

    db_table = 'dateplots_sputterchamber'
    db_logger = ContinuousLogger(table=db_table,
                                 username=credentials.user,
                                 password=credentials.passwd,
                                 measurement_codenames=codenames)
    db_logger.start()
    LOG.info('ContinuousLogger init and started on table "%s"', db_table)

    time.sleep(5)

    while reader.isAlive():
        time.sleep(0.25)
        for name in codenames:
            value = loggers[name].read_value()
            if not math.isnan(value):
                live_socket.set_point_now(name, value)
                if loggers[name].read_trigged():
                    LOG.debug('Log value %s for codename "%s"', value, name)
                    db_logger.enqueue_point_now(name, value)
                    loggers[name].clear_trigged()
Example #5
0
def main():
    """Main function"""
    chiller_port = '/dev/serial/by-id/'
    chiller_port += 'usb-Prolific_Technology_Inc._USB-Serial_Controller-if00-port0'

    LOG.info('Using chiller port %s', chiller_port)
    reader = ChillerReader(chiller_port)
    reader.start()
    LOG.info('ChillerReader started')

    codenames = ['sputterchamber_chiller_temperature',
                 'sputterchamber_chiller_flow',
                 'sputterchamber_chiller_temperature_ambient',
                 'sputterchamber_chiller_pressure',
                 'sputterchamber_chiller_temperature_setpoint']
    LOG.debug('Using codenames %s', codenames)
    loggers = {}
    for i in range(0, len(codenames)):
        loggers[codenames[i]] = ValueLogger(reader, comp_val=0.1, channel=i)
        loggers[codenames[i]].start()

    live_socket_name = 'Sputterchamber chiller'
    live_socket = LiveSocket(live_socket_name, codenames, 2)
    live_socket.start()
    LOG.info('Live socket init and started with name "%s"', live_socket_name)

    db_table = 'dateplots_sputterchamber'
    db_logger = ContinuousLogger(table=db_table,
                                 username=credentials.user,
                                 password=credentials.passwd,
                                 measurement_codenames=codenames)
    db_logger.start()
    LOG.info('ContinuousLogger init and started on table "%s"', db_table)

    time.sleep(5)

    while reader.isAlive():
        time.sleep(0.25)
        for name in codenames:
            value = loggers[name].read_value()
            if not math.isnan(value):
                live_socket.set_point_now(name, value)
                if loggers[name].read_trigged():
                    LOG.debug('Log value %s for codename "%s"', value, name)
                    db_logger.enqueue_point_now(name, value)
                    loggers[name].clear_trigged()
Example #6
0
def main():
    LOGGER.info('main started')
    cni = CNi3244_C24(5)
    socket = DateDataPullSocket(FULL_NAME, [SHORT_NAME], timeouts=1.0)
    socket.start()
    db_logger = ContinuousLogger(table='dateplots_tower',
                                 username='******',
                                 password='******',
                                 measurement_codenames=[NAME],
                                 dsn='servcinf')
    db_logger.start()
    time.sleep(0.1)

    # Main part
    try:
        main_measure_loop(cni, socket, db_logger)
    except KeyboardInterrupt:
        LOGGER.info('Keyboard Interrupt. Shutting down!')
        db_logger.stop()
        cni.close()
        socket.stop()
Example #7
0
def main():
    LOGGER.info('main started')
    cni = CNi3244_C24(0)
    socket = DateDataSocket([SHORT_NAME], timeouts=1.0)
    socket.start()
    db_logger = ContinuousLogger(
        table='dateplots_tower', username='******', password='******',
        measurement_codenames=[NAME],
        dsn='servcinf'
    )
    db_logger.start()
    time.sleep(0.1)

    # Main part
    try:
        main_measure_loop(cni, socket, db_logger)
    except KeyboardInterrupt:
        LOGGER.info('Keyboard Interrupt. Shutting down!')
        db_logger.stop()
        cni.close()
        socket.stop()
Example #8
0
class MainDatalogger(threading.Thread):
    """ Temperature reader """
    def __init__(self,):
        logging.info('MainDatalogger class started')
        threading.Thread.__init__(self)
        #from datalogger import TemperatureReader
        self.quit = False
        self.codenames = ['tabs_guard_temperature_inlet',
                     'tabs_floor_temperature_inlet',
                     'tabs_ceiling_temperature_inlet',
                     'tabs_cooling_temperature_inlet',
                     ]
        self.MC302 = WaterTemperatureReader()
        self.MC302.start()
        self.codenames = [
                     'tabs_cooling_temperature_inlet',
                     ]
        self.omega_temperature = TemperatureReader(['tabs_cooling_temperature_inlet',])
        self.omega_temperature.daemon = True
        self.omega_temperature.start()
        #omega_temperature.update_values()
        
        time.sleep(1.5)
        
        chlist = {'tabs_guard_temperature_control': 0,
                  'tabs_room_temperature_control': 1,
                  #'tabs_ceiling_temperature_inlet': 2,
                  'tabs_cooling_temperature_inlet': 3}
        self.loggers = {}
        for key in chlist.keys():
            self.loggers[key] = ValueLogger(self.omega_temperature, comp_val = 0.2, maximumtime=300,
                                            comp_type = 'lin', channel = chlist[key])
            self.loggers[key].start()
        chlist = {'tabs_guard_temperature_inlet': 0,
                   'tabs_guard_temperature_outlet': 1,
                   'tabs_guard_temperature_delta': 2,
                   'tabs_floor_temperature_inlet': 3,
                   'tabs_floor_temperature_outlet': 4,
                   'tabs_floor_temperature_delta': 5,                   
                   'tabs_ceiling_temperature_inlet': 6,
                   'tabs_ceiling_temperature_outlet': 7,
                   'tabs_ceiling_temperature_delta': 8,
                   'tabs_guard_water_flow': 9,
                   'tabs_floor_water_flow': 10,
                   'tabs_ceiling_water_flow': 11,}
        for key in chlist.keys():
            self.loggers[ key] = ValueLogger(self.MC302, comp_val = 0.2, maximumtime=300,
                                            comp_type = 'lin', channel = chlist[key])
            self.loggers[key].start()
        self.codenames = self.loggers.keys()
        #livesocket = LiveSocket('tabs_temperature_logger', codenames, 2)
        #livesocket.start()
        sockname = 'tabs_temperatures'
        self.PullSocket = DateDataPullSocket(sockname, self.codenames, timeouts=[60.0]*len(self.codenames), port = socketinfo.INFO[sockname]['port'])
        self.PullSocket.start()
        
        self.db_logger = ContinuousLogger(table='dateplots_tabs', username=credentials.user, password=credentials.passwd, measurement_codenames=self.codenames)
        self.db_logger.start()
    
    def run(self,):
        i = 0
        while not self.quit and self.omega_temperature.isAlive():
            try:
                #print(i)
                time.sleep(1)
                for name in self.loggers.keys():
                    v = self.loggers[name].read_value()
                    #livesocket.set_point_now(name, v)
                    if v != None and v != 0:
                        self.PullSocket.set_point_now(name, v)
                        if self.loggers[name].read_trigged():
                            if __name__ == '__main__':
                                print('Log: ', i, name, v)
                            self.db_logger.enqueue_point_now(name, v)
                            self.loggers[name].clear_trigged()
                        else:
                            if __name__ == '__main__':
                                print('STA: ', i, name, v)
            except (KeyboardInterrupt, SystemExit):
                pass
                #self.omega_temperature.close()
                #report error and proceed
            i += 1
        self.stop()
        
    def stop(self):
        self.quit = True
        self.omega_temperature.stop()
        self.MC302.stop()
        self.db_logger.stop()
        self.PullSocket.stop()
        for key in self.codenames:
            self.loggers[key].status['quit'] = True
Example #9
0
fc = FlowControl(MFCs, Datasocket, Pushsocket, Livesocket)
fc.start()

Logger = ValueLogger(fc, comp_val=1, comp_type='log', low_comp=0.0001, channel=1)
Logger.start()

Sniffer_Logger = ValueLogger(fc, comp_val=1, comp_type='log', low_comp=0.0001, channel=2)
Sniffer_Logger.start()


db_logger = ContinuousLogger(table='dateplots_microreactor',
                             username=credentials.user,
                             password=credentials.passwd,
                             measurement_codenames=['mr_reactor_pressure'])
db_logger.start()

db_logger_sniffer = ContinuousLogger(table='dateplots_sniffer',
                                     username=credentials_sniffer.user,
                                     password=credentials_sniffer.passwd,
                                     measurement_codenames=['sniffer_chip_pressure'])
db_logger_sniffer.start()
time.sleep(5)
while True:
    time.sleep(0.25)
    v = Logger.read_value()
    if Logger.read_trigged():
        print v
        db_logger.enqueue_point_now('mr_reactor_pressure', v)
        Logger.clear_trigged()
Example #10
0
                     low_comp=0.0001,
                     channel=1)
Logger.start()

Sniffer_Logger = ValueLogger(fc,
                             comp_val=1,
                             comp_type='log',
                             low_comp=0.0001,
                             channel=2)
Sniffer_Logger.start()

db_logger = ContinuousLogger(table='dateplots_microreactor',
                             username=credentials.user,
                             password=credentials.passwd,
                             measurement_codenames=['mr_reactor_pressure'])
db_logger.start()

db_logger_sniffer = ContinuousLogger(
    table='dateplots_sniffer',
    username=credentials_sniffer.user,
    password=credentials_sniffer.passwd,
    measurement_codenames=['sniffer_chip_pressure'])
db_logger_sniffer.start()
time.sleep(5)
while True:
    time.sleep(0.25)
    v = Logger.read_value()
    if Logger.read_trigged():
        print v
        db_logger.enqueue_point_now('mr_reactor_pressure', v)
        Logger.clear_trigged()
Example #11
0
class MainPID(threading.Thread):
    """ pid controller """
    def __init__(self, ):
        logging.info('MainPID class started')
        threading.Thread.__init__(self)
        #from datalogger import TemperatureReader
        self.quit = False
        self.codenames = [
            'tabs_guard_pid_value',
            'tabs_floor_pid_value',
            'tabs_ceiling_pid_value',
            'tabs_cooling_pid_value',
            'tabs_guard_valve_heating',
            'tabs_floor_valve_heating',
            'tabs_ceiling_valve_heating',
            'tabs_guard_valve_cooling',
            'tabs_floor_valve_cooling',
            'tabs_ceiling_valve_cooling',
            'tabs_cooling_valve_cooling',
        ]
        sockname = 'tabs_pids'
        self.PullSocket = DateDataPullSocket(
            sockname,
            self.codenames,
            timeouts=[60.0] * len(self.codenames),
            port=socketinfo.INFO[sockname]['port'])
        self.PullSocket.start()

        self.PTC = PidTemperatureControl(self.codenames)
        self.PTC.daemon = True
        self.PTC.start()
        #time.sleep(5)

        chlist = {
            'tabs_guard_pid_value': 0,
            'tabs_floor_pid_value': 1,
            'tabs_ceiling_pid_value': 2,
            'tabs_cooling_pid_value': 3,
            'tabs_guard_valve_heating': 4,
            'tabs_floor_valve_heating': 5,
            'tabs_ceiling_valve_heating': 6,
            'tabs_guard_valve_cooling': 7,
            'tabs_floor_valve_cooling': 8,
            'tabs_ceiling_valve_cooling': 9,
            'tabs_cooling_valve_cooling': 10
        }
        self.loggers = {}
        for key in self.codenames:
            self.loggers[key] = ValueLogger(self.PTC,
                                            comp_val=0.10,
                                            maximumtime=60,
                                            comp_type='lin',
                                            channel=chlist[key])
            self.loggers[key].start()
        #livesocket = LiveSocket('tabs_temperature_logger', codenames, 2)
        #livesocket.start()

        self.db_logger = ContinuousLogger(table='dateplots_tabs',
                                          username=credentials.user,
                                          password=credentials.passwd,
                                          measurement_codenames=self.codenames)
        self.db_logger.start()

    def run(self, ):
        i = 0
        while not self.quit and self.PTC.isAlive():
            try:
                #print(i)
                time.sleep(1)
                for name in self.codenames:
                    v = self.loggers[name].read_value()
                    #print('Status: ', name , v)
                    #livesocket.set_point_now(name, v)
                    self.PullSocket.set_point_now(name, v)
                    if self.loggers[name].read_trigged():
                        if __name__ == '__main__':
                            print('Log: ', i, name, v)
                        #print(i, name, v)
                        self.db_logger.enqueue_point_now(name, v)
                        self.loggers[name].clear_trigged()
            except (KeyboardInterrupt, SystemExit):
                self.quit = True
                pass
                #self.PTC.stop()
                #report error and proceed
            i += 1
        self.stop()

    def stop(self):
        self.quit = True
        self.PTC.stop()
        self.PullSocket.stop()
        self.db_logger.stop()
        for key in self.codenames:
            self.loggers[key].status['quit'] = True
Example #12
0
class MainTui(threading.Thread):
    """ Temperature reader """
    def __init__(self,):
        threading.Thread.__init__(self)
        #from mytui import CursesTui
        self.quit = False
        self.codenames = ['tabs_guard_temperature_setpoint',
                     'tabs_floor_temperature_setpoint',
                     'tabs_ceiling_temperature_setpoint',
                     'tabs_cooling_temperature_setpoint',
                     ]
        sockname = 'tabs_setpoints'
        self.PullSocket = DateDataPullSocket(sockname, self.codenames, timeouts=[60.0]*len(self.codenames), port = socketinfo.INFO[sockname]['port'])
        self.PullSocket.start()
        
        self.TUI = CursesTui(self.codenames)
        self.TUI.start()
        #time.sleep(5)
        
        chlist = {'tabs_guard_temperature_setpoint': 0,
                  'tabs_floor_temperature_setpoint': 1,
                  'tabs_ceiling_temperature_setpoint': 2,
                  'tabs_cooling_temperature_setpoint': 3}
        self.loggers = {}
        for key in self.codenames:
            self.loggers[key] = ValueLogger(self.TUI, comp_val = 0.2, maximumtime=60,
                                            comp_type = 'lin', channel = chlist[key])
            self.loggers[key].start()
        #livesocket = LiveSocket('tabs_temperature_logger', codenames, 2)
        #livesocket.start()
        
        
        
        self.db_logger = ContinuousLogger(table='dateplots_tabs', username=credentials.user, password=credentials.passwd, measurement_codenames=self.codenames)
        #print('Hostname of db logger: ' + db_logger.host)
        self.db_logger.start()
    
    def run(self):
        i = 0
        while not self.quit:
            #print(i)
            if self.TUI.isAlive():
                pass
            else:
                print('TUI has shutdown')
                self.quit = True
            try:
                #print(i)
                time.sleep(2)
                for name in self.codenames:
                    v = self.loggers[name].read_value()
                    #print('Status: ', name , v)
                    #livesocket.set_point_now(name, v)
                    self.PullSocket.set_point_now(name, v)
                    if self.loggers[name].read_trigged():
                        #if __name__ == '__main__':
                        #    print('Log: ', i, name, v)
                        #print('Log: ', name, v)
                        self.db_logger.enqueue_point_now(name, v)
                        self.loggers[name].clear_trigged()
            except:
                print('run error')
                pass
                #self.TUI.stop()
                #report error and proceed
            i += 1
        self.stop()
        
    def stop(self):
        self.quit = True
        self.TUI.stop()
        self.PullSocket.stop()
        self.db_logger.stop()
        for key in self.codenames:
            self.loggers[key].status['quit'] = True
Example #13
0
class GasAlarmMonitor(object):
    """Class that monitors the gas alarm the building 307"""
    def __init__(self):
        # Start logger
        codenames = [
            'B307_gasalarm_CO_051', 'B307_gasalarm_H2_051',
            'B307_gasalarm_CO_055', 'B307_gasalarm_H2_055',
            'B307_gasalarm_CO_059', 'B307_gasalarm_H2_059',
            'B307_gasalarm_CO_061', 'B307_gasalarm_H2_061',
            'B307_gasalarm_CO_42-43', 'B307_gasalarm_H2_2sal',
            'B307_gasalarm_CO_932', 'B307_gasalarm_H2_932'
        ]
        self.db_logger = ContinuousLogger(table='dateplots_b307gasalarm',
                                          username=credentials.USERNAME,
                                          password=credentials.PASSWORD,
                                          measurement_codenames=codenames)
        self.db_logger.start()
        LOGGER.info('Logger started')

        # Each value is measured about every 5 sec, so sane interval about 2
        self.live_socket = LiveSocket(name='gas_alarm_307_live',
                                      codenames=codenames)
        self.live_socket.start()
        LOGGER.info('Live socket started')

        # Start driver
        self.vortex = Vortex('/dev/ttyUSB0', 1)
        LOGGER.info('Vortex driver opened')

        # Init database connection
        self.db_connection = MySQLdb.connect(host='servcinf-sql.fysik.dtu.dk',
                                             user=credentials.USERNAME,
                                             passwd=credentials.PASSWORD,
                                             db='cinfdata')
        self.db_cursor = self.db_connection.cursor()

        # Initiate static information. All information about the except for
        # the list of their numbers are placed in dicts because the numbering
        # starts at 1.
        # Detector numbers: [1, 2, 3, ..., 12]
        self.detector_numbers = \
            range(1, self.vortex.get_number_installed_detectors() + 1)
        self.detector_info = \
            {detector_num: self.vortex.detector_configuration(detector_num)
             for detector_num in self.detector_numbers}
        # trip_levels are the differences that are required to force a log
        # The levels are set to 2 * the communication resolution
        # (1000 values over the full range)
        # NOTE. Since we have had a lot of noise on the CO channels, we
        # increased the level to info.range * 7.0 / 1000.0 for those
        #self.trip_levels = {detector_num: info.range * 2.0 / 1000.0 for
        #                    detector_num, info in self.detector_info.items()}
        self.trip_levels = {}
        for detector_number, info in self.detector_info.items():
            if info.unit == "PPM":
                self.trip_levels[detector_number] = info.range * 7.0 / 1000.0
            else:
                self.trip_levels[detector_number] = info.range * 2.0 / 1000.0

        # Initiate last measured values and their corresponding times
        self.detector_levels_last_values = \
            {detector_num: - (10 ** 9)
             for detector_num in self.detector_numbers}
        self.detector_levels_last_times = \
            {detector_num: 0 for detector_num in self.detector_numbers}
        self.detector_status_last_values = \
            {detector_num: {'inhibit': False, 'status': ['OK'],
                            'codename': self.detector_info[detector_num].identity}
             for detector_num in self.detector_numbers}
        self.detector_status_last_times = \
            {detector_num: 0 for detector_num in self.detector_numbers}

        # Initiate variables for system power status
        self.central_power_status_last_value = 'OK'
        self.central_power_status_last_time = -(10**9)

        # Initiate variables for system status
        self.central_status_last_value = ['All OK']
        self.central_status_last_time = 0

    def close(self):
        """Close the logger and the connection to the Vortex"""
        self.db_logger.stop()
        LOGGER.info('Logger stopped')
        self.live_socket.stop()
        LOGGER.info('Live socket stopped')
        self.vortex.close()
        LOGGER.info('Vortex driver closed')

    @staticmethod
    def identity_to_codename(identity):
        """Convert the identity the sensor returns to the codename used in the
        database
        """
        # NOTE The identities was changed at some point, which is the reason where there
        # is this manual mingling with name. The current names are:
        # 'CO 51', 'H2 51', 'CO 55', 'H2 55', 'CO 59', 'H2 61', 'CO 61', 'H2 61',
        # 'CO 42/43', 'H2 2 sal', 'CO 932', 'H2 932'
        # and they need to be changed to the codenames in codenames (in __init__)

        #first, second = identity.split(' ', 1)
        #if len(second) == 2:
        #    second = '0' + second
        #identity = first + ' ' + second

        #identity = identity.replace('2 sal', '2sal').replace(' ', '_').replace('/', '-')
        identity = identity.replace(' ', '_').replace('/', '-')
        return 'B307_gasalarm_{}'.format(identity)

    def main(self):
        """Main monitoring and logging loop"""
        # Each iteration takes about 5 sec
        while True:
            # Log detectors
            for detector_num in self.detector_numbers:
                self.log_detector(detector_num)

            # Log Vortex unit status (force log every 24 hours)
            self.log_central_unit()

    def log_detector(self, detector_num):
        """Get the levels from one detector and log if required"""
        # Get detector info and levels for this detector
        conf = self.detector_info[detector_num]
        codename = self.identity_to_codename(conf.identity)

        ##### HACK HACK HACK FIXME There is a duplicate name error in the configuration
        # which for now we fix here in code
        #if codename == "B307_gasalarm_H2_061" and detector_num == 6:
        #    codename = "B307_gasalarm_H2_059"
        ##### HACK HACK HACK FIXME

        LOGGER.debug('Use detector {} \'{}\''.format(detector_num, codename))
        levels = self.vortex.get_detector_levels(detector_num)
        LOGGER.debug('Levels read: {}'.format(levels))

        # Detector level
        now = time.time()
        # Always send to live socket
        self.live_socket.set_point_now(codename, levels.level)
        # Force log every 10 m
        time_condition = \
            now - self.detector_levels_last_times[detector_num] > 600
        value_condition = \
            abs(self.detector_levels_last_values[detector_num] - levels.level)\
            >= self.trip_levels[detector_num]
        if time_condition or value_condition:
            LOGGER.debug('Send level to db trigged in time: {} or value: '
                         '{}'.format(time_condition, value_condition))
            self.db_logger.enqueue_point(codename, (now, levels.level))
            # Update last values
            self.detector_levels_last_values[detector_num] = levels.level
            self.detector_levels_last_times[detector_num] = now
        else:
            LOGGER.debug('Level logging condition false')

        self.log_detector_status(detector_num, levels, conf)

    def log_detector_status(self, detector_num, levels, conf):
        """Sub function to log single detector status"""
        now = time.time()
        # Force log every 24 hours
        time_condition = \
            now - self.detector_status_last_times[detector_num] > 86400
        status = {
            'inhibit': levels.inhibit,
            'status': levels.status,
            'codename': conf.identity
        }

        ##### HACK HACK HACK FIXME There is a duplicate name error in the configuration
        if detector_num == 6 and status['codename'] == 'H2 61':
            status['codename'] = 'H2 59'
        ##### HACK HACK HACK FIXME

        value_condition = \
            (status != self.detector_status_last_values[detector_num])

        # Check if we should log
        if time_condition or value_condition:
            check_in = time_condition and not value_condition
            LOGGER.info('Send detector status to db trigged on time: {} or '
                        'value: {}'.format(time_condition, value_condition))
            query = 'INSERT INTO status_b307gasalarm '\
                '(time, device, status, check_in) '\
                'VALUES (FROM_UNIXTIME(%s), %s, %s, %s);'
            values = (now, detector_num, json.dumps(status), check_in)
            self._wake_mysql()
            self.db_cursor.execute(query, values)
            # Update last values
            self.detector_status_last_times[detector_num] = now
            self.detector_status_last_values[detector_num] = status
        else:
            LOGGER.debug('Detector status logging condition false')

    def log_central_unit(self):
        """Log the status of the central unit"""
        power_status = self.vortex.get_system_power_status().value
        now = time.time()
        # Force a log once per 24 hours
        time_condition = now - self.central_power_status_last_time > 86400
        value_condition = self.central_power_status_last_value != power_status
        LOGGER.debug('Read central power status: \'{}\''.format(power_status))
        if time_condition or value_condition:
            check_in = time_condition and not value_condition
            LOGGER.info('Send power status to db trigged in time: {} or '
                        'value: {}'.format(time_condition, value_condition))
            query = 'INSERT INTO status_b307gasalarm '\
                '(time, device, status, check_in) '\
                'VALUES (FROM_UNIXTIME(%s), %s, %s, %s);'
            values = (now, 255, json.dumps(power_status), check_in)
            self._wake_mysql()
            self.db_cursor.execute(query, values)
            # Update last values
            self.central_power_status_last_time = now
            self.central_power_status_last_value = power_status
        else:
            LOGGER.debug('Power status logging condition false')

        self.log_central_unit_generel()

    def log_central_unit_generel(self):
        """Log the generel status from the central"""
        generel_status = self.vortex.get_system_status()
        now = time.time()
        # Force a log once per 24 hours
        time_condition = now - self.central_status_last_time > 86400
        value_condition = generel_status != self.central_status_last_value
        LOGGER.debug(
            'Read central generel status: \'{}\''.format(generel_status))
        if time_condition or value_condition:
            check_in = time_condition and not value_condition
            LOGGER.info('Send central generel status to db trigged in time: {}'
                        ' or value: {}'.format(time_condition,
                                               value_condition))
            query = 'INSERT INTO status_b307gasalarm '\
                '(time, device, status, check_in) '\
                'VALUES (FROM_UNIXTIME(%s), %s, %s, %s);'
            values = (now, 254, json.dumps(generel_status), check_in)
            self._wake_mysql()
            self.db_cursor.execute(query, values)
            # Update last values
            self.central_status_last_time = now
            self.central_status_last_value = generel_status
        else:
            LOGGER.debug('Central generel status logging confition false')

    def _wake_mysql(self):
        """Send a ping via the connection and re-initialize the cursor"""
        self.db_connection.ping(True)
        self.db_cursor = self.db_connection.cursor()
def main():
    """ Main loop """
    il800 = intellemetrics_il800.IL800('/dev/serial/by-id/' +
                                       'usb-Prolific_Technology_Inc.' +
                                       '_USB-Serial_Controller_D-if00-port0')
    sqm160 = inficon_sqm160.InficonSQM160(
        '/dev/serial/by-id/usb-1a86_USB2.0-Ser_-if00-port0')

    qcm1 = QcmReader(il800)
    qcm1.start()

    qcm2 = QcmReader(sqm160)
    qcm2.start()

    time.sleep(2.5)

    codenames = [
        'pvd309_qcm1_rate', 'pvd309_qcm1_thickness', 'pvd309_qcm1_frequency',
        'pvd309_qcm2_rate', 'pvd309_qcm2_thickness', 'pvd309_qcm2_frequency'
    ]

    loggers = {}
    loggers[codenames[0]] = ValueLogger(qcm1,
                                        comp_val=0.01,
                                        comp_type='lin',
                                        channel=0)
    loggers[codenames[1]] = ValueLogger(qcm1,
                                        comp_val=0.1,
                                        comp_type='lin',
                                        channel=1)
    loggers[codenames[2]] = ValueLogger(qcm1,
                                        comp_val=1,
                                        comp_type='lin',
                                        channel=2)
    loggers[codenames[3]] = ValueLogger(qcm2,
                                        comp_val=0.3,
                                        comp_type='lin',
                                        channel=0)
    loggers[codenames[4]] = ValueLogger(qcm2,
                                        comp_val=0.1,
                                        comp_type='lin',
                                        channel=1)
    loggers[codenames[5]] = ValueLogger(qcm2,
                                        comp_val=1,
                                        comp_type='lin',
                                        channel=2)
    for name in codenames:
        loggers[name].daemon = True
        loggers[name].start()

    livesocket = LiveSocket('pvd309 qcm logger', codenames)
    livesocket.start()

    socket = DateDataPullSocket('pvd309 qcm',
                                codenames,
                                timeouts=[1.0] * len(codenames))
    socket.start()

    db_logger = ContinuousLogger(table='dateplots_pvd309',
                                 username=credentials.user,
                                 password=credentials.passwd,
                                 measurement_codenames=codenames)
    db_logger.start()

    while qcm1.isAlive() and qcm2.isAlive():
        time.sleep(0.25)
        for name in codenames:
            value = loggers[name].read_value()
            livesocket.set_point_now(name, value)
            socket.set_point_now(name, value)
            if loggers[name].read_trigged():
                print(name + ': ' + str(value))
                db_logger.enqueue_point_now(name, value)
                loggers[name].clear_trigged()
Example #15
0
class MainDatalogger(threading.Thread):
    """ Temperature reader """

    def __init__(self,):
        logging.info("MainDatalogger class started")
        threading.Thread.__init__(self)
        # from datalogger import TemperatureReader
        self.quit = False
        self.codenames = [
            "tabs_guard_temperature_inlet",
            "tabs_floor_temperature_inlet",
            "tabs_ceiling_temperature_inlet",
            "tabs_cooling_temperature_inlet",
        ]
        self.MC302 = WaterTemperatureReader()
        self.MC302.start()
        self.codenames = ["tabs_cooling_temperature_inlet"]
        self.omega_temperature = TemperatureReader(["tabs_cooling_temperature_inlet"])
        self.omega_temperature.daemon = True
        self.omega_temperature.start()
        # omega_temperature.update_values()

        time.sleep(1.5)

        chlist = {
            "tabs_guard_temperature_control": 0,
            "tabs_room_temperature_control": 1,
            #'tabs_ceiling_temperature_inlet': 2,
            "tabs_cooling_temperature_inlet": 3,
        }
        self.loggers = {}
        for key in chlist.keys():
            self.loggers[key] = ValueLogger(
                self.omega_temperature, comp_val=0.2, maximumtime=300, comp_type="lin", channel=chlist[key]
            )
            self.loggers[key].start()
        chlist = {
            "tabs_guard_temperature_inlet": 0,
            "tabs_guard_temperature_outlet": 1,
            "tabs_guard_temperature_delta": 2,
            "tabs_floor_temperature_inlet": 3,
            "tabs_floor_temperature_outlet": 4,
            "tabs_floor_temperature_delta": 5,
            "tabs_ceiling_temperature_inlet": 6,
            "tabs_ceiling_temperature_outlet": 7,
            "tabs_ceiling_temperature_delta": 8,
            "tabs_guard_water_flow": 9,
            "tabs_floor_water_flow": 10,
            "tabs_ceiling_water_flow": 11,
        }
        for key in chlist.keys():
            self.loggers[key] = ValueLogger(
                self.MC302, comp_val=0.2, maximumtime=300, comp_type="lin", channel=chlist[key]
            )
            self.loggers[key].start()
        self.codenames = self.loggers.keys()
        # livesocket = LiveSocket('tabs_temperature_logger', codenames, 2)
        # livesocket.start()
        sockname = "tabs_temperatures"
        self.PullSocket = DateDataPullSocket(
            sockname, self.codenames, timeouts=[60.0] * len(self.codenames), port=socketinfo.INFO[sockname]["port"]
        )
        self.PullSocket.start()

        self.db_logger = ContinuousLogger(
            table="dateplots_tabs",
            username=credentials.user,
            password=credentials.passwd,
            measurement_codenames=self.codenames,
        )
        self.db_logger.start()

    def run(self,):
        i = 0
        while not self.quit and self.omega_temperature.isAlive():
            try:
                # print(i)
                time.sleep(1)
                for name in self.loggers.keys():
                    v = self.loggers[name].read_value()
                    # livesocket.set_point_now(name, v)
                    if v != None and v != 0:
                        self.PullSocket.set_point_now(name, v)
                        if self.loggers[name].read_trigged():
                            if __name__ == "__main__":
                                print("Log: ", i, name, v)
                            self.db_logger.enqueue_point_now(name, v)
                            self.loggers[name].clear_trigged()
                        else:
                            if __name__ == "__main__":
                                print("STA: ", i, name, v)
            except (KeyboardInterrupt, SystemExit):
                pass
                # self.omega_temperature.close()
                # report error and proceed
            i += 1
        self.stop()

    def stop(self):
        self.quit = True
        self.omega_temperature.stop()
        self.MC302.stop()
        self.db_logger.stop()
        self.PullSocket.stop()
        for key in self.codenames:
            self.loggers[key].status["quit"] = True
Example #16
0
    if pc_measurement.trigged:
        print(pc)
        #db_logger.enqueue_point_now('stm312_pc', pc)
        pc_measurement.trigged = False
    time.sleep(0.5)
"""

#Pullsocket = DateDataPullSocket('stm312 hpc pressure control', ['pressure', 'setpoint'])
#Pushsocket = DataPushSocket('stm312 hpc pressure control', action='store_last')

if __name__ == '__main__':
    print('program start')
    #Pullsocket.start()
    #Pushsocket.start()
    #socket.start()
    db_logger_stm312.start()
    #db_logger_ocs.start()
    time.sleep(1)

    pc = PcClass()
    #pc.add_socket_server(Pullsocket,Pushsocket)
    #pc.add_logger(db_logger_stm312)
    #pirani = PiraniClass()
    #pirani.add_logger(db_logger_stm312)

    baratron = Baratron()
    #baratron.deamon = True
    #baratron.start
    time.sleep(2)

    pc.start()
Example #17
0
class MainTui(threading.Thread):
    """ Temperature reader """
    def __init__(self, ):
        threading.Thread.__init__(self)
        #from mytui import CursesTui
        self.quit = False
        self.codenames = [
            'tabs_guard_temperature_setpoint',
            'tabs_floor_temperature_setpoint',
            'tabs_ceiling_temperature_setpoint',
            'tabs_cooling_temperature_setpoint',
        ]
        sockname = 'tabs_setpoints'
        self.PullSocket = DateDataPullSocket(
            sockname,
            self.codenames,
            timeouts=[60.0] * len(self.codenames),
            port=socketinfo.INFO[sockname]['port'])
        self.PullSocket.start()

        self.TUI = CursesTui(self.codenames)
        self.TUI.daemon = True
        self.TUI.start()
        #time.sleep(5)

        chlist = {
            'tabs_guard_temperature_setpoint': 0,
            'tabs_floor_temperature_setpoint': 1,
            'tabs_ceiling_temperature_setpoint': 2,
            'tabs_cooling_temperature_setpoint': 3
        }
        self.loggers = {}
        for key in self.codenames:
            self.loggers[key] = ValueLogger(self.TUI,
                                            comp_val=0.2,
                                            maximumtime=60,
                                            comp_type='lin',
                                            channel=chlist[key])
            self.loggers[key].start()
        #livesocket = LiveSocket('tabs_temperature_logger', codenames, 2)
        #livesocket.start()

        self.db_logger = ContinuousLogger(table='dateplots_tabs',
                                          username=credentials.user,
                                          password=credentials.passwd,
                                          measurement_codenames=self.codenames)
        #print('Hostname of db logger: ' + db_logger.host)
        self.db_logger.start()

    def run(self):
        i = 0
        while not self.quit:
            #print(i)
            if self.TUI.isAlive():
                pass
            else:
                print('TUI has shutdown')
                self.quit = True
            try:
                #print(i)
                time.sleep(2)
                for name in self.codenames:
                    v = self.loggers[name].read_value()
                    #print('Status: ', name , v)
                    #livesocket.set_point_now(name, v)
                    self.PullSocket.set_point_now(name, v)
                    if self.loggers[name].read_trigged():
                        #if __name__ == '__main__':
                        #    print('Log: ', i, name, v)
                        #print('Log: ', name, v)
                        self.db_logger.enqueue_point_now(name, v)
                        self.loggers[name].clear_trigged()
            except:
                print('run error')
                pass
                #self.TUI.stop()
                #report error and proceed
            i += 1
        self.stop()

    def stop(self):
        self.quit = True
        self.TUI.stop()
        self.PullSocket.stop()
        self.db_logger.stop()
        for key in self.codenames:
            self.loggers[key].status['quit'] = True
Example #18
0
class GasAlarmMonitor(object):
    """Class that monitors the gas alarm the building 307"""

    def __init__(self):
        # Start logger
        codenames = ['B307_gasalarm_CO_051', 'B307_gasalarm_H2_051',
                     'B307_gasalarm_CO_055', 'B307_gasalarm_H2_055',
                     'B307_gasalarm_CO_059', 'B307_gasalarm_H2_059',
                     'B307_gasalarm_CO_061', 'B307_gasalarm_H2_061',
                     'B307_gasalarm_CO_42-43', 'B307_gasalarm_H2_2sal',
                     'B307_gasalarm_CO_932', 'B307_gasalarm_H2_932']
        self.db_logger = ContinuousLogger(table='dateplots_b307gasalarm',
                                          username=credentials.USERNAME,
                                          password=credentials.PASSWORD,
                                          measurement_codenames=codenames)
        self.db_logger.start()
        LOGGER.info('Logger started')

        # Each value is measured about every 5 sec, so sane interval about 2
        self.live_socket = LiveSocket(name='gas_alarm_307_live',
                                      codenames=codenames,
                                      sane_interval=2.0)
        self.live_socket.start()
        LOGGER.info('Live socket started')

        # Start driver
        self.vortex = Vortex('/dev/ttyUSB0', 1)
        LOGGER.info('Vortex driver opened')

        # Init database connection
        self.db_connection = MySQLdb.connect(
            host='servcinf', user=credentials.USERNAME,
            passwd=credentials.PASSWORD, db='cinfdata')
        self.db_cursor = self.db_connection.cursor()

        # Initiate static information. All information about the except for
        # the list of their numbers are placed in dicts because the numbering
        # starts at 1.
        # Detector numbers: [1, 2, 3, ..., 12]
        self.detector_numbers = \
            range(1, self.vortex.get_number_installed_detectors() + 1)
        self.detector_info = \
            {detector_num: self.vortex.detector_configuration(detector_num)
             for detector_num in self.detector_numbers}
        # trip_levels are the differences that are required to force a log
        # The levels are set to 2 * the communication resolution
        # (1000 values / full range)
        self.trip_levels = {detector_num: info.range * 2.0 / 1000.0 for
                            detector_num, info in self.detector_info.items()}

        # Initiate last measured values and their corresponding times
        self.detector_levels_last_values = \
            {detector_num: - (10 ** 9)
             for detector_num in self.detector_numbers}
        self.detector_levels_last_times = \
            {detector_num: 0 for detector_num in self.detector_numbers}
        self.detector_status_last_values = \
            {detector_num: {'inhibit': False, 'status': ['OK'],
                            'codename': self.detector_info[detector_num].identity}
             for detector_num in self.detector_numbers}
        self.detector_status_last_times = \
            {detector_num: 0 for detector_num in self.detector_numbers}

        # Initiate variables for system power status
        self.central_power_status_last_value = 'OK'
        self.central_power_status_last_time = - (10 ** 9)

        # Initiate variables for system status
        self.central_status_last_value = ['All OK']
        self.central_status_last_time = 0

    def close(self):
        """Close the logger and the connection to the Vortex"""
        self.db_logger.stop()
        LOGGER.info('Logger stopped')
        self.live_socket.stop()
        LOGGER.info('Live socket stopped')
        self.vortex.close()
        LOGGER.info('Vortex driver closed')

    @staticmethod
    def identity_to_codename(identity):
        """Convert the identity the sensor returns to the codename used in the
        database
        """
        identity = identity.replace(' ', '_').replace('/', '-')
        return 'B307_gasalarm_{}'.format(identity)

    def main(self):
        """Main monitoring and logging loop"""
        # Each iteration takes about 5 sec
        while True:
            # Log detectors
            for detector_num in self.detector_numbers:
                self.log_detector(detector_num)

            # Log Vortex unit status (force log every 24 hours)
            self.log_central_unit()

    def log_detector(self, detector_num):
        """Get the levels from one detector and log if required"""
        # Get detector info and levels for this detector
        conf = self.detector_info[detector_num]
        codename = self.identity_to_codename(conf.identity)
        LOGGER.debug('Use detector {} \'{}\''.format(detector_num, codename))
        levels = self.vortex.get_detector_levels(detector_num)
        LOGGER.debug('Levels read: {}'.format(levels))

        # Detector level
        now = time.time()
        # Always send to live socket
        self.live_socket.set_point_now(codename, levels.level)
        # Force log every 10 m
        time_condition = \
            now - self.detector_levels_last_times[detector_num] > 600
        value_condition = \
            abs(self.detector_levels_last_values[detector_num] - levels.level)\
            >= self.trip_levels[detector_num]
        if time_condition or value_condition:
            LOGGER.debug('Send level to db trigged in time: {} or value: '
                         '{}'.format(time_condition, value_condition))
            self.db_logger.enqueue_point(codename, (now, levels.level))
            # Update last values
            self.detector_levels_last_values[detector_num] = levels.level
            self.detector_levels_last_times[detector_num] = now
        else:
            LOGGER.debug('Level logging condition false')

        self.log_detector_status(detector_num, levels, conf)

    def log_detector_status(self, detector_num, levels, conf):
        """Sub function to log single detector status"""
        now = time.time()
        # Force log every 24 hours
        time_condition = \
            now - self.detector_status_last_times[detector_num] > 86400
        status = {'inhibit': levels.inhibit, 'status': levels.status,
                  'codename': conf.identity}
        value_condition = \
            (status != self.detector_status_last_values[detector_num])

        # Check if we should log
        if time_condition or value_condition:
            check_in = time_condition and not value_condition
            LOGGER.info('Send detector status to db trigged on time: {} or '
                        'value: {}'.format(time_condition, value_condition))
            query = 'INSERT INTO status_b307gasalarm '\
                '(time, device, status, check_in) '\
                'VALUES (FROM_UNIXTIME(%s), %s, %s, %s);'
            values = (now, detector_num, json.dumps(status), check_in)
            self._wake_mysql()
            self.db_cursor.execute(query, values)
            # Update last values
            self.detector_status_last_times[detector_num] = now
            self.detector_status_last_values[detector_num] = status
        else:
            LOGGER.debug('Detector status logging condition false')

    def log_central_unit(self):
        """Log the status of the central unit"""
        power_status = self.vortex.get_system_power_status().value
        now = time.time()
        # Force a log once per 24 hours
        time_condition = now - self.central_power_status_last_time > 86400
        value_condition = self.central_power_status_last_value != power_status
        LOGGER.debug('Read central power status: \'{}\''.format(power_status))
        if time_condition or value_condition:
            check_in = time_condition and not value_condition
            LOGGER.info('Send power status to db trigged in time: {} or '
                        'value: {}'.format(time_condition, value_condition))
            query = 'INSERT INTO status_b307gasalarm '\
                '(time, device, status, check_in) '\
                'VALUES (FROM_UNIXTIME(%s), %s, %s, %s);'
            values = (now, 255, json.dumps(power_status), check_in)
            self._wake_mysql()
            self.db_cursor.execute(query, values)
            # Update last values
            self.central_power_status_last_time = now
            self.central_power_status_last_value = power_status
        else:
            LOGGER.debug('Power status logging condition false')

        self.log_central_unit_generel()

    def log_central_unit_generel(self):
        """Log the generel status from the central"""
        generel_status = self.vortex.get_system_status()
        now = time.time()
        # Force a log once per 24 hours
        time_condition = now - self.central_status_last_time > 86400
        value_condition = generel_status != self.central_status_last_value
        LOGGER.debug(
            'Read central generel status: \'{}\''.format(generel_status))
        if time_condition or value_condition:
            check_in = time_condition and not value_condition
            LOGGER.info('Send central generel status to db trigged in time: {}'
                        ' or value: {}'.format(time_condition,
                                               value_condition))
            query = 'INSERT INTO status_b307gasalarm '\
                '(time, device, status, check_in) '\
                'VALUES (FROM_UNIXTIME(%s), %s, %s, %s);'
            values = (now, 254, json.dumps(generel_status), check_in)
            self._wake_mysql()
            self.db_cursor.execute(query, values)
            # Update last values
            self.central_status_last_time = now
            self.central_status_last_value = generel_status
        else:
            LOGGER.debug('Central generel status logging confition false')

    def _wake_mysql(self):
        """Send a ping via the connection and re-initialize the cursor"""
        self.db_connection.ping(True)
        self.db_cursor = self.db_connection.cursor()
Example #19
0
class GasAlarmMonitor(object):
    """Class that monitors the gas alarm the building 312"""
    def __init__(self):
        # Start logger
        codenames = CONF_TO_NAME.values()
        self.db_logger = ContinuousLogger(table='dateplots_b312gasalarm',
                                          username=credentials.USERNAME,
                                          password=credentials.PASSWORD,
                                          measurement_codenames=codenames)
        self.db_logger.start()
        LOGGER.info('Logger started')

        # Each value is measured about every 5 sec, so sane interval about 2
        self.live_socket = LiveSocket(name='gas_alarm_312_live',
                                      codenames=codenames,
                                      sane_interval=2.0)
        self.live_socket.start()
        LOGGER.info('Live socket started')

        # Start driver
        self.vortex = Vortex('/dev/ttyUSB0', 1)
        LOGGER.info('Vortex driver opened')

        # Init database connection
        self.db_connection = MySQLdb.connect(host='servcinf-sql',
                                             user=credentials.USERNAME,
                                             passwd=credentials.PASSWORD,
                                             db='cinfdata')
        self.db_cursor = self.db_connection.cursor()

        # Initiate static information. All information about the except for
        # the list of their numbers are placed in dicts because the numbering
        # starts at 1.
        # Detector numbers: [1, 2, 3, ..., 12]
        self.detector_numbers = range(
            1,
            self.vortex.get_number_installed_detectors() + 1)
        self.detector_info = {
            detector_num: self.vortex.detector_configuration(detector_num)
            for detector_num in self.detector_numbers
        }
        pprint(self.detector_info)
        # trip_levels are the differences that are required to force a log
        # The levels are set to 2 * the communication resolution
        # (1000 values / full range)
        self.trip_levels = {
            detector_num: info.range * 2.0 / 1000.0
            for detector_num, info in self.detector_info.items()
        }

        # Initiate last measured values and their corresponding times
        self.detector_levels_last_values = \
            {detector_num: - (10 ** 9)
             for detector_num in self.detector_numbers}
        self.detector_levels_last_times = \
            {detector_num: 0 for detector_num in self.detector_numbers}
        self.detector_status_last_values = \
            {detector_num: {'inhibit': False, 'status': ['OK'],
                            'codename': self.detector_info[detector_num].identity}
             for detector_num in self.detector_numbers}
        self.detector_status_last_times = \
            {detector_num: 0 for detector_num in self.detector_numbers}

        # Initiate variables for system power status
        self.central_power_status_last_value = 'OK'
        self.central_power_status_last_time = -(10**9)

        # Initiate variables for system status
        self.central_status_last_value = ['All OK']
        self.central_status_last_time = 0

    def close(self):
        """Close the logger and the connection to the Vortex"""
        self.db_logger.stop()
        LOGGER.info('Logger stopped')
        self.live_socket.stop()
        LOGGER.info('Live socket stopped')
        self.vortex.close()
        LOGGER.info('Vortex driver closed')

    @staticmethod
    def conf_to_codename(conf):
        """Convert the identity the sensor returns to the codename used in the
        database
        """
        conf = '{conf.number} {conf.identity} {conf.unit}'.format(conf=conf)
        return CONF_TO_NAME[conf]

    def main(self):
        """Main monitoring and logging loop"""
        # Each iteration takes about 5 sec
        while True:
            # Log detectors
            for detector_num in self.detector_numbers:
                self.log_detector(detector_num)

            # Log Vortex unit status (force log every 24 hours)
            self.log_central_unit()

    def log_detector(self, detector_num):
        """Get the levels from one detector and log if required"""
        # Get detector info and levels for this detector
        conf = self.detector_info[detector_num]
        codename = self.conf_to_codename(conf)
        LOGGER.debug('Use detector {} \'{}\''.format(detector_num, codename))
        levels = self.vortex.get_detector_levels(detector_num)
        LOGGER.debug('Levels read: {}'.format(levels))

        # Detector level
        now = time.time()
        # Always send to live socket
        self.live_socket.set_point_now(codename, levels.level)
        print detector_num, codename, levels.level
        # Force log every 10 m
        time_condition = now - self.detector_levels_last_times[
            detector_num] > 600
        value_condition = abs(self.detector_levels_last_values[detector_num] - levels.level)\
                          >= self.trip_levels[detector_num]
        if time_condition or value_condition:
            LOGGER.debug('Send level to db trigged in time: {} or value: '
                         '{}'.format(time_condition, value_condition))
            self.db_logger.enqueue_point(codename, (now, levels.level))
            # Update last values
            self.detector_levels_last_values[detector_num] = levels.level
            self.detector_levels_last_times[detector_num] = now
        else:
            LOGGER.debug('Level logging condition false')

        self.log_detector_status(detector_num, levels, conf)

    def log_detector_status(self, detector_num, levels, conf):
        """Sub function to log single detector status"""
        now = time.time()
        # Force log every 24 hours
        time_condition = now - self.detector_status_last_times[
            detector_num] > 86400
        status = {
            'inhibit': levels.inhibit,
            'status': levels.status,
            'codename': conf.identity
        }
        value_condition = (status !=
                           self.detector_status_last_values[detector_num])
        print detector_num, status

        # Check if we should log
        if time_condition or value_condition:
            check_in = time_condition and not value_condition
            LOGGER.info('Send detector status to db trigged on time: {} or '
                        'value: {}'.format(time_condition, value_condition))
            query = 'INSERT INTO status_b312gasalarm '\
                '(time, device, status, check_in) '\
                'VALUES (FROM_UNIXTIME(%s), %s, %s, %s);'
            values = (now, detector_num, json.dumps(status), check_in)
            self._wake_mysql()
            self.db_cursor.execute(query, values)
            # Update last values
            self.detector_status_last_times[detector_num] = now
            self.detector_status_last_values[detector_num] = status
        else:
            LOGGER.debug('Detector status logging condition false')

    def log_central_unit(self):
        """Log the status of the central unit"""
        power_status = self.vortex.get_system_power_status().value
        print "power status", power_status
        now = time.time()
        # Force a log once per 24 hours
        time_condition = now - self.central_power_status_last_time > 86400
        value_condition = self.central_power_status_last_value != power_status
        LOGGER.debug('Read central power status: \'{}\''.format(power_status))
        if time_condition or value_condition:
            check_in = time_condition and not value_condition
            LOGGER.info('Send power status to db trigged in time: {} or '
                        'value: {}'.format(time_condition, value_condition))
            query = 'INSERT INTO status_b312gasalarm '\
                '(time, device, status, check_in) '\
                'VALUES (FROM_UNIXTIME(%s), %s, %s, %s);'
            values = (now, 255, json.dumps(power_status), check_in)
            self._wake_mysql()
            self.db_cursor.execute(query, values)
            # Update last values
            self.central_power_status_last_time = now
            self.central_power_status_last_value = power_status
        else:
            LOGGER.debug('Power status logging condition false')

        self.log_central_unit_generel()

    def log_central_unit_generel(self):
        """Log the generel status from the central"""
        generel_status = self.vortex.get_system_status()
        print "general status", generel_status
        now = time.time()
        # Force a log once per 24 hours
        time_condition = now - self.central_status_last_time > 86400
        value_condition = generel_status != self.central_status_last_value
        LOGGER.debug(
            'Read central generel status: \'{}\''.format(generel_status))
        if time_condition or value_condition:
            check_in = time_condition and not value_condition
            LOGGER.info('Send central generel status to db trigged in time: {}'
                        ' or value: {}'.format(time_condition,
                                               value_condition))
            query = 'INSERT INTO status_b312gasalarm '\
                '(time, device, status, check_in) '\
                'VALUES (FROM_UNIXTIME(%s), %s, %s, %s);'
            values = (now, 254, json.dumps(generel_status), check_in)
            self._wake_mysql()
            self.db_cursor.execute(query, values)
            # Update last values
            self.central_status_last_time = now
            self.central_status_last_value = generel_status
        else:
            LOGGER.debug('Central generel status logging confition false')

    def _wake_mysql(self):
        """Send a ping via the connection and re-initialize the cursor"""
        self.db_connection.ping(True)
        self.db_cursor = self.db_connection.cursor()
Example #20
0
class MainPID(threading.Thread):
    """ pid controller """
    def __init__(self,):
        logging.info('MainPID class started')
        threading.Thread.__init__(self)
        #from datalogger import TemperatureReader
        self.quit = False
        self.codenames = ['tabs_guard_pid_value',
                 'tabs_floor_pid_value',
                 'tabs_ceiling_pid_value',
                 'tabs_cooling_pid_value',
                 
                 'tabs_guard_valve_heating',
                 'tabs_floor_valve_heating',
                 'tabs_ceiling_valve_heating',
                 
                 'tabs_guard_valve_cooling',
                 'tabs_floor_valve_cooling',
                 'tabs_ceiling_valve_cooling',
                 'tabs_cooling_valve_cooling',
                 ]
        sockname = 'tabs_pids'
        self.PullSocket = DateDataPullSocket(sockname, self.codenames, timeouts=[60.0]*len(self.codenames), port = socketinfo.INFO[sockname]['port'])
        self.PullSocket.start()
    
        self.PTC = PidTemperatureControl(self.codenames)
        self.PTC.daemon = True
        self.PTC.start()
        #time.sleep(5)
    
        chlist = {'tabs_guard_pid_value': 0,
                  'tabs_floor_pid_value': 1,
                  'tabs_ceiling_pid_value': 2,
                  'tabs_cooling_pid_value': 3,
                  
                  'tabs_guard_valve_heating': 4,
                  'tabs_floor_valve_heating': 5,
                  'tabs_ceiling_valve_heating': 6,
                  
                  'tabs_guard_valve_cooling': 7,
                  'tabs_floor_valve_cooling': 8,
                  'tabs_ceiling_valve_cooling': 9,
                  'tabs_cooling_valve_cooling': 10}
        self.loggers = {}
        for key in self.codenames:
            self.loggers[key] = ValueLogger(self.PTC, comp_val = 0.10, maximumtime=60,
                                        comp_type = 'lin', channel = chlist[key])
            self.loggers[key].start()
        #livesocket = LiveSocket('tabs_temperature_logger', codenames, 2)
        #livesocket.start()

    
        self.db_logger = ContinuousLogger(table='dateplots_tabs', username=credentials.user, password=credentials.passwd, measurement_codenames=self.codenames)
        self.db_logger.start()

    def run(self,):
        i = 0
        while not self.quit and self.PTC.isAlive():
            try:
                #print(i)
                time.sleep(1)
                for name in self.codenames:
                    v = self.loggers[name].read_value()
                    #print('Status: ', name , v)
                    #livesocket.set_point_now(name, v)
                    self.PullSocket.set_point_now(name, v)
                    if self.loggers[name].read_trigged():
                        if __name__ == '__main__':
                            print('Log: ', i, name, v)
                        #print(i, name, v)
                        self.db_logger.enqueue_point_now(name, v)
                        self.loggers[name].clear_trigged()
            except (KeyboardInterrupt, SystemExit):
                self.quit = True
                pass
                #self.PTC.stop()
                #report error and proceed
            i += 1
        self.stop()

    def stop(self):
        self.quit = True
        self.PTC.stop()
        self.PullSocket.stop()
        self.db_logger.stop()
        for key in self.codenames:
            self.loggers[key].status['quit'] = True
Example #21
0
        print(pc)
        #db_logger.enqueue_point_now('stm312_pc', pc)
        pc_measurement.trigged = False
    time.sleep(0.5)
"""

Pullsocket = DateDataPullSocket('stm312 hpc pressure control', ['pressure', 'setpoint'])
Pushsocket = DataPushSocket('stm312 hpc pressure control', action='store_last')


if __name__ == '__main__':
    print('program start')
    Pullsocket.start()
    Pushsocket.start()
    #socket.start()
    db_logger_stm312.start()
    #db_logger_ocs.start()
    time.sleep(1)

    pc = PcClass()
    pc.add_socket_server(Pullsocket,Pushsocket)
    pc.add_logger(db_logger_stm312)
    pirani = PiraniClass()
    pirani.add_logger(db_logger_stm312)

    baratron = Baratron()
    #baratron.deamon = True
    baratron.start
    time.sleep(2)
    
    pc.start()
Example #22
0
loggers[codenames[1]] = ValueLogger(analog_measurement,
                                    comp_val=0.5,
                                    comp_type='lin')
loggers[codenames[1]].start()

socket = DateDataPullSocket('Volvo data logger',
                            codenames,
                            timeouts=[1.0, 1.0])
socket.start()

livesocket = LiveSocket('Volvo data logger', codenames, 2)
livesocket.start()

db_logger = ContinuousLogger(
    table='dateplots_volvo',
    username='******',
    password='******',
    measurement_codenames=['volvo_pressure', 'volvo_temperature'])
db_logger.start()

while pressure.isAlive() and analog_measurement.isAlive():
    time.sleep(0.25)
    for name in codenames:
        v = loggers[name].read_value()
        socket.set_point_now(name, v)
        livesocket.set_point_now(name, v)
        if loggers[name].read_trigged():
            print(v)
            db_logger.enqueue_point_now(name, v)
            loggers[name].clear_trigged()
Example #23
0
class MainMultilogger(threading.Thread):
    """ Temperature reader """
    def __init__(self, ):
        logging.info('MainMultilogger class started')
        threading.Thread.__init__(self)
        #from datalogger import TemperatureReader
        self.quit = False
        self.codenames = Setting_channel_list.keys()
        """['tabs_ceiling_temperature_delta',
                          'tabs_ceiling_temperature_deltaref',
                          'tabs_floor_temperature_delta',
                          'tabs_floor_temperature_deltaref',
                          'tabs_room_temperature_aircenter010',
                          'tabs_room_temperature_aircenter060',
                          'tabs_room_temperature_aircenter110',
                          'tabs_room_temperature_aircenter170',
                          'tabs_room_temperature_aircenter355',
                          'tabs_guard_temperature_airfloor',
                          'tabs_guard_temperature_airceiling',
                          'tabs_guard_temperature_airwallsouth',
                          'tabs_guard_temperature_airwallnorth',
                          'tabs_guard_temperature_airwalleast',
                          'tabs_guard_temperature_airwallwest',
                          
                          ]"""
        self.multiplex_reader = MultiplexReader(self.codenames)
        self.multiplex_reader.daemon = True
        self.multiplex_reader.start()
        #omega_temperature.update_values()

        time.sleep(3.5)

        chlist = Setting_channel_list
        self.loggers = {}
        for key in self.codenames:
            self.loggers[key] = ValueLogger(self.multiplex_reader,
                                            comp_val=0.5,
                                            maximumtime=300,
                                            comp_type='lin',
                                            channel=chlist[key])
            self.loggers[key].start()

        #livesocket = LiveSocket('tabs_temperature_logger', codenames, 2)
        #livesocket.start()
        sockname = 'tabs_multiplexer'
        self.PullSocket = DateDataPullSocket(
            sockname,
            self.codenames,
            timeouts=[60.0] * len(self.codenames),
            port=socketinfo.INFO[sockname]['port'])
        self.PullSocket.start()

        self.db_logger = ContinuousLogger(table='dateplots_tabs',
                                          username=credentials.user,
                                          password=credentials.passwd,
                                          measurement_codenames=self.codenames)
        self.db_logger.start()

    def run(self, ):
        i = 0
        while not self.quit and self.multiplex_reader.isAlive():
            try:
                #print(i)
                time.sleep(1)
                for name in self.codenames:
                    v = self.loggers[name].read_value()
                    #livesocket.set_point_now(name, v)
                    self.PullSocket.set_point_now(name, v)
                    #print(i, name, v)
                    if self.loggers[name].read_trigged(
                    ) and abs(v) < 9.9E+5 and v != None:
                        if __name__ == '__main__':
                            print('Log: ', i, name, v)
                        #print(name, v)
                        self.db_logger.enqueue_point_now(name, v)
                        self.loggers[name].clear_trigged()
            except (KeyboardInterrupt, SystemExit):
                self.quit = True
                pass
                #self.omega_temperature.close()
                #report error and proceed
            i += 1
        self.stop()

    def stop(self):
        self.quit = True
        self.multiplex_reader.stop()
        self.PullSocket.stop()
        self.db_logger.stop()
        for key in self.codenames:
            self.loggers[key].status['quit'] = True
Example #24
0
    loggers = {}
    loggers['pvd309_main_chamber_ig'] = PressureLogger(pressurereader, 3)
    loggers['pvd309_main_chamber_pirani'] = PressureLogger(pressurereader, 2)
    loggers['pvd309_load_lock_pirani'] = PressureLogger(pressurereader, 5)

    for codename in pressure_codenames:
        loggers[codename].start()

    socket = DateDataPullSocket('pvd309', pressure_codenames, timeouts=[5.0, 5.0, 5.0])
    socket.start()

    db_logger = ContinuousLogger(table='dateplots_pvd309',
                                 username=credentials.user,
                                 password=credentials.passwd,
                                 measurement_codenames=pressure_codenames)
    db_logger.start()

    time.sleep(3)

    while True:
        time.sleep(0.25)
        for codename in pressure_codenames:
            p = loggers[codename].read_pressure()
            socket.set_point_now(codename, p)
            if loggers[codename].trigged:
                print p
                db_logger.enqueue_point_now(codename, p)
                loggers[codename].trigged = False


Example #25
0
class MainMultilogger(threading.Thread):
    """ Temperature reader """
    def __init__(self,):
        logging.info('MainMultilogger class started')
        threading.Thread.__init__(self)
        #from datalogger import TemperatureReader
        self.quit = False
        self.codenames = Setting_channel_list.keys()
        """['tabs_ceiling_temperature_delta',
                          'tabs_ceiling_temperature_deltaref',
                          'tabs_floor_temperature_delta',
                          'tabs_floor_temperature_deltaref',
                          'tabs_room_temperature_aircenter010',
                          'tabs_room_temperature_aircenter060',
                          'tabs_room_temperature_aircenter110',
                          'tabs_room_temperature_aircenter170',
                          'tabs_room_temperature_aircenter355',
                          'tabs_guard_temperature_airfloor',
                          'tabs_guard_temperature_airceiling',
                          'tabs_guard_temperature_airwallsouth',
                          'tabs_guard_temperature_airwallnorth',
                          'tabs_guard_temperature_airwalleast',
                          'tabs_guard_temperature_airwallwest',
                          
                          ]"""
        self.multiplex_reader = MultiplexReader(self.codenames)
        self.multiplex_reader.daemon = True
        self.multiplex_reader.start()
        #omega_temperature.update_values()
        
        time.sleep(3.5)
        
        chlist = Setting_channel_list
        self.loggers = {}
        for key in self.codenames:
            self.loggers[key] = ValueLogger(self.multiplex_reader, comp_val = 0.5, maximumtime=300,
                                            comp_type = 'lin', channel = chlist[key])
            self.loggers[key].start()
        
        #livesocket = LiveSocket('tabs_temperature_logger', codenames, 2)
        #livesocket.start()
        sockname = 'tabs_multiplexer'
        self.PullSocket = DateDataPullSocket(sockname, self.codenames, timeouts=[60.0]*len(self.codenames), port = socketinfo.INFO[sockname]['port'])
        self.PullSocket.start()
        
        self.db_logger = ContinuousLogger(table='dateplots_tabs', username=credentials.user, password=credentials.passwd, measurement_codenames=self.codenames)
        self.db_logger.start()
    
    def run(self,):
        i = 0
        while not self.quit and self.multiplex_reader.isAlive():
            try:
                #print(i)
                time.sleep(1)
                for name in self.codenames:
                    v = self.loggers[name].read_value()
                    #livesocket.set_point_now(name, v)
                    self.PullSocket.set_point_now(name, v)
                    #print(i, name, v)
                    if self.loggers[name].read_trigged() and abs(v) < 9.9E+5 and v != None:
                        if __name__ == '__main__':
                            print('Log: ', i, name, v)
                        #print(name, v)
                        self.db_logger.enqueue_point_now(name, v)
                        self.loggers[name].clear_trigged()
            except (KeyboardInterrupt, SystemExit):
                self.quit = True
                pass
                #self.omega_temperature.close()
                #report error and proceed
            i += 1
        self.stop()
        
    def stop(self):
        self.quit = True
        self.multiplex_reader.stop()
        self.PullSocket.stop()
        self.db_logger.stop()        
        for key in self.codenames:
            self.loggers[key].status['quit'] = True