我的毕业论文的一部分是创建 web 界面来通过 SNMP 命令控制设备。所以我创建了自己的 SNMP 类抽象级别
<?php
class snmp_lib {
private $snmpInstance;
private $VERSION = SNMP::VERSION_1;
private $HOST = '192.168.0.150';
private $passwordRead = '000000000000';
private $passwordWrite = 'private';
private $releys = array(1 => '1.3.6.1.4.1.19865.1.2.1.1.0',
2 => '1.3.6.1.4.1.19865.1.2.1.2.0');
private $allPorts = array('3' => '1.3.6.1.4.1.19865.1.2.1.33.0',
'5' => '1.3.6.1.4.1.19865.1.2.2.33.0');
public function __construct($action) {
if (in_array($action, array('read', 'write'))) {
if (strcmp($action, 'read') === 0) {
$this->_read();
} else {
$this->_write();
}
}
}
private function _read() {
$this->snmpInstance = new SNMP($this->VERSION, $this->HOST, $this->passwordRead);
}
private function _write() {
$this->snmpInstance = new SNMP($this->VERSION, $this->HOST, $this->passwordWrite);
}
public function closeSession() {
return $this->snmpInstance->close();
}
public function activate($relay) {
$this->snmpInstance->set($this->releys[$relay], 'i', '1');
}
public function deactivate($relay) {
$this->snmpInstance->set($this->releys[$relay], 'i', '0');
}
public function getAllPortsStatus() {
$allPins = array();
foreach ($this->allPorts as $number => $port) {
$getbits = $this->snmpInstance->get($port);
$bits = str_replace('INTEGER: ', '', $getbits);
$pinsStatus = $this->_getActivePins($bits);
$allPins[$number] = $pinsStatus;
}
return $allPins;
}
private function _getActivePins($bits) {
$bitMapping = array(
1 => 1,
2 => 2,
3 => 4,
4 => 8,
5 => 16,
6 => 32,
7 => 64,
8 => 128
);
$pinsStatus = array();
foreach ($bitMapping as $int => $bit) {
if (($bits & $bit) == $bit) {
$pinsStatus[$int] = true;
continue;
}
$pinsStatus[$int] = false;
}
return $pinsStatus;
}
}
?>
我有一个接收 SNMP 请求并向继电器发送命令的模块。以下是一些使用此库的示例脚本
打开脚本
<?php
require_once 'snmp_lib.php';
$snmp = new snmp_lib('write');
$snmp->activate($getRelayNumber);
$snmp->closeSession();
?>
关闭脚本
<?php
require_once 'snmp_lib.php';
$snmp = new snmp_lib('write');
$snmp->deactivate($getRelayNumber);
$snmp->closeSession();
?>
获取所有端口状态的脚本
<?php
require_once 'snmp_lib.php';
$snmp = new snmp_lib('read');
$getActive = $snmp->getAllPortsStatus();
?>