$akcp_array = snmpwalk_cache_multi_oid($device, "sensorProbeSwitchTable", $akcp_array, "SPAGENT-MIB", mib_dirs('akcp'));
foreach ($akcp_array as $index => $entry) {
    if ($entry['sensorProbeTempStatus']) {
        # Temp sensor
        # FIXME do we need to take note of this? [sensorProbeTempOffset] => 0
        $descr = $entry['sensorProbeTempDescription'];
        $oid = ".1.3.6.1.4.1.3854.1.2.2.1.16.1.3.{$index}";
        # SPAGENT-MIB:sensorProbeTempDegree.$index
        $value = $entry['sensorProbeTempDegree'];
        $limits = array('limit_high' => $entry['sensorProbeTempHighCritical'], 'limit_low' => $entry['sensorProbeTempLowCritical'], 'limit_high_warn' => $entry['sensorProbeTempHighWarning'], 'limit_low_warn' => $entry['sensorProbeTempLowWarning']);
        $scale_temp = 1;
        if ($entry['sensorProbeTempDegreeType'] == 'fahr') {
            $scale_temp = 5 / 9;
            //$value      = f2c($value);
            foreach (array('limit_high', 'limit_low', 'limit_high_warn', 'limit_low_warn') as $param) {
                $limits[$param] = f2c($limits[$param]);
                // Convert from fahrenheit to celsius
            }
        }
        if ($entry['sensorProbeTempStatus'] != 'noStatus') {
            discover_sensor($valid['sensor'], 'temperature', $device, $oid, $index, 'akcp', $descr, $scale_temp, $value, $limits);
        }
    }
    if ($entry['sensorProbeHumidityStatus']) {
        # Humidity sensor
        # FIXME do we need to take note of this? [sensorProbeHumidityOffset] => 0
        $descr = $entry['sensorProbeHumidityDescription'];
        $oid = ".1.3.6.1.4.1.3854.1.2.2.1.17.1.3.{$index}";
        # SPAGENT-MIB:sensorProbeHumidityPercent.$index
        $value = $entry['sensorProbeHumidityPercent'];
        $limits = array('limit_high' => $entry['sensorProbeHumidityHighCritical'], 'limit_low' => $entry['sensorProbeHumidityLowCritical'], 'limit_high_warn' => $entry['sensorProbeHumidityHighWarning'], 'limit_low_warn' => $entry['sensorProbeHumidityLowWarning']);
示例#2
0
 //tempHumidSensorTempValue
 $oid = '.1.3.6.1.4.1.1718.3.2.5.1.6.1.' . $index;
 if (isset($entry['tempHumidSensorTempValue']) && $entry['tempHumidSensorTempValue'] >= 0) {
     if (isset($entry['tempHumidSensorTempScale'])) {
         // Note, after MIB revision "200606120930Z" scale changed to "tenth degrees"
         $scale_temp = 0.1;
     } else {
         $scale_temp = 1;
     }
     $value = $entry['tempHumidSensorTempValue'] * $scale_temp;
     $limits = array('limit_high' => isset($entry['tempHumidSensorTempHighThresh']) ? $entry['tempHumidSensorTempHighThresh'] * $scale_temp : NULL, 'limit_low' => isset($entry['tempHumidSensorTempLowThresh']) ? $entry['tempHumidSensorTempLowThresh'] * $scale_temp : NULL);
     if ($entry['tempHumidSensorTempScale'] == 'fahrenheit') {
         $scale_temp *= 5 / 9;
         $value = f2c($value);
         $limits['limit_high'] = f2c($limits['limit_high']);
         $limits['limit_low'] = f2c($limits['limit_low']);
     }
     ## Rename code for older revisions
     $old_rrd = $config['rrd_dir'] . '/' . $device['hostname'] . '/' . safename("sensor-temperature-sentry3-{$index}.rrd");
     $new_rrd = $config['rrd_dir'] . '/' . $device['hostname'] . '/' . safename("sensor-temperature-sentry3-tempHumidSensor.{$index}.rrd");
     if (is_file($old_rrd)) {
         rename($old_rrd, $new_rrd);
         print_message('Moved RRD');
     }
     discover_sensor($valid['sensor'], 'temperature', $device, $oid, "tempHumidSensor.{$index}", 'sentry3', $descr, $scale_temp, $value, $limits);
 }
 //tempHumidSensorHumidValue
 $oid = '.1.3.6.1.4.1.1718.3.2.5.1.10.1.' . $index;
 if (isset($entry['tempHumidSensorHumidValue']) && $entry['tempHumidSensorHumidValue'] >= 0) {
     $limits = array('limit_high' => isset($entry['tempHumidSensorHumidHighThresh']) ? $entry['tempHumidSensorHumidHighThresh'] : NULL, 'limit_low' => isset($entry['tempHumidSensorHumidLowThresh']) ? $entry['tempHumidSensorHumidLowThresh'] : NULL);
     $value = $entry['tempHumidSensorHumidValue'];
示例#3
0
文件: currents.php 项目: raprasad/iem
$lbl->set("font", "liberation");
$lbl->set("size", 18);
//$lbl->set("color", $black);
$lbl->set("position", MS_AUTO);
$lbl->set("force", MS_ON);
$ly2 = $map->getLayerByName("pointonly");
$ly2->set("status", MS_ON);
$ly2->setProjection("init=epsg:4326");
$barbs = $map->getlayerbyname("barbs");
$barbs->set("status", MS_ON);
$bclass = $barbs->getClass(0);
$now = time();
foreach ($sts as $key => $value) {
    $bzz = $value;
    $sped = $bzz->db["sknt"] * 1.15078;
    $bzz->db["relh"] = relh(f2c($bzz->db["tmpf"]), f2c($bzz->db["dwpf"]));
    $bzz->db["feel"] = feels_like($bzz->db["tmpf"], $bzz->db["relh"], $sped);
    $val = round(@$bzz->db[$var], @$rnd[$var]);
    $mynetwork = $bzz->db["network"];
    if (($now - $bzz->ts < 3900 || (substr($mynetwork, 3, 4) == "COOP" || $mynetwork == "IACOCORAHS") && $now - $bzz->ts < 86400) && $val > -99 & $val != 99) {
        if (in_array('barbs', $layers)) {
            $pt = ms_newPointObj();
            $pt->setXY($bzz->db["x"], $bzz->db["y"], 0);
            $rotate = 0 - intval($bzz->db["drct"]);
            $bclass->getLabel(0)->set("angle", doubleval($rotate));
            $pt->draw($map, $barbs, $img, 0, skntChar($bzz->db["sknt"]));
        }
        if ($var == "barb" && $bzz->db["sknt"] > -1) {
            $pt = ms_newPointObj();
            $pt->setXY($bzz->db["x"], $bzz->db["y"], 0);
            $rotate = 0 - intval($bzz->db["drct"]);
示例#4
0
文件: obs.php 项目: raprasad/iem
        arsort($indexMap);
    }
    while (list($firstIndex, ) = each($indexMap)) {
        if (is_numeric($firstIndex)) {
            $sortedArray[] = $multiArray[$firstIndex];
        } else {
            $sortedArray[$firstIndex] = $multiArray[$firstIndex];
        }
    }
    return $sortedArray;
}
$mydata = array();
while (list($key, $iemob) = each($asos)) {
    $mydata[$key] = $iemob->db;
    $mydata[$key]["sped"] = $mydata[$key]["sknt"] * 1.15078;
    $mydata[$key]["relh"] = relh(f2c($mydata[$key]["tmpf"]), f2c($mydata[$key]["dwpf"]));
    if ($mydata[$key]["relh"] < 5) {
        $mydata[$key]["relh"] = "M";
        $mydata[$key]["dewpf"] = "M";
        if ($sortcol == "feel" || $sortcol == "dwpf" || $sortcol == "relh") {
            $mydata[$key] = 0;
            continue;
        }
    }
    if ($mydata[$key]["tmpf"] < -60) {
        $mydata[$key]["tmpf"] = "M";
        if ($sortcol == "tmpf" || $sortcol == "feel" || $sortcol == "dwpf" || $sortcol == "relh") {
            $mydata[$key] = 0;
            continue;
        }
    }
示例#5
0
function formatter($i, $row)
{
    $ts = strtotime(substr($row["valid"], 0, 16));
    $relh = relh(f2c($row["tmpf"]), f2c($row["dwpf"]));
    return sprintf("<tr style=\"background: %s;\"><td>%s</td><td>%s</td><td>%s</td>\n\t<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>\n\t<td><span class=\"high\">%s</span></td>\n\t<td><span class=\"low\">%s</span></td>\n\t<td>%.0f%%</td>\n\t<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n\t<tr style=\"background: %s;\" class=\"metar\"><td colspan=\"15\">%s</td></tr>", $i % 2 == 0 ? "#FFF" : "#EEE", date("g:i A", $ts), wind_formatter($row), vis_formatter($row["vsby"]), sky_formatter($row), $row["presentwx"], temp_formatter($row["tmpf"]), temp_formatter($row["dwpf"]), temp_formatter(feels_like($row["tmpf"], $relh, $row["sknt"] * 1.15)), temp_formatter($row["max_tmpf_6hr"]), temp_formatter($row["min_tmpf_6hr"]), relh(f2c($row["tmpf"]), f2c($row["dwpf"])), $row["alti"], $row["pres"], $row["phour"], $row["p03i"], $row["p06i"], $i % 2 == 0 ? "#FFF" : "#EEE", $row["raw"]);
}
示例#6
0
foreach (array("memSensorsStatusTable") as $table) {
    echo "{$table} ";
    $cache['apc'] = snmpwalk_cache_multi_oid($device, $table, $cache['apc'], "PowerNet-MIB", mib_dirs('apc'));
}
$temp_units = snmp_get($device, "memSensorsStatusSysTempUnits.0", "-Ovq", "PowerNet-MIB", mib_dirs('apc'));
foreach ($cache['apc'] as $index => $entry) {
    $descr = $entry['memSensorsStatusSensorName'];
    $oid = ".1.3.6.1.4.1.318.1.1.10.4.2.3.1.5.{$index}";
    $value = $entry['memSensorsTemperature'];
    list(, $ems_index) = explode('.', $index);
    // Exclude already added sensor from emsProbeStatusTable
    if ($value != '' && $value != -1 && !isset($valid['sensor']['temperature']['apc']["emsProbeStatusProbeTemperature.{$ems_index}"])) {
        $scale_temp = 1;
        if ($temp_units == 'fahrenheit') {
            $scale_temp = 5 / 9;
            $value = f2c($value);
            // Convert from fahrenheit to celsius
            print_debug('TEMP sensor: Fahrenheit -> Celsius');
        }
        ## Rename code for older revisions
        $old_rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/" . safename("sensor-temperature-apc-{$index}.rrd");
        $new_rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/" . safename("sensor-temperature-apc-memSensorsTemperature.{$index}.rrd");
        if (is_file($old_rrd)) {
            rename($old_rrd, $new_rrd);
            print_warning("Moved RRD");
        }
        discover_sensor($valid['sensor'], 'temperature', $device, $oid, "memSensorsTemperature.{$index}", 'apc', $descr, $scale_temp, $value);
    }
    $oid = ".1.3.6.1.4.1.318.1.1.10.4.2.3.1.6.{$index}";
    $value = $entry['memSensorsHumidity'];
    // Exclude already added sensor from emsProbeStatusTable
示例#7
0
                    case "low":
                    case "high":
                    case "crit":
                    case "warn":
                    case "hyst":
                        $array[$value] = preg_replace('/[^0-9\\.\\-]/', '', array_shift($data));
                        break;
                }
            }
            if ($array['class'] == "temperature" && $array['scale'] < 1) {
                //$array['current'] = f2c($array['current']);
                $array['high'] = f2c($array['high']);
                $array['low'] = f2c($array['low']);
            }
        }
        if (isset($array) && isset($array['class'])) {
            $sensors_array[$array['descr']] = $array;
        }
        unset($array);
    }
    foreach ($sensors_array as $key => $array) {
        $limits = array('limit_high' => $array['high'], 'limit_low' => $array['low']);
        discover_sensor($valid['sensor'], $array['class'], $device, '', $key, 'lmsensors', $array['descr'], $array['scale'], $array['current'], $limits, 'agent');
        if ($array['class'] == "temperature" && $array['scale'] < 1) {
            $array['current'] = f2c($array['current']);
        }
        $agent_sensors[$array['class']]['lmsensors'][$key] = array('description' => $array['descr'], 'current' => $array['current'], 'index' => $key);
    }
    #print_r($sensors_array);
}
// EOF
示例#8
0
文件: dl.php 项目: muthulatha/iem
     
     StationID, Year, DOY, SRAD, Tmax, Tmin, Rain, DewP, Wind, Par, dbnum
     CTRL, 1981, 1, 5.62203, 2.79032, -3.53361, 5.43766, NaN, NaN, NaN, 2
     CTRL, 1981, 2, 3.1898, 1.59032, -6.83361, 1.38607, NaN, NaN, NaN, 3
     */
     if (sizeof($stations) > 1) {
         die("Sorry, only one station request at a time for daycent option");
     }
     if ($selectAll) {
         die("Sorry, only one station request at a time for daycent option");
     }
     pg_prepare($connection, "TBD", "SELECT extract(doy from day) as doy, high," . " low, precip, month, year, extract(day from day) as lday, station, year," . " coalesce(narr_srad, merra_srad, hrrr_srad) as srad" . " from {$table} WHERE station IN " . $stationString . " and " . " day >= '" . $sqlTS1 . "' and day <= '" . $sqlTS2 . "' ORDER by day ASC");
     $rs = pg_execute($connection, 'TBD', array());
     echo "StationID, Year, DOY, SRAD, Tmax, Tmin, Rain, DewP, Wind, Par, dbnum\n";
     for ($i = 0; $row = @pg_fetch_assoc($rs, $i); $i++) {
         echo sprintf("%s, %s, %s, %.4f, %.2f, %.2f, %.2f, , , , %s\n", substr($row["station"], 0, 4), $row["year"], $row["doy"], $row["srad"] === null ? -99 : $row["srad"], f2c($row["high"]), f2c($row["low"]), $row["precip"] * 25.4, $i + 2);
     }
 } else {
     if ($what != "plot") {
         $rs = pg_exec($connection, $sqlStr);
         pg_close($connection);
         if ($gis == "yes") {
             echo "station" . $d[$delim] . "station_name" . $d[$delim] . "lat" . $d[$delim] . "lon" . $d[$delim] . "day" . $d[$delim] . "julianday" . $d[$delim];
         } else {
             echo "station" . $d[$delim] . "station_name" . $d[$delim] . "day" . $d[$delim] . "julianday" . $d[$delim];
         }
         for ($j = 0; $j < $num_vars; $j++) {
             echo $vars[$j] . $d[$delim];
         }
         echo "\r\n";
         for ($i = 0; $row = @pg_fetch_array($rs, $i); $i++) {
示例#9
0
            $array['current'] = preg_replace('/[^0-9\\.\\-]/', '', array_shift($data));
            while ($value = array_shift($data)) {
                switch ($value) {
                    case "low":
                    case "high":
                    case "crit":
                    case "warn":
                    case "hyst":
                        $array[$value] = preg_replace('/[^0-9\\.\\-]/', '', array_shift($data));
                        break;
                }
            }
            if ($array['scale'] < 1) {
                $array['current'] = f2c($array['current']);
                $array['high'] = f2c($array['high']);
                $array['low'] = f2c($array['low']);
            }
        }
        if (isset($array) && isset($array['class'])) {
            $sensors_array[$array['descr']] = $array;
        }
        unset($array);
    }
    foreach ($sensors_array as $key => $array) {
        $limits = array('limit_high' => $array['high'], 'limit_low' => $array['low']);
        discover_sensor($valid['sensor'], $array['class'], $device, '', $key, 'lmsensors', $array['descr'], $array['scale'], $array['current'], $limits, 'agent');
        $agent_sensors[$array['class']]['lmsensors'][$key] = array('description' => $array['descr'], 'current' => $array['current'], 'index' => $key);
    }
    #print_r($sensors_array);
}
// EOF
     # FIXME do we need to take note of this? [sensorProbeTempOffset] => 0
     $descr = $entry['sensorProbeTempDescription'];
     $oid = ".1.3.6.1.4.1.3854.1.2.2.1.16.1.3.{$index}";
     # SPAGENT-MIB:sensorProbeTempDegree.$index
     $value = $entry['sensorProbeTempDegree'];
     $low_limit = $entry['sensorProbeTempLowCritical'];
     $low_warn_limit = $entry['sensorProbeTempLowWarning'];
     $warn_limit = $entry['sensorProbeTempHighWarning'];
     $limit = $entry['sensorProbeTempHighCritical'];
     $divisor = 1;
     $multiplier = 1;
     if ($entry['sensorProbeTempDegreeType'] == 'fahr') {
         $divisor = 9;
         $multiplier = 5;
         foreach (array('value', 'low_limit', 'low_warn_limit', 'warn_limit', 'limit') as $param) {
             ${$param} = f2c(${$param});
             // Convert from fahrenheit to celsius
         }
         print_debug('TEMP sensor: Fahrenheit -> Celsius');
     }
     if ($entry['sensorProbeTempStatus'] != 'noStatus') {
         discover_sensor($valid['sensor'], 'temperature', $device, $oid, $index, 'akcp', $descr, $divisor, $multiplier, $low_limit, $low_warn_limit, $warn_limit, $limit, $value);
     }
 }
 if ($entry['sensorProbeHumidityStatus']) {
     # Humidity sensor
     # FIXME do we need to take note of this? [sensorProbeHumidityOffset] => 0
     $descr = $entry['sensorProbeHumidityDescription'];
     $oid = ".1.3.6.1.4.1.3854.1.2.2.1.17.1.3.{$index}";
     # SPAGENT-MIB:sensorProbeHumidityPercent.$index
     $value = $entry['sensorProbeHumidityPercent'];
示例#11
0
文件: vtec_obs.php 项目: raprasad/iem
    for ($j = 0; $row2 = @pg_fetch_assoc($rs2, $j); $j++) {
        if ($ostation != $row2["station"]) {
            if ($stfound > 0 && $stfound % 3 == 0) {
                $table .= "</td></tr>";
                $ostation = "";
            }
            if ($ostation == "") {
                $table .= "<tr><td valign='top'>";
            } else {
                $table .= "</td><td valign='top'>";
            }
            $ostation = $row2["station"];
            $stfound += 1;
            $table .= sprintf("<u>UGC Code: %s</u><br/>", $station2ugc[$row2["station"]]);
        }
        $table .= sprintf("%s %sZ %s/%.0f %s %s %s%s<br>", $row2["station"], $row2["z"], c4($row2["tmpf"]), $row2["dwpf"], c1(relh(f2c($row2["tmpf"]), f2c($row2["dwpf"]))), c3($row2["vsby"]), c2($row2["sknt"], $row2["gust"]), c5($row2["wcht"]));
    }
    $table .= "</td></tr></table>";
}
$t->content = <<<EOF
  <h2>NWS Watch/Warning/Advisory + ASOS Observations</h2>
  
  <p>This app allows you to view an office's warnings for a year and
  then looks for ASOS/AWOS observations valid for the warning period. The observations
  presented are coded like:
  <br />ID DDHHMI TMPF/DWPF RELH VSBY SKNT/GUST WC WINDCHILL
  <br />Where ID is the station identifier, DDHHMI is the day-hour-minute of the
  observation in UTC, TMPF is the air temperature in Fahrenheit, DWPF is the
  dew point temperature in Fahrenheit, RELH is the relative humidity, VSBY is
  the visibility, SKNT is the wind speed in knots and GUST is the wind gust in knots. 
  The wind chill is displayed when the temperature is below 32&deg;F.
function poll_sensor($device, $class, $unit, &$oid_cache)
{
    global $config, $agent_sensors, $ipmi_sensors, $graphs;
    $sql = "SELECT *, `sensors`.`sensor_id` AS `sensor_id`";
    $sql .= " FROM  `sensors`";
    $sql .= " LEFT JOIN  `sensors-state` ON  `sensors`.sensor_id =  `sensors-state`.sensor_id";
    $sql .= " WHERE `sensor_class` = ? AND `device_id` = ?";
    foreach (dbFetchRows($sql, array($class, $device['device_id'])) as $sensor_db) {
        $sensor_poll = array();
        if (OBS_DEBUG) {
            echo "检测中 (" . $sensor_db['poller_type'] . ") {$class} " . $sensor_db['sensor_descr'] . " ";
            print_r($sensor_db);
        }
        if ($sensor_db['poller_type'] == "snmp") {
            # if ($class == "temperature" && $device['os'] == "papouch")
            // Why all temperature?
            if ($class == "temperature") {
                for ($i = 0; $i < 5; $i++) {
                    // Take value from $oid_cache if we have it, else snmp_get it
                    if (is_numeric($oid_cache[$sensor_db['sensor_oid']])) {
                        print_debug("取值来自 oid_cache");
                        $sensor_poll['sensor_value'] = $oid_cache[$sensor_db['sensor_oid']];
                    } else {
                        $sensor_poll['sensor_value'] = snmp_fix_numeric(snmp_get($device, $sensor_db['sensor_oid'], "-OUqnv", "SNMPv2-MIB", mib_dirs()));
                    }
                    if (is_numeric($sensor_poll['sensor_value']) && $sensor_poll['sensor_value'] != 9999) {
                        break;
                    }
                    // Papouch TME sometimes sends 999.9 when it is right in the middle of an update;
                    sleep(1);
                    // Give the TME some time to reset
                }
                // If we received 999.9 degrees still, reset to Unknown.
                if ($sensor_poll['sensor_value'] == 9999) {
                    $sensor_poll['sensor_value'] = "U";
                }
            } else {
                if ($class == "runtime") {
                    if (isset($oid_cache[$sensor_db['sensor_oid']])) {
                        print_debug("value taken from oid_cache");
                        $sensor_poll['sensor_value'] = $oid_cache[$sensor_db['sensor_oid']];
                    } else {
                        $sensor_poll['sensor_value'] = snmp_get($device, $sensor_db['sensor_oid'], "-OUqnv", "SNMPv2-MIB", mib_dirs());
                    }
                    if (strpos($sensor_poll['sensor_value'], ':') !== FALSE) {
                        // Use timetick conversion only when snmpdata is formatted as timetick 0:0:21:00.00
                        $sensor_poll['sensor_value'] = timeticks_to_sec($sensor_poll['sensor_value']);
                    }
                } else {
                    // Take value from $oid_cache if we have it, else snmp_get it
                    if (is_numeric($oid_cache[$sensor_db['sensor_oid']])) {
                        print_debug("取值来自 oid_cache");
                        $sensor_poll['sensor_value'] = $oid_cache[$sensor_db['sensor_oid']];
                    } else {
                        $sensor_poll['sensor_value'] = snmp_fix_numeric(snmp_get($device, $sensor_db['sensor_oid'], "-OUqnv", "SNMPv2-MIB", mib_dirs()));
                    }
                }
            }
        } else {
            if ($sensor_db['poller_type'] == "agent") {
                if (isset($agent_sensors)) {
                    $sensor_poll['sensor_value'] = $agent_sensors[$class][$sensor_db['sensor_type']][$sensor_db['sensor_index']]['current'];
                    // FIXME pass unit?
                } else {
                    print_warning("传感器中的数据无可用的代理.");
                    continue;
                }
            } else {
                if ($sensor_db['poller_type'] == "ipmi") {
                    if (isset($ipmi_sensors)) {
                        $sensor_poll['sensor_value'] = $ipmi_sensors[$class][$sensor_db['sensor_type']][$sensor_db['sensor_index']]['current'];
                        $unit = $ipmi_sensors[$class][$sensor_db['sensor_type']][$sensor_db['sensor_index']]['unit'];
                    } else {
                        print_warning("IPMI传感器数据不可用.");
                        continue;
                    }
                } else {
                    print_warning("未知的系缆柱型传感器.");
                    continue;
                }
            }
        }
        if (OBS_DEBUG) {
            print_r($sensor_poll);
        }
        if ($sensor_poll['sensor_value'] == -32768) {
            print_debug("Invalid (-32768) ");
            $sensor_poll['sensor_value'] = 0;
        }
        /// FIXME. This is old pre 'scale' method, remove in r7000
        if (isset($sensor_db['sensor_divisor']) && $sensor_db['sensor_divisor'] > 1) {
            /// This is fix for r5351
            if ($sensor_db['sensor_multiplier'] >= 1) {
                $sensor_poll['sensor_value'] = $sensor_poll['sensor_value'] / $sensor_db['sensor_divisor'];
            }
        }
        if (isset($sensor_db['sensor_multiplier']) && $sensor_db['sensor_multiplier'] != 0) {
            $f2c = FALSE;
            if ($class == "temperature") {
                // This is weird hardcode for convert Fahrenheit to Celsius
                foreach (array(1, 0.1) as $scale_tmp) {
                    if (float_cmp($sensor_db['sensor_multiplier'], $scale_tmp * 5 / 9) === 0) {
                        $sensor_db['sensor_multiplier'] = $scale_tmp;
                        $f2c = TRUE;
                        break;
                    }
                }
            }
            $sensor_poll['sensor_value'] *= $sensor_db['sensor_multiplier'];
            if ($f2c) {
                $sensor_poll['sensor_value'] = f2c($sensor_poll['sensor_value']);
                print_debug('TEMPERATURE sensor: Fahrenheit -> Celsius');
            }
        }
        $rrd_file = get_sensor_rrd($device, $sensor_db);
        rrdtool_create($device, $rrd_file, "DS:sensor:GAUGE:600:-20000:U");
        echo $sensor_poll['sensor_value'] . "{$unit} ";
        // FIXME this block and the other block below it are kinda retarded. They should be merged and simplified.
        if ($sensor_poll['sensor_ignore'] || $sensor_poll['sensor_disable']) {
            $sensor_poll['sensor_event'] = 'ignore';
        } else {
            if ($sensor_db['sensor_limit_low_warn'] != '' && $sensor_poll['sensor_value'] < $sensor_db['sensor_limit_low_warn'] || $sensor_db['sensor_limit_warn'] != '' && $sensor_poll['sensor_value'] > $sensor_db['sensor_limit_warn']) {
                $sensor_poll['sensor_event'] = 'warning';
                $sensor_poll['sensor_status'] = 'Sensor warning thresholds exceeded.';
                // FIXME - be more specific
            } else {
                if (($sensor_db['sensor_limit_low'] != '' && $sensor_poll['sensor_value'] < $sensor_db['sensor_limit_low'] || $sensor_db['sensor_limit'] != '' && $sensor_poll['sensor_value'] > $sensor_db['sensor_limit']) && $sensor_db['sensor_value'] != '') {
                    $sensor_poll['sensor_event'] = 'alert';
                    $sensor_poll['sensor_status'] = 'Sensor critical thresholds exceeded.';
                    // FIXME - be more specific
                } else {
                    $sensor_poll['sensor_event'] = 'up';
                    $sensor_poll['sensor_status'] = '';
                    //if ($sensor_db['sensor_event'] != 'up' && $sensor_db['sensor_event'] != '')
                    //{
                    //  $sensor_poll['sensor_status'] = 'Sensor thresholds cleared.'; // FIXME - be more specific
                    //}
                }
            }
        }
        // FIXME I left the eventlog code for now, as soon as alerts send an entry to the eventlog this can go.
        if ($sensor_db['sensor_event'] != 'ignore') {
            if ($sensor_db['sensor_limit_low'] != "" && $sensor_db['sensor_value'] >= $sensor_db['sensor_limit_low'] && $sensor_poll['sensor_value'] < $sensor_db['sensor_limit_low']) {
                // If old value greater than low limit and new value less than low limit
                $msg = ucfirst($class) . " Alarm: " . $device['hostname'] . " " . $sensor_db['sensor_descr'] . " is under threshold: " . $sensor_poll['sensor_value'] . "{$unit} (< " . $sensor_db['sensor_limit_low'] . "{$unit})";
                log_event(ucfirst($class) . ' ' . $sensor_db['sensor_descr'] . " under threshold: " . $sensor_poll['sensor_value'] . " {$unit} (< " . $sensor_db['sensor_limit_low'] . " {$unit})", $device, 'sensor', $sensor_db['sensor_id'], 'warning');
            } else {
                if ($sensor_db['sensor_limit'] != "" && $sensor_db['sensor_value'] <= $sensor_db['sensor_limit'] && $sensor_poll['sensor_value'] > $sensor_db['sensor_limit']) {
                    // If old value less than high limit and new value greater than high limit
                    $msg = ucfirst($class) . " Alarm: " . $device['hostname'] . " " . $sensor_db['sensor_descr'] . " is over threshold: " . $sensor_poll['sensor_value'] . "{$unit} (> " . $sensor_db['sensor_limit'] . "{$unit})";
                    log_event(ucfirst($class) . ' ' . $sensor_db['sensor_descr'] . " above threshold: " . $sensor_poll['sensor_value'] . " {$unit} (> " . $sensor_db['sensor_limit'] . " {$unit})", $device, 'sensor', $sensor_db['sensor_id'], 'warning');
                }
            }
        } else {
            print_message("[%ySensor Ignored%n]", 'color');
        }
        echo PHP_EOL;
        // Send statistics array via AMQP/JSON if AMQP is enabled globally and for the ports module
        if ($config['amqp']['enable'] == TRUE && $config['amqp']['modules']['sensors']) {
            $json_data = array('value' => $sensor_poll['sensor_value']);
            messagebus_send(array('attribs' => array('t' => time(), 'device' => $device['hostname'], 'device_id' => $device['device_id'], 'e_type' => 'sensor', 'e_class' => $sensor_db['sensor_class'], 'e_type' => $sensor_db['sensor_type'], 'e_index' => $sensor_db['sensor_index']), 'data' => $json_data));
        }
        // Update StatsD/Carbon
        if ($config['statsd']['enable'] == TRUE) {
            StatsD::gauge(str_replace(".", "_", $device['hostname']) . '.' . 'sensor' . '.' . $sensor_db['sensor_class'] . '.' . $sensor_db['sensor_type'] . '.' . $sensor_db['sensor_index'], $sensor_poll['sensor_value']);
        }
        // Update RRD
        rrdtool_update($device, $rrd_file, "N:" . $sensor_poll['sensor_value']);
        // Enable graph
        $graphs[$sensor_db['sensor_class']] = TRUE;
        // Check alerts
        $metrics = array();
        $metrics['sensor_value'] = $sensor_poll['sensor_value'];
        $metrics['sensor_event'] = $sensor_poll['sensor_event'];
        $metrics['sensor_status'] = $sensor_poll['sensor_status'];
        check_entity('sensor', $sensor_db, $metrics);
        // Update SQL State
        if (is_numeric($sensor_db['sensor_polled'])) {
            dbUpdate(array('sensor_value' => $sensor_poll['sensor_value'], 'sensor_event' => $sensor_poll['sensor_event'], 'sensor_status' => $sensor_poll['sensor_status'], 'sensor_polled' => time()), 'sensors-state', '`sensor_id` = ?', array($sensor_db['sensor_id']));
        } else {
            dbInsert(array('sensor_id' => $sensor_db['sensor_id'], 'sensor_value' => $sensor_poll['sensor_value'], 'sensor_event' => $sensor_poll['sensor_event'], 'sensor_status' => $sensor_poll['sensor_status'], 'sensor_polled' => time()), 'sensors-state');
        }
    }
}
function discover_sensor(&$valid, $class, $device, $oid, $index, $type, $sensor_descr, $scale = 1, $current = NULL, $options = array(), $poller_type = 'snmp')
{
    global $config;
    // If this is actually a status indicator, pass it off to discover_status() then return.
    if ($class == 'state' || $class == 'status') {
        print_debug("Redirect call to discover_status().");
        $return = discover_status($device, $oid, $index, $type, $sensor_descr, $current, $options, $poller_type);
        return $return;
    }
    // Init main
    $param_main = array('oid' => 'sensor_oid', 'sensor_descr' => 'sensor_descr', 'scale' => 'sensor_multiplier');
    // Init numeric values
    if (!is_numeric($scale) || $scale == 0) {
        $scale = 1;
    }
    // Skip discovery sensor if value not numeric or null (default)
    if ($current !== NULL) {
        // Some retarded devices report data with spaces and commas
        // STRING: "  20,4"
        $current = snmp_fix_numeric($current);
    }
    if (is_numeric($current)) {
        $f2c = FALSE;
        if ($class == 'temperature') {
            // This is weird hardcode for convert Fahrenheit to Celsius
            foreach (array(1, 0.1) as $scale_f2c) {
                if (float_cmp($scale, $scale_f2c * 5 / 9) === 0) {
                    //$scale = $scale_tmp;
                    $f2c = TRUE;
                    break;
                }
            }
        }
        if ($f2c) {
            $current = f2c($current * $scale_f2c);
            print_debug('TEMPERATURE sensor: Fahrenheit -> Celsius');
        } else {
            $current *= $scale;
        }
    } else {
        if ($current !== NULL) {
            print_debug("Sensor skipped by not numeric value: {$current}, {$sensor_descr} ");
            return FALSE;
        }
    }
    $param_limits = array('limit_high' => 'sensor_limit', 'limit_high_warn' => 'sensor_limit_warn', 'limit_low' => 'sensor_limit_low', 'limit_low_warn' => 'sensor_limit_low_warn');
    foreach ($param_limits as $key => $column) {
        ${$key} = is_numeric($options[$key]) ? $options[$key] : NULL;
    }
    // Init optional
    $param_opt = array('entPhysicalIndex', 'entPhysicalClass', 'entPhysicalIndex_measured', 'measured_class', 'measured_entity');
    foreach ($param_opt as $key) {
        ${$key} = $options[$key] ? $options[$key] : NULL;
    }
    print_debug("发现传感器: {$class}, " . $device['hostname'] . ", {$oid}, {$index}, {$type}, {$sensor_descr}, SCALE: {$scale}, LIMITS: ({$limit_low}, {$limit_low_warn}, {$limit_high_warn}, {$limit_high}), CURRENT: {$current}, {$poller_type}, {$entPhysicalIndex}, {$entPhysicalClass}");
    // Check sensor ignore filters
    foreach ($config['ignore_sensor'] as $bi) {
        if (strcasecmp($bi, $sensor_descr) == 0) {
            print_debug("Skipped by equals: {$bi}, {$sensor_descr} ");
            return FALSE;
        }
    }
    foreach ($config['ignore_sensor_string'] as $bi) {
        if (stripos($sensor_descr, $bi) !== FALSE) {
            print_debug("Skipped by strpos: {$bi}, {$sensor_descr} ");
            return FALSE;
        }
    }
    foreach ($config['ignore_sensor_regexp'] as $bi) {
        if (preg_match($bi, $sensor_descr) > 0) {
            print_debug("Skipped by regexp: {$bi}, {$sensor_descr} ");
            return FALSE;
        }
    }
    if (!is_null($limit_low_warn) && !is_null($limit_high_warn) && $limit_low_warn > $limit_high_warn) {
        // Fix high/low thresholds (i.e. on negative numbers)
        list($limit_high_warn, $limit_low_warn) = array($limit_low_warn, $limit_high_warn);
    }
    if (dbFetchCell('SELECT COUNT(`sensor_id`) FROM `sensors`
                   WHERE `poller_type`= ? AND `sensor_class` = ? AND `device_id` = ? AND `sensor_type` = ? AND `sensor_index` = ?', array($poller_type, $class, $device['device_id'], $type, $index)) == '0') {
        if (!$limit_high) {
            $limit_high = sensor_limit_high($class, $current);
        }
        if (!$limit_low) {
            $limit_low = sensor_limit_low($class, $current);
        }
        if (!is_null($limit_low) && !is_null($limit_high) && $limit_low > $limit_high) {
            // Fix high/low thresholds (i.e. on negative numbers)
            list($limit_high, $limit_low) = array($limit_low, $limit_high);
            print_debug("High/low limits swapped.");
        }
        $sensor_insert = array('poller_type' => $poller_type, 'sensor_class' => $class, 'device_id' => $device['device_id'], 'sensor_index' => $index, 'sensor_type' => $type);
        foreach ($param_main as $key => $column) {
            $sensor_insert[$column] = ${$key};
        }
        foreach ($param_limits as $key => $column) {
            // Convert strings/numbers to (float) or to array('NULL')
            ${$key} = ${$key} === NULL ? array('NULL') : (double) ${$key};
            $sensor_insert[$column] = ${$key};
        }
        foreach ($param_opt as $key) {
            if (is_null(${$key})) {
                ${$key} = array('NULL');
            }
            $sensor_insert[$key] = ${$key};
        }
        $sensor_id = dbInsert($sensor_insert, 'sensors');
        $state_insert = array('sensor_id' => $sensor_id, 'sensor_value' => $current, 'sensor_polled' => 'NOW()');
        dbInsert($state_insert, 'sensors-state');
        print_debug("( {$sensor_id} inserted )");
        echo "+";
        if ($poller_type != 'ipmi') {
            // Suppress events for IPMI, see: http://jira.observium.org/browse/OBSERVIUM-959
            log_event("传感器已添加: {$class} {$type} {$index} {$sensor_descr}", $device, 'sensor', $sensor_id);
        }
    } else {
        $sensor_entry = dbFetchRow("SELECT * FROM `sensors` WHERE `sensor_class` = ? AND `device_id` = ? AND `sensor_type` = ? AND `sensor_index` = ?", array($class, $device['device_id'], $type, $index));
        // Limits
        if (!$sensor_entry['sensor_custom_limit']) {
            if (!is_numeric($limit_high) && !is_numeric($limit_low)) {
                if ($sensor_entry['sensor_limit'] !== '') {
                    // Calculate a reasonable limit
                    $limit_high = sensor_limit_high($class, $current);
                } else {
                    // Use existing limit. (this is wrong! --mike)
                    $limit_high = $sensor_entry['sensor_limit'];
                }
                if ($sensor_entry['sensor_limit_low'] !== '') {
                    // Calculate a reasonable limit
                    $limit_low = sensor_limit_low($class, $current);
                } else {
                    // Use existing limit. (this is wrong! --mike)
                    $limit_low = $sensor_entry['sensor_limit_low'];
                }
            }
            // Fix high/low thresholds (i.e. on negative numbers)
            if (!is_null($limit_low) && !is_null($limit_high) && $limit_low > $limit_high) {
                list($limit_high, $limit_low) = array($limit_low, $limit_high);
                print_debug("High/low limits swapped.");
            }
            // Update limits
            $update = array();
            $update_msg = array();
            $debug_msg = 'Current sensor value: "' . $current . '", scale: "' . $scale . '"' . PHP_EOL;
            foreach ($param_limits as $key => $column) {
                // $key - param name, $$key - param value, $column - column name in DB for $key
                $debug_msg .= '  ' . $key . ': "' . $sensor_entry[$column] . '" -> "' . ${$key} . '"' . PHP_EOL;
                //convert strings/numbers to identical type (float) or to array('NULL') for correct comparison
                ${$key} = ${$key} === NULL ? array('NULL') : (double) ${$key};
                $sensor_entry[$column] = $sensor_entry[$column] === NULL ? array('NULL') : (double) $sensor_entry[$column];
                if (float_cmp(${$key}, $sensor_entry[$column], 0.1) !== 0) {
                    $update[$column] = ${$key};
                    $update_msg[] = $key . ' -> "' . (is_array(${$key}) ? 'NULL' : ${$key}) . '"';
                }
            }
            if (count($update)) {
                echo "L";
                print_debug($debug_msg);
                log_event('传感器已更新(限制): ' . implode(', ', $update_msg), $device, 'sensor', $sensor_entry['sensor_id']);
                $updated = dbUpdate($update, 'sensors', '`sensor_id` = ?', array($sensor_entry['sensor_id']));
            }
        }
        $update = array();
        foreach ($param_main as $key => $column) {
            if (float_cmp(${$key}, $sensor_entry[$column]) !== 0) {
                $update[$column] = ${$key};
            }
        }
        foreach ($param_opt as $key) {
            if (${$key} != $sensor_entry[$key]) {
                $update[$key] = ${$key};
            }
        }
        if (count($update)) {
            $updated = dbUpdate($update, 'sensors', '`sensor_id` = ?', array($sensor_entry['sensor_id']));
            echo "U";
            log_event("传感器已更新: {$class} {$type} {$index} {$sensor_descr}", $device, 'sensor', $sensor_entry['sensor_id']);
        } else {
            echo ".";
        }
    }
    $valid[$class][$type][$index] = 1;
}
示例#14
0
system($cmd);
unlink("/tmp/wxc_ildot.txt");
// ------------------------------------------------
pg_close($nt->dbconn);
$nt = new NetworkTable(array("OH_RWIS", "IN_RWIS", "KY_RWIS"));
$cities = $nt->table;
$mydata = $iem->getNetwork(array("OH_RWIS", "IN_RWIS", "KY_RWIS"));
$rwis = fopen('/tmp/wxc_oh_in_kydot.txt', 'w');
$rwiscsv = fopen('/tmp/csv_oh_in_kydot.txt', 'w');
fwrite($rwis, "Weather Central 001d0300 Surface Data TimeStamp={$tstamp}\n  22\n   6 Station\n  52 CityName\n   2 State\n   7 Lat\n   8 Lon\n   2 Day\n   4 Hour\n   5 AirTemp\n   5 AirDewp\n   4 Wind Direction Degrees\n   4 Wind Direction Text\n   5 Wind Speed\n   5 SubSurface Temp\n   5 P1 Temp\n   5 P2 Temp\n   5 P3 Temp\n   5 P4 Temp\n   5 Pave Ave Temp\n   5 Wind Chill F\n   5 Heat Index F\n   5 Today High Temp F\n   5 Today Low Temp F\n");
fwrite($rwiscsv, "station,cityname,state,lat,lon,day,hour,airtemp,airdewp," . "drct,drcttxt,sped,subsurfacetemp,p1temp,p2temp,p3temp,p4temp," . "pavetemp,wcht,hidx,today_high,today_low\n");
$now = time();
while (list($key, $val) = each($mydata)) {
    $tdiff = $now - $val->db["ts"];
    // Heat index
    $relh = relh(f2c($val->db['tmpf']), f2c($val->db['dwpf']));
    $val->db["heat"] = round(heat_idx($val->db['tmpf'], $relh), 1);
    $val->db["wcht"] = round(wcht_idx($val->db['tmpf'], $val->db['sknt'] * 1.15), 1);
    if ($val->db['dwpf'] < -99.0) {
        $val->db['dwpf'] = 'M';
        $val->db['heat'] = 'M';
    } else {
        $val->db['dwpf'] = round($val->db['dwpf'], 1);
    }
    if ($val->db['tmpf'] < -99.0) {
        $val->db['tmpf'] = 'M';
        $val->db['heat'] = 'M';
        $val->db['wcht'] = 'M';
    } else {
        $val->db['tmpf'] = round($val->db['tmpf'], 1);
    }