在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進行設備發現,并獲取到設備的地址信息。