コード例 #1
0
ファイル: __init__.py プロジェクト: dan-cristian/haiot
def __save_sensor_db(p_id='', p_type='', value_list=None):
    if not value_list:
        value_list = []

    record = m.Sensor.find_one({m.Sensor.address: p_id})
    if record is None:
        record = m.Sensor()
        record.address = p_id
    zone_sensor = m.ZoneSensor.find_one({m.ZoneSensor.sensor_address: p_id})
    if zone_sensor:
        record.sensor_name = zone_sensor.sensor_name
    else:
        record.sensor_name = '(not defined) ' + p_id
    record.updated_on = utils.get_base_location_now_date()
    record.type = p_type
    if 'Humidity' in value_list:
        record.humidity = utils.round_sensor_value(value_list['Humidity'])
    if 'Temperature' in value_list:
        record.temperature = utils.round_sensor_value(
            value_list['Temperature'])
    if 'Battery numeric' in value_list:
        record.battery_level = value_list['Battery numeric']
    if 'Rssi numeric' in value_list:
        record.rssi = value_list['Rssi numeric']
    # L.l.info('Saving RFX object {}'.format(record))
    record.save_changed_fields(broadcast=True, persist=True)
コード例 #2
0
def __save_sensor_db(p_id='', p_type='', value_list=None):
    if not value_list:
        value_list = []
    record = models.Sensor(address=p_id)
    assert isinstance(record, models.Sensor)
    zone_sensor = models.ZoneSensor.query.filter_by(
        sensor_address=p_id).first()
    if zone_sensor:
        record.sensor_name = zone_sensor.sensor_name
    else:
        record.sensor_name = '(not defined) ' + p_id
    record.updated_on = utils.get_base_location_now_date()
    record.type = p_type
    if 'Humidity' in value_list:
        record.humidity = utils.round_sensor_value(value_list['Humidity'])
    if 'Temperature' in value_list:
        record.temperature = utils.round_sensor_value(
            value_list['Temperature'])
    if 'Battery numeric' in value_list:
        record.battery_level = value_list['Battery numeric']
    if 'Rssi numeric' in value_list:
        record.rssi = value_list['Rssi numeric']
    current_record = models.Sensor.query.filter_by(address=p_id).first()
    record.save_changed_fields(current_record=current_record,
                               new_record=record,
                               notify_transport_enabled=True,
                               save_to_graph=True,
                               ignore_only_updated_on_change=True)
コード例 #3
0
def _read_disk_stats():
    #fixme
    return
    if Constant.is_os_linux():
        with open('/proc/diskstats') as f:
            for line in f:
                words = line.split()
                if len(words) > 8:
                    device_major = words[0]
                    device_name = words[2]

                    # skip for non hdds and partitions (ending with digit)
                    if device_major != '8' or device_name[-1:].isdigit():
                        continue  # just to avoid another tab
                    record = m.SystemDisk.find_one({m.SystemDisk.hdd_disk_dev: '/dev/' + device_name,
                                                    m.SystemDisk.system_name: Constant.HOST_NAME})
                    if record is None:
                        record = models.SystemDisk()
                    reads_completed = utils.round_sensor_value(words[3])
                    writes_completed = utils.round_sensor_value(words[7])
                    record.hdd_disk_dev = '/dev/' + device_name
                    record.last_reads_completed_count = reads_completed
                    record.last_writes_completed_count = writes_completed
                    record.system_name = Constant.HOST_NAME
                    record.updated_on = utils.get_base_location_now_date()
                    # save read/write date time only if count changes
                    if current_record is not None:
                        if current_record.serial is None or current_record.serial == '':
                            record.serial = 'serial not available {} {}'.format(Constant.HOST_NAME, record.hdd_disk_dev)
                        if current_record.hdd_name is None or current_record.hdd_name == '':
                            record.hdd_name = '{} {}'.format(Constant.HOST_NAME, record.hdd_disk_dev)
                        read_elapsed = -1
                        write_elapsed = -1
                        if record.last_reads_completed_count != current_record.last_reads_completed_count:
                            record.last_reads_datetime = utils.get_base_location_now_date()
                        else:
                            record.last_reads_datetime = current_record.last_reads_datetime
                        if record.last_writes_completed_count != current_record.last_writes_completed_count:
                            record.last_writes_datetime = utils.get_base_location_now_date()
                        else:
                            record.last_writes_datetime = current_record.last_writes_datetime
                        if current_record.last_reads_datetime:
                            read_elapsed = (utils.get_base_location_now_date()
                                            - record.last_reads_datetime).total_seconds()
                            record.last_reads_elapsed = utils.round_sensor_value(read_elapsed)
                        if current_record.last_writes_datetime:
                            write_elapsed = (utils.get_base_location_now_date()
                                             - record.last_writes_datetime).total_seconds()
                            record.last_writes_elapsed = utils.round_sensor_value(write_elapsed)
                        L.l.debug('Disk {} elapsed read {}s write {}s'.format(
                            device_name, int(read_elapsed), int(write_elapsed)))
                    else:
                        record.last_reads_datetime = utils.get_base_location_now_date()
                        record.last_writes_datetime = utils.get_base_location_now_date()
                        record.serial = 'serial not available {} {}'.format(Constant.HOST_NAME, record.hdd_disk_dev)
                    record.save_changed_fields(current_record=current_record, new_record=record,
                                               notify_transport_enabled=True, save_to_graph=True, debug=False)
                else:
                    L.l.warning(
                        'Unexpected lower number of split atoms={} in diskstat={}'.format(len(words), line))
コード例 #4
0
def __read_ups_status():
    status = __write_read_port(P.serial, 'Q1\r')
    if status != '':
        status = status.replace('(', '')
        atoms = status.split()
        if len(atoms) >= 8:
            P.ups.InputVoltage = round(utils.round_sensor_value(atoms[0]), 0)
            P.ups.RemainingMinutes = utils.round_sensor_value(atoms[1])
            P.ups.OutputVoltage = round(utils.round_sensor_value(atoms[2]), 0)
            P.ups.LoadPercent = utils.round_sensor_value(atoms[3])
            P.ups.PowerFrequency = atoms[4]
            P.ups.BatteryVoltage = atoms[5]
            P.ups.Temperature = atoms[6]
            P.ups.OtherStatus = atoms[7]
            if len(P.ups.OtherStatus) >= 8:
                P.ups.PowerFailed = (P.ups.OtherStatus[0] == '1')
                P.ups.TestInProgress = (P.ups.OtherStatus[5] == '1')
                P.ups.BeeperOn = (P.ups.OtherStatus[7] == '1')

            record = models.Ups()
            record.name = P.ups.Name
            record.system_name = Constant.HOST_NAME
            record.input_voltage = P.ups.InputVoltage
            record.remaining_minutes = P.ups.RemainingMinutes
            record.battery_voltage = P.ups.BatteryVoltage
            record.beeper_on = P.ups.BeeperOn
            record.load_percent = P.ups.LoadPercent
            record.output_voltage = P.ups.OutputVoltage
            record.power_frequency = P.ups.PowerFrequency
            record.temperature = P.ups.Temperature
            record.other_status = P.ups.OtherStatus
            record.power_failed = P.ups.PowerFailed
            record.updated_on = utils.get_base_location_now_date()
            current_record = models.Ups.query.filter_by(
                system_name=Constant.HOST_NAME).first()
            record.save_changed_fields(current_record=current_record,
                                       new_record=record,
                                       notify_transport_enabled=True,
                                       save_to_graph=True)

            L.l.debug('UPS remaining={} load={} input={} output={}'.format(
                P.ups.RemainingMinutes, P.ups.LoadPercent, P.ups.InputVoltage,
                P.ups.OutputVoltage))
        else:
            L.l.warning(
                'Unexpected number of parameters ({}) on ups status read'.
                format(len(atoms)))
    else:
        L.l.info('Read empty UPS status')
コード例 #5
0
def get_temperature(sensor, dev, ow):
    try:
        dev = get_prefix(sensor, dev, ow)
        # 2 digits round
        if P.failed_temp and P.failed_temp_count < 100:
            val = utils.round_sensor_value(ow.read(sensor + 'fasttemp'))
        else:
            val = utils.round_sensor_value(ow.read(sensor + 'temperature'))
            P.failed_temp_count = 0
        if val != P.IGNORED_TEMPERATURE:
            dev['temperature'] = val
    except Exception as ex:
        L.l.warning("Read temp failed with {}".format(ex))
        P.failed_temp = True
        P.failed_temp_count += 1
    return dev
コード例 #6
0
def __get_cpu_temperature():
    temp = -1
    if Constant.IS_OS_WINDOWS():
        # http://stackoverflow.com/questions/3262603/accessing-cpu-temperature-in-python
        global import_module_wmi_ok
        if import_module_wmi_ok:
            try:
                pythoncom.CoInitialize()
                w = wmi.WMI(namespace="root\wmi")
                temperature_info = w.MSAcpi_ThermalZoneTemperature()[0]
                temp = (temperature_info.CurrentTemperature / 10) - 273
            except Exception as ex:
                L.l.error(
                    'Unable to get temperature using wmi, err={}'.format(ex))
        else:
            L.l.warning('Unable to get CPU temp, no function available')
    else:
        if Constant.IS_MACHINE_RASPBERRYPI:
            path = '/sys/class/thermal/thermal_zone0/temp'
        elif Constant.IS_MACHINE_BEAGLEBONE:
            path = '/sys/class/hwmon/hwmon0/device/temp1_input'
        elif Constant.IS_MACHINE_INTEL:
            path = '/sys/devices/virtual/thermal/thermal_zone0/temp'
        else:
            path = None
        line = '-1'
        if path and os.path.isfile(path):
            file = None
            try:
                file = open(path)
                line = file.readline()
            except Exception as ex:
                L.l.error('Unable to open cpu_temp_read file {}'.format(path))
            if file:
                file.close()
        else:
            L.l.debug('Unable to get CPU temp for machine type {}'.format(
                Constant.HOST_MACHINE_TYPE))
        temp = float(line) / 1000
    temp = utils.round_sensor_value(temp)
    return temp
コード例 #7
0
def get_temperature(sensor, dev, ow):
    try:
        dev = get_prefix(sensor, dev, ow)
        # val = None
        # 2 digits round
        # if P.failed_temp and P.failed_temp_count < 100:
        #    try:
        #        val = utils.round_sensor_value(ow.read(sensor + 'fasttemp'))
        #    except Exception as ex1:
        #        # fasttemp might not exist, so revert to normal
        #        P.failed_temp = False
        #        P.failed_temp_count = 0
        # if val is None:
        val = utils.round_sensor_value(
            ow.read(sensor + 'temperature').decode('utf-8'))
        P.failed_temp_count = 0
        P.failed_temp = False
        if val != P.IGNORED_TEMPERATURE:
            dev['temperature'] = val
    except Exception as ex:
        L.l.warning("Read temp with {}".format(ex))
        # P.failed_temp = True
        # P.failed_temp_count += 1
    return dev
コード例 #8
0
def _read_all_hdd_smart():
    output = cStringIO.StringIO()
    current_disk_valid = True
    disk_letter = 'a'
    disk_count = 1
    global ERR_TEXT_NO_DEV
    if import_module_psutil_exist:
        while current_disk_valid and disk_count < 64:
            try:
                record = models.SystemDisk()
                record.system_name = Constant.HOST_NAME
                assert isinstance(record, models.SystemDisk)
                record.hdd_disk_dev = Constant.DISK_DEV_MAIN + disk_letter
                L.l.debug('Processing disk {}'.format(record.hdd_disk_dev))
                try:
                    record.power_status = __read_hddparm(
                        disk_dev=record.hdd_disk_dev)
                except Exception as ex1:
                    record.power_status = None
                try:
                    use_sudo = bool(
                        model_helper.get_param(Constant.P_USESUDO_DISKTOOLS))
                    if Constant.OS in Constant.OS_LINUX and use_sudo:
                        smart_out = subprocess.check_output(
                            [
                                'sudo', 'smartctl', '-a', record.hdd_disk_dev,
                                '-n', 'sleep'
                            ],
                            stderr=subprocess.STDOUT)
                    else:  # in windows
                        smart_out = subprocess.check_output(
                            [
                                'smartctl', '-a', record.hdd_disk_dev, '-n',
                                'sleep'
                            ],
                            stderr=subprocess.STDOUT)
                except subprocess.CalledProcessError as exc:
                    smart_out = exc.output
                    if ERR_TEXT_NO_DEV in smart_out or ERR_TEXT_NO_DEV_3 in smart_out:
                        raise exc
                except Exception as ex:
                    smart_out = None
                    current_disk_valid = False
                    L.l.warning("Error checking smart status {}".format(ex))

                if smart_out:
                    output.reset()
                    output.write(smart_out)
                    output.seek(0)
                    pos = -1
                    while pos != output.tell() and current_disk_valid:
                        pos = output.tell()
                        line = output.readline()
                        if Constant.SMARTCTL_ERROR_NO_DISK in line:
                            current_disk_valid = False
                            L.l.debug(
                                'First disk that cannot be read is {}'.format(
                                    record.hdd_disk_dev))
                        if Constant.SMARTCTL_TEMP_ID in line:
                            words = line.split(None)
                            record.temperature = utils.round_sensor_value(
                                words[9])
                            # print 'Temp is {}'.format(temp)
                        if Constant.SMARTCTL_ERROR_SECTORS in line:
                            words = line.split(None)
                            record.sector_error_count = words[9]
                            # print 'Offline sectors with error is {}'.format(errcount)
                        if Constant.SMARTCTL_START_STOP_COUNT in line:
                            words = line.split(None)
                            record.start_stop_count = words[9]
                        if Constant.SMARTCTL_LOAD_CYCLE_COUNT in line:
                            words = line.split(None)
                            record.load_cycle_count = words[9]
                        if Constant.SMARTCTL_STATUS in line:
                            words = line.split(': ')
                            record.smart_status = words[1].replace(
                                '\r', '').replace('\n', '').strip()
                            # print 'SMART Status is {}'.format(status)
                        if Constant.SMARTCTL_MODEL_DEVICE in line:
                            words = line.split(': ')
                            record.device = words[1].replace('\r', '').replace(
                                '\n', '').lstrip()
                            # print 'Device is {}'.format(device)
                        if Constant.SMARTCTL_MODEL_FAMILY in line:
                            words = line.split(': ')
                            record.family = words[1].replace('\r', '').replace(
                                '\n', '').lstrip()
                            # print 'Family is {}'.format(family)
                        if Constant.SMARTCTL_SERIAL_NUMBER in line:
                            words = line.split(': ')
                            record.serial = words[1].replace('\r', '').replace(
                                '\n', '').lstrip()
                            # print 'Serial is {}'.format(serial)
                            # print ('Disk dev is {}'.format(disk_dev))
                record.updated_on = utils.get_base_location_now_date()
                if record.serial is None or record.serial == '':
                    L.l.debug(
                        'This hdd will be skipped, probably does not exist if serial not retrieved'
                    )
                    record.serial = 'serial not available {} {}'.format(
                        Constant.HOST_NAME, record.hdd_disk_dev)
                else:
                    record.hdd_name = '{} {} {}'.format(
                        record.system_name, record.hdd_device,
                        record.hdd_disk_dev)
                    current_record = models.SystemDisk.query.filter_by(
                        hdd_disk_dev=record.hdd_disk_dev,
                        system_name=record.system_name).first()
                    record.save_changed_fields(current_record=current_record,
                                               new_record=record,
                                               notify_transport_enabled=True,
                                               save_to_graph=True)
                disk_letter = chr(ord(disk_letter) + 1)
                disk_count += 1
            except subprocess.CalledProcessError as ex1:
                L.l.debug('Invalid disk {} err {}'.format(
                    record.hdd_disk_dev, ex1))
                current_disk_valid = False
            except Exception as exc:
                if disk_count > 10:
                    L.l.warning(
                        'Too many disks iterated {}, missing or wrong sudo rights for smartctl'
                        .format(disk_count))
                L.l.exception('Disk read error={} dev={}'.format(
                    exc, record.hdd_disk_dev))
                current_disk_valid = False
    else:
        L.l.debug('Unable to read smart status')
コード例 #9
0
def get_humidity(sensor, dev, ow):
    dev = get_prefix(sensor, dev, ow)
    dev['humidity'] = utils.round_sensor_value(
        ow.read(sensor + 'humidity').decode('utf-8'))
    return dev