在C#中使用ONVIF进行设备发现的步骤如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
public class ONVIFDeviceDiscovery
{
public static List<string> DiscoverDevices()
{
List<string> devices = new List<string>();
// 创建UDP广播终结点
EndpointAddress discoveryEndPointAddress = new EndpointAddress("soap.udp://239.255.255.250:3702");
// 创建消息工厂
MessageFactory messageFactory = new MessageFactory();
// 创建消息版本
AddressingVersion addressingVersion = AddressingVersion.WSAddressing10;
// 创建消息头
MessageHeader unicastHeader = MessageHeader.CreateHeader("Unicast", "", "");
MessageHeader multicastHeader = MessageHeader.CreateHeader("Multicast", "", "");
// 创建绑定元素
BindingElement[] bindingElements = new BindingElement[2];
bindingElements[0] = new TextMessageEncodingBindingElement();
bindingElements[1] = new HttpTransportBindingElement();
// 创建自定义绑定
CustomBinding customBinding = new CustomBinding(bindingElements);
// 创建ChannelFactory
ChannelFactory<IDiscoveryProxy> factory = new ChannelFactory<IDiscoveryProxy>(customBinding, discoveryEndPointAddress);
// 创建Channel
IDiscoveryProxy proxy = factory.CreateChannel();
factory.Open();
// 发送消息
Message message = messageFactory.CreateMessage(addressingVersion, "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", multicastHeader, new DiscoveryMessage());
Message reply = proxy.Discover(message);
// 解析响应
if (reply != null)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reply.GetReaderAtBodyContents());
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("XAddrs");
foreach (XmlNode node in nodeList)
{
devices.Add(node.InnerText);
}
}
// 关闭通道和工厂
factory.Close();
return devices;
}
}
class Program
{
static void Main(string[] args)
{
List<string> devices = ONVIFDeviceDiscovery.DiscoverDevices();
foreach (string device in devices)
{
Console.WriteLine("Discovered device: " + device);
}
Console.ReadLine();
}
}
通过以上步骤,您可以在C#中使用ONVIF进行设备发现,并获取到设备的地址信息。