Skip to content

Commit

Permalink
1.代码结构优化,利用kotlin特性修改在方法体内添加可选参数。
Browse files Browse the repository at this point in the history
2.优化错误捕获机制,不漏下任何一个错误。
  • Loading branch information
sunze committed Apr 24, 2020
1 parent 0078b17 commit 9ff860a
Show file tree
Hide file tree
Showing 4 changed files with 113 additions and 86 deletions.
27 changes: 14 additions & 13 deletions app/src/main/java/com/wosika/smnp/demo/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package com.wosika.smnp.demo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.wosika.smnp.SnmpUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.concurrent.thread
Expand All @@ -19,29 +18,31 @@ class MainActivity : AppCompatActivity() {
text.clear()
setMessage("")
thread {
SnmpUtils.apply {
//调用发送
SnmpUtils.sendSNMP(
oidCmd = ".1.3.6.1.2.1.25.3.5.1.1"
, ipAddress = "169.254.198.16"
//设置版本 可选参数默认为2c
snmpVersion = SNMP_VERSION_2c
//设置超时时间 可选参数 默认为1000
timeoutMillisecond = 1000
, snmpVersion = SnmpUtils.SNMP_VERSION_2c
//设置超时时间 可选参数 默认为1000毫秒
, timeoutMillisecond = 1000
//设置重试次数 可选参数 默认为2次
retryCount = 2
, retryCount = 2
//设置团体名 可选参数 默认public
community = "public"
//设置监听器
, community = "public"
, //设置监听器 可选参数
responseListener = { responseState ->
//先判定是否成功,成功再去使用value
if (responseState.isSuccess) {
setMessage("成功~回调数据:${responseState.value}")
} else {
setMessage("失败~回调数据:${responseState.exception?.message}")
}
}
}
//调用发送
.sendSNMP(".1.3.6.1.2.1.25.3.5.1.1", "169.254.198.16")
)
}
//切记不要再使用start kotlin中语法糖thread{}会自动start
// .start()
//切记不要再使用start kotlin中语法糖thread{}会自动start
// .start()
}
}

Expand Down
6 changes: 3 additions & 3 deletions snmp/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ android {
defaultConfig {
minSdkVersion 16
targetSdkVersion 29
versionCode 2
versionName "1.0.1"
versionCode 3
versionName "1.0.2"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles 'consumer-rules.pro'
}



buildTypes {
release {
Expand Down
5 changes: 4 additions & 1 deletion snmp/src/main/java/com/wosika/smnp/ResponseState.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@ data class ResponseState(
val exception: SnmpException? = null
)

class SnmpException(errorMsg: String) : Exception(errorMsg)
class SnmpException : Exception {
constructor(message: String?) : super(message)
constructor(message: String?, cause: Throwable?) : super(message, cause)
}
161 changes: 92 additions & 69 deletions snmp/src/main/java/com/wosika/smnp/SnmpUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,101 +24,124 @@ object SnmpUtils {
const val SNMP_VERSION_2c = SnmpConstants.version2c
const val SNMP_VERSION_3 = SnmpConstants.version3

//团体名默认
//默认团体名
private const val SNMP_COMMUNITY = "public"

//默认的snmp 端口
private const val SNMP_PORT = 161

//版本默认为2c
var snmpVersion = SNMP_VERSION_2c
//默认重试次数
private const val DEFAULT_RETRY_COUNT = 2

//重试次数
var retryCount = 2
//默认超时时间 为1秒
private const val DEFAULT_TIMEOUT_MILLISECOND = 1000L

//超时毫秒值
var timeoutMillisecond = 1000L


//监听器
var responseListener: ((ResponseState) -> Unit)? = null

//团体
var community = SNMP_COMMUNITY

/**
*
* 用get的方式发送snmp指令
* @param oidCmd String oid命令字符串
* @param ipAddress String 访问ip地址
* @param port Int 端口号 默认 161
* @param ipAddress String 访问ip地址
* @param port Int 可选参数 端口号 默认 161
* @param snmpVersion Int 可选参数 版本 默认2c
* @param community String 可选参数 团体名 默认 public
* @param retryCount Int 可选参数 重试次数 默认2次
* @param timeoutMillisecond Long 可选参数 超时时间 默认 1000毫秒
* @param responseListener Function1<ResponseState, Unit>? 可选参数 回调函数 返回请求状态
*/
fun sendSNMP(oidCmd: String, ipAddress: String, port: Int = SNMP_PORT) {
// 创建传输映射并监听
val transport: TransportMapping<UdpAddress> = DefaultUdpTransportMapping()
transport.listen()
Log.d(TAG, "创建目标地址对象")
// 创建目标地址对象
val comtarget = CommunityTarget()
comtarget.community = OctetString(community)
comtarget.version = snmpVersion
Log.d(TAG, "-address: ${ipAddress} / $SNMP_PORT ")
comtarget.address = UdpAddress(InetAddress.getByName(ipAddress), port)
comtarget.retries = retryCount
comtarget.timeout = timeoutMillisecond;
Log.d(TAG, "创建PDU对象")
val pdu = PDU()
val oid = OID(oidCmd)
pdu.add(VariableBinding(oid))
pdu.type = PDU.GETNEXT
val snmp = Snmp(transport)
Log.d(TAG, "发送请求给代理");
// 发送PDU
val response = snmp.send(pdu, comtarget)
//流程代理响应
if (response != null) {
// 提取响应PDU(如果超时response为null)
val responsePDU = response.response
// 提取代理用于发送响应的地址:
val peerAddress: Address = response.peerAddress
Log.d(TAG, "peerAddress $peerAddress")
if (responsePDU != null) {
val errorStatus = responsePDU.errorStatus
val errorIndex = responsePDU.errorIndex
val errorStatusText = responsePDU.errorStatusText
if (errorStatus == PDU.noError) {
Log.d(TAG, "SNMP GET 返回的完整数据 " + responsePDU.variableBindings)
val variable: Variable = responsePDU.getVariable(oid)
val value = variable.toString()
responseListener?.invoke(ResponseState(true, value))
Log.d(TAG, "返回的字符串 $value")
fun sendSNMP(
oidCmd: String,
ipAddress: String,
port: Int = SNMP_PORT,
snmpVersion: Int = SNMP_VERSION_2c,
community: String = SNMP_COMMUNITY,
retryCount: Int = DEFAULT_RETRY_COUNT,
timeoutMillisecond: Long = DEFAULT_TIMEOUT_MILLISECOND,
responseListener: ((ResponseState) -> Unit)? = null
) {
var snmp: Snmp? = null
try {
// 创建传输映射并监听
val transport: TransportMapping<UdpAddress> = DefaultUdpTransportMapping()
transport.listen()
Log.d(TAG, "创建目标地址对象")
// 创建目标地址对象
val comtarget = CommunityTarget()
comtarget.community = OctetString(community)
comtarget.version = snmpVersion
Log.d(TAG, "-address: $ipAddress / $port ")
val inetAddress = InetAddress.getByName(ipAddress)
comtarget.address = UdpAddress(inetAddress, port)
comtarget.retries = retryCount
comtarget.timeout = timeoutMillisecond;
Log.d(TAG, "创建PDU对象")
val pdu = PDU()
val oid = OID(oidCmd)
pdu.add(VariableBinding(oid))
pdu.type = PDU.GETNEXT
snmp = Snmp(transport)
Log.d(TAG, "发送请求给代理");
// 发送PDU
val response = snmp.send(pdu, comtarget)
//流程代理响应
if (response != null) {
// 提取响应PDU(如果超时response为null)
val responsePDU = response.response
// 提取代理用于发送响应的地址:
val peerAddress: Address = response.peerAddress
Log.d(TAG, "peerAddress $peerAddress")
if (responsePDU != null) {
val errorStatus = responsePDU.errorStatus
val errorIndex = responsePDU.errorIndex
val errorStatusText = responsePDU.errorStatusText
if (errorStatus == PDU.noError) {
Log.d(TAG, "SNMP GET 返回的完整数据 " + responsePDU.variableBindings)
val variable: Variable = responsePDU.getVariable(oid)
val value = variable.toString()
responseListener?.invoke(ResponseState(true, value))
Log.d(TAG, "返回的字符串 $value")
} else {
Log.d(TAG, "Error: Request Failed")
Log.d(TAG, "Error Status = $errorStatus")
Log.d(TAG, "Error Index = $errorIndex")
Log.d(TAG, "Error Status Text = $errorStatusText")
val errorMessage =
"SNMP请求错误 Error Status = $errorStatus Error Index = $errorIndex Error Status Text = $errorStatusText"
responseListener?.invoke(
ResponseState(
false,
exception = SnmpException(errorMessage)
)
)
}
} else {
Log.d(TAG, "Error: Request Failed")
Log.d(TAG, "Error Status = $errorStatus")
Log.d(TAG, "Error Index = $errorIndex")
Log.d(TAG, "Error Status Text = $errorStatusText")
val errorMessage =
"SNMP请求错误 Error Status = $errorStatus Error Index = $errorIndex Error Status Text = $errorStatusText"
Log.d(TAG, "SNMP响应PDU为空")
responseListener?.invoke(
ResponseState(
false,
exception = SnmpException(errorMessage)
exception = SnmpException("SNMP响应PDU为空")
)
)
}
} else {
Log.d(TAG, "SNMP响应PDU为空")
Log.d(TAG, "SNMP请求超时")
responseListener?.invoke(
ResponseState(
false,
exception = SnmpException("SNMP响应PDU为空")
exception = SnmpException("SNMP请求超时")
)
)
}
} else {
Log.d(TAG, "SNMP请求超时")
responseListener?.invoke(ResponseState(false, exception = SnmpException("SNMP请求超时")))
} catch (e: Exception) {
e.fillInStackTrace()
responseListener?.invoke(
ResponseState(
false,
exception = SnmpException(e.javaClass.simpleName + (e.message ?: "未知异常"), e)
)
)
} finally {
//释放SNMP
snmp?.close()
}
snmp.close()
}
}

0 comments on commit 9ff860a

Please sign in to comment.