Using IceStorm

IceStorm主题发布与订阅

// Topic Interface file
struct Measurement {
string tower; // tower id
float windSpeed; // knots
short windDirection; // degrees
float temperature; // degrees Celsius
};
interface Monitor {
void report(Measurement m);
};
// Implementing a Publisher
The implementation of our collector application can be summarized easily:
1. Obtain a proxy for the TopicManager. This is the primary IceStorm object,
used by both publishers and subscribers.
2. Obtain a proxy for the Weather topic, either by creating the topic if it does
not exist, or retrieving the proxy for the existing topic.
3. Obtain a proxy for the Weather topic’s “publisher object.” This proxy is
provided for the purpose of publishing messages, and therefore is narrowed to
the topic interface (Monitor).
4. Collect and report measurements.
////////////////////////////////
#include <Ice/Ice.h>
#include <IceStorm/IceStorm.h>
#include <Monitor.h>
int main(int argc, char* argv[])
{
...
// Note that this example assumes that IceStorm uses the instance name IceStorm.
// The actual instance name may differ.
// instance name Specifies an alternate identity category for the IceStorm topic manager object. If
// defined, the identity of the object becomes name/TopicManager. If not specified,
// the default identity category is IceStorm.
Ice::ObjectPrx obj = communicator->stringToProxy(
"IceStorm/TopicManager:tcp -p 9999");

IceStorm::TopicManagerPrx topicManager =
IceStorm::TopicManagerPrx::checkedCast(obj);
IceStorm::TopicPrx topic;
try {
topic = topicManager->retrieve("Weather");
}
catch (const IceStorm::NoSuchTopic&) {
topic = topicManager->create("Weather");
}
Ice::ObjectPrx pub = topic->getPublisher()->ice_oneway();
MonitorPrx monitor = MonitorPrx::uncheckedCast(pub);
while (true) {
Measurement m = getMeasurement();
monitor->report(m);
}
...
}
// Using a Publisher Object
Type Safety
IceStorm places the burden on the developer to ensure that publishers and
subscribers are using it correctly.
Oneway or Twoway?
IceStorm messages have oneway semantics (see Section 41.3.3), but publishers
may use either oneway or twoway invocations when sending messages to the
publisher object.
The differences between the invocation styles affect a publisher in four ways:
1) Efficiency
Oneway invocations have the advantage in efficiency
2) Ordering
If ordering is important, use twoway invocations with a reliability QoS of ordered, or use a single thread in the subscriber
3) Reliability
If the loss of messages is unacceptable, or you are unable to address the potential causes of
lost oneway messages, then twoway invocations are recommended.
4) Delays
Twoway invocations are more susceptible to these delays than oneway invocations.
Transports
Each publisher can select its own transport for message delivery, therefore the
transport used by a publisher to communicate with IceStorm has no effect on how
IceStorm delivers messages to its subscribers.
Request Contexts
A request context is an optional argument of all remote invocations (see Section 28.11). If a publisher supplies a request context when publishing a
message, IceStorm will forward it intact to subscribers.
 
Ice::ObjectPrx pub = topic->getPublisher();
Ice::Context ctx;
ctx["_fwd"] = "Oz";
MonitorPrx monitor =
MonitorPrx::uncheckedCast(pub->ice_context(ctx));
// Implementing a Subscriber
Our subscriber implementation takes the following steps:
1. Obtain a proxy for the TopicManager. This is the primary IceStorm object,
used by both publishers and subscribers.
2. Create an object adapter to host our Monitor servant.
3. Instantiate the Monitor servant and activate it with the object adapter.
4. Subscribe to the Weather topic.
5. Process report messages until shutdown.
6. Unsubscribe from the Weather topic.
/////////////////////////////////////
#include <Ice/Ice.h>
#include <IceStorm/IceStorm.h>
#include <Monitor.h>
using namespace std;
class MonitorI : virtual public Monitor {
public:
virtual void report(const Measurement& m,
const Ice::Current&) {
cout << "Measurement report:" << endl
<< " Tower: " << m.tower << endl
<< " W Spd: " << m.windSpeed << endl
<< " W Dir: " << m.windDirection << endl
<< " Temp: " << m.temperature << endl
<< endl;
}
};
/////////////////////////////////////////
int main(int argc, char* argv[])
{
...
Ice::ObjectPrx obj = communicator->stringToProxy(
"IceStorm/TopicManager:tcp -p 9999");
IceStorm::TopicManagerPrx topicManager =
IceStorm::TopicManagerPrx::checkedCast(obj);
Ice::ObjectAdapterPtr adapter =
communicator->createObjectAdapter("MonitorAdapter");
MonitorPtr monitor = new MonitorI;
Ice::ObjectPrx proxy = adapter->
addWithUUID(monitor)->ice_oneway();
IceStorm::TopicPrx topic;
try {
topic = topicManager->retrieve("Weather");
IceStorm::QoS qos;
topic->subscribeAndGetPublisher(qos, proxy);
}
catch (const IceStorm::NoSuchTopic&) {
// Error! No topic found!
...
}
adapter->activate();
communicator->waitForShutdown();
topic->unsubscribe(proxy);
...
}
using Baosight.SIS.Core.Communication; using Ice; using IceStorm; using System; using System.Collections.Generic; using System.Net.NetworkInformation; using System.Threading; namespace Baosight.SIS.Core.Common { class TmpWarp { public SISCameraServiceContractExPrx sendway = null; public SISCameraContractExPrx twowayR = null; public int CameraId; }; /// <summary> /// 实时图像通信服务(多适配器) /// </summary> public class LiveImageServiceMultiAdapter { /// <summary> /// 实时图像通信服务构造函数 /// </summary> /// <param name="iceStormServerIp">广播服务IP</param> /// <param name="iceStormServerPort">广播服务端口</param> /// <param name="terminalAdapterPort">适配器端口</param> public LiveImageServiceMultiAdapter(string iceStormServerIp, int iceStormServerPort, int terminalAdapterPort) { //初始化主题,服务,适配器 _Config_SysPara_NetworkParam_IceStormServer = iceStormServerIp; _Config_SysPara_NetworkParam_IceStormServerPort = iceStormServerPort.ToString(); _Config_SysPara_NetworkParam_TerminalAdapterPort = terminalAdapterPort.ToString(); } #region Members and properties. private string _Config_LocalMachineName = "LocalMachineName"; private string _Config_SysPara_NetworkParam_IceStormServer = "192.168.100.1"; private string _Config_SysPara_NetworkParam_IceStormServerPort = "10000"; private string _Config_SysPara_NetworkParam_TerminalAdapterPort = "10003"; private InitializationData _InitializationData = new InitializationData(); private string _Config; private Communicator _IceCommunicator = null; private TopicManagerPrx _TopicManager = null; private Dictionary<string, Ice.ObjectPrx> _Topics = new Dictionary<string,ObjectPrx>(); private Dictionary<string, Ice.Object> _Serants = new Dictionary<string,Ice.Object>(); private Dictionary<string, ObjectAdapter> _Adapters = new Dictionary<string,ObjectAdapter>(); private Dictionary<string, TmpWarp> _Contracts = new Dictionary<string, TmpWarp>(); private ObjectAdapter _DefaultAdapter = null; private const int c_TimeOut = 100; // ms private bool _IsServiceOK = false; private bool _IsConnecting = false; public bool IsServiceOK { get { return _IsServiceOK; } } public bool IsConnecting { get { return _IsConnecting; } } public Communicator IceCommunicator { get { return _IceCommunicator; } } public ObjectAdapter DefaultAdapter { get { return _DefaultAdapter; } } #endregion #region Private methods. /// <summary> /// 创建主题管理 /// </summary> /// <param name="data"></param> /// <returns></returns> private bool CreateTopicManager(InitializationData data) { try { string s = data.properties.getProperty("IceStorm.TopicManager.Proxy"); s = s.Replace("$IceStormIp", _Config_SysPara_NetworkParam_IceStormServer); s = s.Replace("$IceStormPort", _Config_SysPara_NetworkParam_IceStormServerPort); _TopicManager = IceStorm.TopicManagerPrxHelper.checkedCast(_IceCommunicator.stringToProxy(s)); return true; } catch (Ice.Exception ex) { Console.WriteLine("CreateTopicManager Error"); Console.WriteLine(ex.Message); Console.WriteLine("------------------------------------------------------------------"); _TopicManager = null; return false; } } /// <summary> /// 创建默认适配器 /// </summary> /// <param name="data"></param> /// <returns></returns> private bool CreateDefaultAdapter(InitializationData data) { try { string s = data.properties.getProperty("DefaultAdapter.Endpoints"); s = s.Replace("$Port", _Config_SysPara_NetworkParam_TerminalAdapterPort); _DefaultAdapter = _IceCommunicator.createObjectAdapterWithEndpoints("Default Adpater", s); _DefaultAdapter.activate(); return true; } catch (Ice.Exception ex) { //LogHelper.WriteError(ex.ToString()); _DefaultAdapter = null; return false; } } private ObjectAdapter CreateObjectAdapter(int adapterPort) { try { string name = String.Format("Adapter_{0}", adapterPort.ToString()); string endPoint = String.Format("tcp -p {0}", adapterPort.ToString()); ObjectAdapter adapter = _IceCommunicator.createObjectAdapterWithEndpoints(name, endPoint); adapter.activate(); return adapter; } catch (Ice.Exception ex) { Console.WriteLine("CreateObjectAdapter Error"); Console.WriteLine(ex.Message); Console.WriteLine("------------------------------------------------------------------"); return null; } } #endregion #region Firen private bool _DefaultAdapterInied = false; private void ConnectEx() { try { Ping p = new Ping(); if (p.Send(_Config_SysPara_NetworkParam_IceStormServer, c_TimeOut).Status != IPStatus.Success) { this._IsServiceOK = false; this._IsConnecting = false; return; } } catch { this._IsServiceOK = false; this._IsConnecting = false; return; } bool tempResult1 = false; bool tempResult2 = false; try { _InitializationData.properties = Util.createProperties(); _InitializationData.properties.load(_Config); string[] args = { "" }; _IceCommunicator = Util.initialize(ref args, _InitializationData); } catch (Ice.Exception ex) { _IceCommunicator = null; _IsServiceOK = false; return; } if (!_DefaultAdapterInied) { // 创建Topic管理器 tempResult1 = CreateTopicManager(_InitializationData); // 创建默认的通讯适配器 tempResult2 = CreateDefaultAdapter(_InitializationData); _DefaultAdapterInied = true; } this._IsServiceOK = (tempResult1 & tempResult2); _IsConnecting = false; } public void DebugCameraEx_SingleCall(string cameraPcIp, int cameraPcPort, int cameraId, LiveImageContractEx liveImageContract, int adapterPort) { //连接相机 SISCameraServiceContractExPrx sendway = null;//代理:用于发送 try { string s = _InitializationData.properties.getProperty("LiveImageEx.Proxy"); s = s.Replace("$CameraPcIP", cameraPcIp); s = s.Replace("$CameraPcPort", cameraPcPort.ToString()); sendway = SISCameraServiceContractExPrxHelper.checkedCast(_IceCommunicator.stringToProxy(s).ice_twoway().ice_timeout(300).ice_secure(false)); } catch(Ice.Exception ex) { Console.WriteLine("连接:" + cameraPcIp + ":" + cameraPcPort + "失败!" + "\r\n" + ex.ToString()); return; } //请求实时图像 SISCameraContractExPrx twowayR = null; try { ObjectAdapter adapter = CreateObjectAdapter(adapterPort); if (adapter == null) { return; } _Adapters.Add(cameraPcIp, adapter); //发送数据 DebugCameraEventArgs args = new DebugCameraEventArgs(); args.Info.IsDebug = true; args.Info.CameraId = cameraId; args.Info.InfoType = DebugType.Image; twowayR = SISCameraContractExPrxHelper.uncheckedCast(adapter.createProxy(_IceCommunicator.stringToIdentity(cameraPcIp)).ice_timeout(500)); sendway.OnDebugCamera(twowayR, args); adapter.add(liveImageContract, _IceCommunicator.stringToIdentity(cameraPcIp)); _Serants.Add(cameraPcIp, liveImageContract); } catch(Ice.Exception ex) { Console.WriteLine("DebugCameraEx_SingleCall Error"); Console.WriteLine(ex.Message); Console.WriteLine("------------------------------------------------------------------"); } TmpWarp tmp = new TmpWarp(); tmp.sendway = sendway; tmp.twowayR = twowayR; tmp.CameraId = cameraId; _Contracts.Add(cameraPcIp, tmp); } public void StopDebugCamera(string cameraPcIp) { try { if (!_Contracts.ContainsKey(cameraPcIp)) return; TmpWarp tmp = _Contracts[cameraPcIp]; if (tmp.sendway != null) { //停止实时图请求 DebugCameraEventArgs args = new DebugCameraEventArgs(); args.Info.IsDebug = false; args.Info.CameraId = tmp.CameraId; args.Info.InfoType = DebugType.Image; tmp.sendway.OnDebugCamera(tmp.twowayR, args); } } catch(System.Exception ex) { } } #endregion #region Public methods. public void Start(string config) { _Config = config; _IsConnecting = true; ConnectEx(); } public void Terminate() { try { foreach (string topic in _Topics.Keys) { try { _TopicManager.retrieve(topic).unsubscribe(_Topics[topic]); } catch { } } _Topics.Clear(); _TopicManager = null; foreach (string s in _Serants.Keys) { try { _DefaultAdapter.remove(_IceCommunicator.stringToIdentity(s)); } catch { } } _Serants.Clear(); _DefaultAdapter.destroy(); _DefaultAdapter = null; } catch { } } public bool RemoveSubscription(string topic) { try { if (_Topics.ContainsKey(topic)) { if (_Topics[topic] != null) { _TopicManager.retrieve(topic).unsubscribe(_Topics[topic]); } } return true; } catch { return false; } } public bool AddSubscription(string topic, Ice.Object subscriber, string keyName) { //Create subscribers. try { Ice.Identity subId = new Ice.Identity(string.Format("{0} {1}", _Config_LocalMachineName, keyName), ""); Dictionary<string, string> qos = new Dictionary<string, string>(); Ice.ObjectPrx _objPrx = _DefaultAdapter.add(subscriber, subId); try { _TopicManager.retrieve(topic).subscribeAndGetPublisher(qos, _objPrx); } catch (IceStorm.NoSuchTopic) { _TopicManager.create(topic).subscribeAndGetPublisher(qos, _objPrx); } catch (IceStorm.AlreadySubscribed) { } _Topics.Add(topic, _objPrx); return true; } catch (Ice.Exception ex) { ////LogHelper.WriteError(String.Format("添加对<{0}>的订阅失败! {1}", topic, ex.ToString())); return false; } } public bool RemoveSerant(string id) { try { _DefaultAdapter.remove(_IceCommunicator.stringToIdentity(id)); _Serants.Remove(id); return true; } catch { return false; } } public ObjectPrx GetPublisher(string topic) { try { if (_TopicManager != null) { // // Retrieve the topic. // IceStorm.TopicPrx topicPrx; try { topicPrx = _TopicManager.retrieve(topic); } catch (IceStorm.NoSuchTopic) { try { topicPrx = _TopicManager.create(topic); } catch (IceStorm.TopicExists) { //LogHelper.WriteError("Subscribe TopicTerminal Error"); return null; } } // // Get the topic's publisher object, and create a Clock proxy with // the mode specified as an argument of this application. // Ice.ObjectPrx publisher = topicPrx.getPublisher(); return publisher; } else return null; } catch (Ice.Exception ex) { //LogHelper.WriteError(ex.ToString()); return null; } } #endregion } } 根据这个C#代码修改C++的接收OnCameraGrabArrived
最新发布
11-18
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值