/// <summary> /// Stop this client from using the AllJoyn bus. /// </summary> internal void Stop() { if (null != this.Bus) { this.Bus.UnregisterBusListener(this.Listeners); } this.ProxyObject = null; this.Listeners = null; this.Bus = null; App.OutputLine("Client has been stopped."); }
public void AddMethodHandlerTest() { BusAttachment service = new BusAttachment("methodhandler", true, 4); MethodHandlerBusObject busObj = new MethodHandlerBusObject(service, "/handlertest"); service.Start(); service.ConnectAsync(connectSpec).AsTask().Wait(); SessionPortListener spl = new SessionPortListener(service); spl.AcceptSessionJoiner += new SessionPortListenerAcceptSessionJoinerHandler((ushort sessionPort, string joiner, SessionOpts opts) => { Assert.AreEqual(33, sessionPort); return true; }); service.RequestName("org.alljoyn.methodhandlertest", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE); service.BindSessionPort(33, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), spl); service.AdvertiseName("org.alljoyn.methodhandlertest", TransportMaskType.TRANSPORT_ANY); BusAttachment client = new BusAttachment("methodcaller", true, 4); BusListener bl = new BusListener(client); client.RegisterBusListener(bl); bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler( (string name, TransportMaskType transport, string namePrefix) => { foundMethodObjectName.Set(); }); client.Start(); client.ConnectAsync(connectSpec).AsTask().Wait(); client.FindAdvertisedName("org.alljoyn.methodhandlertest"); foundMethodObjectName.WaitOne(); Task<JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.methodhandlertest", 33, new SessionListener(client), new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionOpts[1], null).AsTask<JoinSessionResult>(); joinTask.Wait(); Assert.IsTrue(QStatus.ER_OK == joinTask.Result.Status); ProxyBusObject proxy = new ProxyBusObject(client, "org.alljoyn.methodhandlertest", "/handlertest", joinTask.Result.SessionId); Task<IntrospectRemoteObjectResult> introTask = proxy.IntrospectRemoteObjectAsync(null).AsTask<IntrospectRemoteObjectResult>(); introTask.Wait(); Assert.IsTrue(QStatus.ER_OK == introTask.Result.Status); MsgArg[] args1 = new MsgArg[2]; args1[0] = new MsgArg("s", new object[] { "one" }); args1[1] = new MsgArg("s", new object[] { "two" }); Task<MethodCallResult> catTask = proxy.MethodCallAsync(service.GetInterface("org.alljoyn.methodhandler").GetMethod("cat"), args1, null, 60000, (byte)0).AsTask<MethodCallResult>(); catTask.Wait(); Assert.IsTrue(AllJoynMessageType.MESSAGE_METHOD_RET == catTask.Result.Message.Type); Assert.AreEqual("onetwo", catTask.Result.Message.GetArg(0).Value.ToString()); // Check BUGBUG above //MsgArg[] args2 = new MsgArg[1]; //args2[0] = new MsgArg("s", new object[] { "hello" }); //Task<MethodCallResult> sayHiTask = proxy.MethodCallAsync(service.GetInterface("org.alljoyn.methodhandler").GetMethod("sayhi"), // args2, null, 60000, (byte)0).AsTask<MethodCallResult>(); //sayHiTask.Wait(); //Assert.IsTrue(AllJoynMessageType.MESSAGE_METHOD_RET == sayHiTask.Result.Message.Type); //Assert.AreEqual("aloha", sayHiTask.Result.Message.GetArg(0).Value.ToString()); // TODO: add another method call that test function with signature MethodReply(AllJoyn.Message msg, string error, string errorMessage) }
/// <summary> /// Run the client stress op which stresses the bus attachment in a client type /// configuration which find the well-known service name and calls the 'cat' /// method /// </summary> /// <param name="isMultipoint">True if operation uses multipoint sessions</param> private void RunClient(bool isMultipoint) { try { ClientBusListener clientBusListener = new ClientBusListener(this.busAtt, this, this.foundName); this.busAtt.FindAdvertisedName(ServiceName); this.DebugPrint("Looking for WKN : " + ServiceName); this.foundName.WaitOne(12000); SessionOpts optsIn = new SessionOpts( TrafficType.TRAFFIC_MESSAGES, isMultipoint, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); SessionOpts[] optsOut = new SessionOpts[1]; Task<JoinSessionResult> joinTask = this.busAtt.JoinSessionAsync( this.DiscoveredName, ServicePort, (SessionListener)clientBusListener, optsIn, optsOut, null).AsTask<JoinSessionResult>(); joinTask.Wait(); JoinSessionResult joinResult = joinTask.Result; QStatus status = joinResult.Status; ProxyBusObject proxyBusObj = null; if (QStatus.ER_OK == status) { this.DebugPrint("JoinSession with " + this.DiscoveredName + " was successful (sessionId=" + joinResult.SessionId + ")"); proxyBusObj = new ProxyBusObject(this.busAtt, this.DiscoveredName, ServicePath, joinResult.SessionId); Task<IntrospectRemoteObjectResult> introTask = proxyBusObj.IntrospectRemoteObjectAsync(null).AsTask<IntrospectRemoteObjectResult>(); introTask.Wait(); IntrospectRemoteObjectResult introResult = introTask.Result; status = introResult.Status; if (QStatus.ER_OK == status) { this.DebugPrint("Introspection of the service was successfull"); MsgArg hello = new MsgArg("s", new object[] { "Hello " }); MsgArg world = new MsgArg("s", new object[] { "World!" }); InterfaceMember catMethod = proxyBusObj.GetInterface(InterfaceName).GetMethod("cat"); byte flags = (byte)0; Task<MethodCallResult> catTask = proxyBusObj.MethodCallAsync(catMethod, new MsgArg[] { hello, world }, null, 5000, flags).AsTask<MethodCallResult>(); catTask.Wait(); MethodCallResult catResult = catTask.Result; if (catResult.Message.Type == AllJoynMessageType.MESSAGE_METHOD_RET) { this.DebugPrint(this.DiscoveredName + ".cat ( path=" + ServicePath + ") returned \"" + catResult.Message.GetArg(0).Value.ToString() + "\""); } else { this.DebugPrint("Method call on " + this.DiscoveredName + ".cat failed (ReturnType=" + catResult.Message.Type.ToString() + ")"); } } else { this.DebugPrint("Introspection was unsuccessful: " + status.ToString()); } } else { this.DebugPrint("Join Session was unsuccessful: " + status.ToString()); } this.busAtt.CancelFindAdvertisedName(ServiceName); this.busAtt.UnregisterBusListener(clientBusListener); this.DebugPrint("Successfully unraveled the client operation"); } catch (ArgumentNullException ex) { this.DebugPrint(">>>> TIMEOUT, Client could not find WKN >>>>"); } catch (Exception ex) { var errMsg = AllJoynException.GetErrorMessage(ex.HResult); this.DebugPrint(">>>> Client Execution Error >>>> " + errMsg); } }
public void AddMethodHandlerTest() { BusAttachment service = new BusAttachment("methodhandler", true, 4); MethodHandlerBusObject busObj = new MethodHandlerBusObject(service, "/handlertest"); service.Start(); service.ConnectAsync(connectSpec).AsTask().Wait(); SessionPortListener spl = new SessionPortListener(service); spl.AcceptSessionJoiner += new SessionPortListenerAcceptSessionJoinerHandler((ushort sessionPort, string joiner, SessionOpts opts) => { Assert.AreEqual(33, sessionPort); return(true); }); service.RequestName("org.alljoyn.methodhandlertest", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE); service.BindSessionPort(33, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), spl); service.AdvertiseName("org.alljoyn.methodhandlertest", TransportMaskType.TRANSPORT_ANY); BusAttachment client = new BusAttachment("methodcaller", true, 4); BusListener bl = new BusListener(client); client.RegisterBusListener(bl); bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler( (string name, TransportMaskType transport, string namePrefix) => { foundMethodObjectName.Set(); }); client.Start(); client.ConnectAsync(connectSpec).AsTask().Wait(); client.FindAdvertisedName("org.alljoyn.methodhandlertest"); foundMethodObjectName.WaitOne(); Task <JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.methodhandlertest", 33, new SessionListener(client), new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionOpts[1], null).AsTask <JoinSessionResult>(); joinTask.Wait(); Assert.IsTrue(QStatus.ER_OK == joinTask.Result.Status); ProxyBusObject proxy = new ProxyBusObject(client, "org.alljoyn.methodhandlertest", "/handlertest", joinTask.Result.SessionId); Task <IntrospectRemoteObjectResult> introTask = proxy.IntrospectRemoteObjectAsync(null).AsTask <IntrospectRemoteObjectResult>(); introTask.Wait(); Assert.IsTrue(QStatus.ER_OK == introTask.Result.Status); MsgArg[] args1 = new MsgArg[2]; args1[0] = new MsgArg("s", new object[] { "one" }); args1[1] = new MsgArg("s", new object[] { "two" }); Task <MethodCallResult> catTask = proxy.MethodCallAsync(service.GetInterface("org.alljoyn.methodhandler").GetMethod("cat"), args1, null, 60000, (byte)0).AsTask <MethodCallResult>(); catTask.Wait(); Assert.IsTrue(AllJoynMessageType.MESSAGE_METHOD_RET == catTask.Result.Message.Type); Assert.AreEqual("onetwo", catTask.Result.Message.GetArg(0).Value.ToString()); // Check BUGBUG above //MsgArg[] args2 = new MsgArg[1]; //args2[0] = new MsgArg("s", new object[] { "hello" }); //Task<MethodCallResult> sayHiTask = proxy.MethodCallAsync(service.GetInterface("org.alljoyn.methodhandler").GetMethod("sayhi"), // args2, null, 60000, (byte)0).AsTask<MethodCallResult>(); //sayHiTask.Wait(); //Assert.IsTrue(AllJoynMessageType.MESSAGE_METHOD_RET == sayHiTask.Result.Message.Type); //Assert.AreEqual("aloha", sayHiTask.Result.Message.GetArg(0).Value.ToString()); // TODO: add another method call that test function with signature MethodReply(AllJoyn.Message msg, string error, string errorMessage) }
private async void Result_AboutAnnounced(object sender, AboutListener.AboutAnnouncedEventArgs e) { Log.WriteLine($"\tFrom bus :{e.BusName}"); Log.WriteLine($"\tAbout version {e.Version}"); Log.WriteLine($"\tSessionPort {e.Port}"); Log.WriteLine($"\tObjectDescription:"); foreach (var path in e.ObjectDescription.Paths) { Log.WriteLine($"\t\t{path}"); var interfaces = e.ObjectDescription.GetInterfaces(path); foreach (var i in interfaces) { Log.WriteLine($"\t\t\t" + i); } } Log.WriteLine($"\tAboutData:"); PrintAboutData(e.AboutData, null, 2); Log.WriteLine("*********************************************************************************"); var session = new Session(TrafficType.Messages, false, Proximity.Any, Transport.Any); clientBus.EnableConcurrentCallbacks(); var sessionId = clientBus.JoinSession(e.BusName, e.Port, null, session); if (sessionId != 0) { var aboutProxy = new AboutProxy(clientBus, e.BusName, sessionId); Log.WriteLine("*********************************************************************************"); Log.WriteLine("AboutProxy.GetObjectDescription:"); var aod2 = aboutProxy.ObjectDescription; foreach (var path in aod2.Paths) { Log.WriteLine($"\t\t{path}"); foreach (var i in aod2.GetInterfaces(path)) { Log.WriteLine($"\t\t\t{i}"); } } Log.WriteLine("*********************************************************************************"); Log.WriteLine("AboutProxy.GetAboutData: (Default Language)"); using ( var aboutData = aboutProxy.GetAboutData("en")) { PrintAboutData(aboutData, "en", 1); var langs = aboutData.SupportedLanguages; if (langs.Length > 1) { var dlang = aboutData.DefaultLanguage; foreach (var lang in langs) { if (lang == dlang) { continue; } using (var data = aboutProxy.GetAboutData(lang)) { PrintAboutData(data, lang, 1); } } } } Log.WriteLine("*********************************************************************************"); Log.WriteLine($"AboutProxy.GetVersion {aboutProxy.Version}"); Log.WriteLine("*********************************************************************************"); string[] paths = e.ObjectDescription.GetInterfacePaths(INTERFACE_NAME); var proxyObject = new ProxyBusObject(clientBus, e.BusName, paths[0], session); proxyObject.IntrospectRemoteObject(); var arg = new MsgArg("ECHO Echo echo...\n"); //var replyMsg = proxyObject.MethodCall(clientBus, INTERFACE_NAME, "Echo", arg, 1, TimeSpan.FromMilliseconds(25000)); var replyMsg = await proxyObject.MethodCallAsync(serviceBus, INTERFACE_NAME, "Echo", arg, 1, TimeSpan.FromMilliseconds(25000)); // var msg = replyMsg.GetArgument(0); Log.WriteLine($"Echo method reply: {ArgValueToString(msg)}"); } Log.WriteLine("*********************************************************************************"); }
/// <summary> /// Connects to the bus, finds the service and sets the 'name' property to the value /// specified by the user. /// </summary> /// <param name="sender">UI control which signaled the click event.</param> /// <param name="e">Arguments associated with the click event.</param> private void Button_RunNameChangeClient(object sender, RoutedEventArgs e) { if (this.TextBox_Input.Text == string.Empty) { this.OutputLine("You must provide an argument to run Name Change Client!"); } if (!runningClient && this.TextBox_Input.Text != string.Empty) { string newName = this.TextBox_Input.Text; Task task = new Task(async () => { try { runningClient = true; busAtt = new BusAttachment("NameChangeApp", true, 4); OutputLine("BusAttachment Created."); NameChangeBusListener busListener = new NameChangeBusListener(busAtt, foundNameEvent); busAtt.RegisterBusListener(busListener); OutputLine("BusListener Registered."); /* Create and register the bundled daemon. The client process connects to daemon over tcp connection */ busAtt.Start(); await busAtt.ConnectAsync(NameChangeGlobals.ConnectSpec); OutputLine("Bundled Daemon Registered."); OutputLine("BusAttachment Connected to " + NameChangeGlobals.ConnectSpec + "."); busAtt.FindAdvertisedName(NameChangeGlobals.WellKnownServiceName); foundNameEvent.WaitOne(); /* Configure session properties and request a session with device with wellKnownName */ SessionOpts sOpts = new SessionOpts( NameChangeGlobals.SessionProps.TrType, NameChangeGlobals.SessionProps.IsMultiPoint, NameChangeGlobals.SessionProps.PrType, NameChangeGlobals.SessionProps.TmType); SessionOpts[] sOptsOut = new SessionOpts[1]; JoinSessionResult joinResults = await busAtt.JoinSessionAsync( NameChangeGlobals.WellKnownServiceName, NameChangeGlobals.SessionProps.SessionPort, busListener, sOpts, sOptsOut, null); QStatus status = joinResults.Status; if (QStatus.ER_OK == status) { this.OutputLine("Join Session was successful (sessionId=" + joinResults.SessionId + ")."); } else { this.OutputLine("Join Session was unsuccessful."); } ProxyBusObject pbo = new ProxyBusObject(busAtt, NameChangeGlobals.WellKnownServiceName, NameChangeGlobals.ServicePath, sessionId); if (QStatus.ER_OK == status) { IntrospectRemoteObjectResult introResult = await pbo.IntrospectRemoteObjectAsync(null); status = introResult.Status; if (QStatus.ER_OK == status) { this.OutputLine("Introspection of the service object was successful."); } else { this.OutputLine("Introspection of the service object was unsuccessful."); } } if (QStatus.ER_OK == status) { object[] obj = new object[] { newName }; MsgArg msg = new MsgArg("s", obj); SetPropertyResult setResult = await pbo.SetPropertyAsync(NameChangeGlobals.InterfaceName, "name", msg, null, 2000); } TearDown(); } catch (Exception ex) { QStatus s = AllJoynException.GetErrorCode(ex.HResult); OutputLine("Error: " + ex.ToString()); runningClient = false; } }); task.Start(); } }
/// <summary> /// Connects to the bus, finds the service and sets the 'name' property to the value /// specified by the user. /// </summary> /// <param name="sender">UI control which signaled the click event.</param> /// <param name="e">Arguments associated with the click event.</param> private void Button_RunNameChangeClient(object sender, RoutedEventArgs e) { if (this.TextBox_Input.Text == string.Empty) { this.OutputLine("You must provide an argument to run Name Change Client!"); } if (!runningClient && this.TextBox_Input.Text != string.Empty) { string newName = this.TextBox_Input.Text; Task task = new Task(async() => { try { runningClient = true; busAtt = new BusAttachment("NameChangeApp", true, 4); OutputLine("BusAttachment Created."); NameChangeBusListener busListener = new NameChangeBusListener(busAtt, foundNameEvent); busAtt.RegisterBusListener(busListener); OutputLine("BusListener Registered."); /* Create and register the bundled daemon. The client process connects to daemon over tcp connection */ busAtt.Start(); await busAtt.ConnectAsync(NameChangeGlobals.ConnectSpec); OutputLine("Bundled Daemon Registered."); OutputLine("BusAttachment Connected to " + NameChangeGlobals.ConnectSpec + "."); busAtt.FindAdvertisedName(NameChangeGlobals.WellKnownServiceName); foundNameEvent.WaitOne(); /* Configure session properties and request a session with device with wellKnownName */ SessionOpts sOpts = new SessionOpts( NameChangeGlobals.SessionProps.TrType, NameChangeGlobals.SessionProps.IsMultiPoint, NameChangeGlobals.SessionProps.PrType, NameChangeGlobals.SessionProps.TmType); SessionOpts[] sOptsOut = new SessionOpts[1]; JoinSessionResult joinResults = await busAtt.JoinSessionAsync( NameChangeGlobals.WellKnownServiceName, NameChangeGlobals.SessionProps.SessionPort, busListener, sOpts, sOptsOut, null); QStatus status = joinResults.Status; if (QStatus.ER_OK == status) { this.OutputLine("Join Session was successful (sessionId=" + joinResults.SessionId + ")."); } else { this.OutputLine("Join Session was unsuccessful."); } ProxyBusObject pbo = new ProxyBusObject(busAtt, NameChangeGlobals.WellKnownServiceName, NameChangeGlobals.ServicePath, sessionId); if (QStatus.ER_OK == status) { IntrospectRemoteObjectResult introResult = await pbo.IntrospectRemoteObjectAsync(null); status = introResult.Status; if (QStatus.ER_OK == status) { this.OutputLine("Introspection of the service object was successful."); } else { this.OutputLine("Introspection of the service object was unsuccessful."); } } if (QStatus.ER_OK == status) { object[] obj = new object[] { newName }; MsgArg msg = new MsgArg("s", obj); SetPropertyResult setResult = await pbo.SetPropertyAsync(NameChangeGlobals.InterfaceName, "name", msg, null, 2000); } TearDown(); } catch (Exception ex) { QStatus s = AllJoynException.GetErrorCode(ex.HResult); OutputLine("Error: " + ex.ToString()); runningClient = false; } }); task.Start(); } }
/// <summary> /// Run the client stress op which stresses the bus attachment in a client type /// configuration which find the well-known service name and calls the 'cat' /// method /// </summary> /// <param name="isMultipoint">True if operation uses multipoint sessions</param> private void RunClient(bool isMultipoint) { try { ClientBusListener clientBusListener = new ClientBusListener(this.busAtt, this, this.foundName); this.busAtt.FindAdvertisedName(ServiceName); this.DebugPrint("Looking for WKN : " + ServiceName); this.foundName.WaitOne(12000); SessionOpts optsIn = new SessionOpts( TrafficType.TRAFFIC_MESSAGES, isMultipoint, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); SessionOpts[] optsOut = new SessionOpts[1]; Task <JoinSessionResult> joinTask = this.busAtt.JoinSessionAsync( this.DiscoveredName, ServicePort, (SessionListener)clientBusListener, optsIn, optsOut, null).AsTask <JoinSessionResult>(); joinTask.Wait(); JoinSessionResult joinResult = joinTask.Result; QStatus status = joinResult.Status; ProxyBusObject proxyBusObj = null; if (QStatus.ER_OK == status) { this.DebugPrint("JoinSession with " + this.DiscoveredName + " was successful (sessionId=" + joinResult.SessionId + ")"); proxyBusObj = new ProxyBusObject(this.busAtt, this.DiscoveredName, ServicePath, joinResult.SessionId); Task <IntrospectRemoteObjectResult> introTask = proxyBusObj.IntrospectRemoteObjectAsync(null).AsTask <IntrospectRemoteObjectResult>(); introTask.Wait(); IntrospectRemoteObjectResult introResult = introTask.Result; status = introResult.Status; if (QStatus.ER_OK == status) { this.DebugPrint("Introspection of the service was successfull"); MsgArg hello = new MsgArg("s", new object[] { "Hello " }); MsgArg world = new MsgArg("s", new object[] { "World!" }); InterfaceMember catMethod = proxyBusObj.GetInterface(InterfaceName).GetMethod("cat"); byte flags = (byte)0; Task <MethodCallResult> catTask = proxyBusObj.MethodCallAsync(catMethod, new MsgArg[] { hello, world }, null, 5000, flags).AsTask <MethodCallResult>(); catTask.Wait(); MethodCallResult catResult = catTask.Result; if (catResult.Message.Type == AllJoynMessageType.MESSAGE_METHOD_RET) { this.DebugPrint(this.DiscoveredName + ".cat ( path=" + ServicePath + ") returned \"" + catResult.Message.GetArg(0).Value.ToString() + "\""); } else { this.DebugPrint("Method call on " + this.DiscoveredName + ".cat failed (ReturnType=" + catResult.Message.Type.ToString() + ")"); } } else { this.DebugPrint("Introspection was unsuccessful: " + status.ToString()); } } else { this.DebugPrint("Join Session was unsuccessful: " + status.ToString()); } this.busAtt.CancelFindAdvertisedName(ServiceName); this.busAtt.UnregisterBusListener(clientBusListener); this.DebugPrint("Successfully unraveled the client operation"); } catch (ArgumentNullException ex) { this.DebugPrint(">>>> TIMEOUT, Client could not find WKN >>>>"); } catch (Exception ex) { var errMsg = AllJoynException.GetErrorMessage(ex.HResult); this.DebugPrint(">>>> Client Execution Error >>>> " + errMsg); } }
/// <summary> /// This method is called when the advertised name is found. /// </summary> /// <param name="wellKnownName">A well known name that the remote bus is advertising.</param> /// <param name="transportMask">Transport that received the advertisement.</param> /// <param name="namePrefix">The well-known name prefix used in call to FindAdvertisedName that triggered this callback.</param> private async void FoundAdvertisedName(string wellKnownName, TransportMaskType transportMask, string namePrefix) { if (!string.IsNullOrEmpty(wellKnownName) && wellKnownName.CompareTo(App.ServiceName) == 0) { string foundIt = string.Format( "Client found advertised name '{0}' on {1}.", wellKnownName, transportMask.ToString()); App.OutputLine(foundIt); // We found a remote bus that is advertising the well-known name so connect to it. bool result = await this.JoinSessionAsync(); if (result) { InterfaceDescription secureInterface = this.Bus.GetInterface(App.InterfaceName); this.ProxyObject = new ProxyBusObject(this.Bus, App.ServiceName, App.ServicePath, 0); this.ProxyObject.AddInterface(secureInterface); MsgArg[] inputs = new MsgArg[1]; inputs[0] = new MsgArg("s", new object[] { "Client says Hello AllJoyn!" }); MethodCallResult callResults = null; try { callResults = await this.ProxyObject.MethodCallAsync(App.InterfaceName, "Ping", inputs, null, 5000, 0); } catch (Exception ex) { const string ErrorFormat = "ProxyObject.MethodCallAsync(\"Ping\") call produced error(s). QStatus = 0x{0:X} ('{1}')."; QStatus status = AllJoynException.GetErrorCode(ex.HResult); string error = string.Format(ErrorFormat, status, status.ToString()); System.Diagnostics.Debug.WriteLine(error); App.OutputLine(error); } if (callResults != null) { Message mess = callResults.Message; AllJoynMessageType messType = mess.Type; if (messType == AllJoynMessageType.MESSAGE_METHOD_RET) { string strRet = mess.GetArg(0).Value as string; if (!string.IsNullOrEmpty(strRet)) { string output = string.Format( "{0}.Ping (path = {1}) returned \"{2}\"", App.InterfaceName, App.ServicePath, strRet); App.OutputLine(output); } else { const string Error = "Error: Server returned null or empty string in response to ping."; App.OutputLine(Error); System.Diagnostics.Debug.WriteLine(Error); } } else { string error = string.Format("Server returned message of type '{0}'.", messType.ToString()); App.OutputLine(error); System.Diagnostics.Debug.WriteLine(error); } } } } }
/// <summary> /// Connects to the bus, finds the service and calls the 'cat' with the two /// arguments "Hello " and "World!" /// </summary> /// <param name="sender">UI control which signaled the click event</param> /// <param name="e">arguments associated with the click event</param> private void Button_RunClick(object sender, RoutedEventArgs e) { if (!runningClient) { Task task = new Task(async() => { try { runningClient = true; busAtt = new BusAttachment("ClientApp", true, 4); this.OutputLine("BusAttachment Created."); BasicClientBusListener basicClientBusListener = new BasicClientBusListener(busAtt, foundNameEvent); busAtt.RegisterBusListener(basicClientBusListener); this.OutputLine("BusListener Registered."); /* Create and register the bundled daemon. The client process connects to daemon over tcp connection */ busAtt.Start(); await busAtt.ConnectAsync(BasicClientGlobals.ConnectSpec); this.OutputLine("Bundled Daemon Registered."); this.OutputLine("BusAttachment Connected to " + BasicClientGlobals.ConnectSpec + "."); busAtt.FindAdvertisedName(BasicClientGlobals.WellKnownServiceName); foundNameEvent.WaitOne(); /* Configure session properties and request a session with device with wellKnownName */ SessionOpts sessionOpts = new SessionOpts( BasicClientGlobals.SessionProps.TrType, BasicClientGlobals.SessionProps.IsMultiPoint, BasicClientGlobals.SessionProps.PrType, BasicClientGlobals.SessionProps.TmType); SessionOpts[] sOptsOut = new SessionOpts[1]; JoinSessionResult joinResults = await busAtt.JoinSessionAsync( BasicClientGlobals.WellKnownServiceName, BasicClientGlobals.SessionProps.SessionPort, basicClientBusListener, sessionOpts, sOptsOut, null); QStatus status = joinResults.Status; if (QStatus.ER_OK != status) { this.OutputLine("Joining a session with the Service was unsuccessful."); } else { this.OutputLine("Join Session was successful (sessionId=" + joinResults.SessionId + ")."); } // Create the proxy for the service interface by introspecting the service bus object ProxyBusObject proxyBusObject = new ProxyBusObject(busAtt, BasicClientGlobals.WellKnownServiceName, BasicClientGlobals.ServicePath, 0); if (QStatus.ER_OK == status) { IntrospectRemoteObjectResult introResult = await proxyBusObject.IntrospectRemoteObjectAsync(null); status = introResult.Status; if (QStatus.ER_OK != status) { this.OutputLine("Introspection of the service bus object failed."); } else { this.OutputLine("Introspection of the service bus object was successful."); } } if (QStatus.ER_OK == status) { // Call 'cat' method with the two string to be concatenated ("Hello" and " World!") MsgArg[] catMe = new MsgArg[2]; catMe[0] = new MsgArg("s", new object[] { "Hello" }); catMe[1] = new MsgArg("s", new object[] { " World!" }); InterfaceDescription interfaceDescription = proxyBusObject.GetInterface(BasicClientGlobals.InterfaceName); InterfaceMember interfaceMember = interfaceDescription.GetMember("cat"); this.OutputLine("Calling the 'cat' method of the service with args 'Hello' and ' World!'"); MethodCallResult callResults = await proxyBusObject.MethodCallAsync(interfaceMember, catMe, null, 100000, 0); Message msg = callResults.Message; if (msg.Type == AllJoynMessageType.MESSAGE_METHOD_RET) { string strRet = msg.GetArg(0).Value as string; this.OutputLine("Sender '" + msg.Sender + "' returned the value '" + strRet + "'"); } else { this.OutputLine("The 'cat' method call produced errors of type: " + msg.Type.ToString()); } } TearDown(); } catch (Exception ex) { QStatus s = AllJoynException.GetErrorCode(ex.HResult); } }); task.Start(); } }
/// <summary> /// This method is called when the advertised name is found. /// </summary> /// <param name="wellKnownName">A well known name that the remote bus is advertising.</param> /// <param name="transportMask">Transport that received the advertisement.</param> /// <param name="namePrefix">The well-known name prefix used in call to FindAdvertisedName that triggered this callback.</param> private async void FoundAdvertisedName(string wellKnownName, TransportMaskType transportMask, string namePrefix) { if (!string.IsNullOrEmpty(wellKnownName) && wellKnownName.CompareTo(App.ServiceName) == 0) { string foundIt = string.Format( "Client found advertised name '{0}' on {1}.", wellKnownName, transportMask.ToString()); App.OutputLine(foundIt); // We found a remote bus that is advertising the well-known name so connect to it. bool result = await this.JoinSessionAsync(); if (result) { InterfaceDescription secureInterface = this.Bus.GetInterface(App.InterfaceName); this.ProxyObject = new ProxyBusObject(this.Bus, App.ServiceName, App.ServicePath, 0); this.ProxyObject.AddInterface(secureInterface); MsgArg[] inputs = new MsgArg[1]; inputs[0] = new MsgArg("s", new object[] { "Client says Hello AllJoyn!" }); MethodCallResult callResults = null; try { callResults = await this.ProxyObject.MethodCallAsync(App.InterfaceName, "Ping", inputs, null, 5000, 0); } catch (Exception ex) { const string ErrorFormat = "ProxyObject.MethodCallAsync(\"Ping\") call produced error(s). QStatus = 0x{0:X} ('{1}')."; QStatus status = AllJoynException.GetErrorCode(ex.HResult); string error = string.Format(ErrorFormat, status, status.ToString()); System.Diagnostics.Debug.WriteLine(error); App.OutputLine(error); } if (callResults != null) { Message mess = callResults.Message; AllJoynMessageType messType = mess.Type; if (messType == AllJoynMessageType.MESSAGE_METHOD_RET) { string strRet = mess.GetArg(0).Value as string; if (!string.IsNullOrEmpty(strRet)) { string output = string.Format( "{0}.Ping (path = {1}) returned \"{2}\"", App.InterfaceName, App.ServicePath, strRet); App.OutputLine(output); } else { const string Error = "Error: Server returned null or empty string in response to ping."; App.OutputLine(Error); System.Diagnostics.Debug.WriteLine(Error); } } else { string error = string.Format("Server returned message of type '{0}'.", messType.ToString()); App.OutputLine(error); System.Diagnostics.Debug.WriteLine(error); } } } } }
/// <summary> /// Stop this client from using the AllJoyn bus. /// </summary> internal void Stop() { if (null != this.Bus) { this.Bus.UnregisterBusListener(this.Listeners); } this.ProxyObject = null; this.Listeners = null; this.Bus = null; App.OutputLine("Client has been stopped."); }
/// <summary> /// Connects to the bus, finds the service and calls the 'cat' with the two /// arguments "Hello " and "World!" /// </summary> /// <param name="sender">UI control which signaled the click event</param> /// <param name="e">arguments associated with the click event</param> private void Button_RunClick(object sender, RoutedEventArgs e) { if (!runningClient) { Task task = new Task(async () => { try { runningClient = true; busAtt = new BusAttachment("ClientApp", true, 4); this.OutputLine("BusAttachment Created."); BasicClientBusListener basicClientBusListener = new BasicClientBusListener(busAtt, foundNameEvent); busAtt.RegisterBusListener(basicClientBusListener); this.OutputLine("BusListener Registered."); /* Create and register the bundled daemon. The client process connects to daemon over tcp connection */ busAtt.Start(); await busAtt.ConnectAsync(BasicClientGlobals.ConnectSpec); this.OutputLine("Bundled Daemon Registered."); this.OutputLine("BusAttachment Connected to " + BasicClientGlobals.ConnectSpec + "."); busAtt.FindAdvertisedName(BasicClientGlobals.WellKnownServiceName); foundNameEvent.WaitOne(); /* Configure session properties and request a session with device with wellKnownName */ SessionOpts sessionOpts = new SessionOpts( BasicClientGlobals.SessionProps.TrType, BasicClientGlobals.SessionProps.IsMultiPoint, BasicClientGlobals.SessionProps.PrType, BasicClientGlobals.SessionProps.TmType); SessionOpts[] sOptsOut = new SessionOpts[1]; JoinSessionResult joinResults = await busAtt.JoinSessionAsync( BasicClientGlobals.WellKnownServiceName, BasicClientGlobals.SessionProps.SessionPort, basicClientBusListener, sessionOpts, sOptsOut, null); QStatus status = joinResults.Status; if (QStatus.ER_OK != status) { this.OutputLine("Joining a session with the Service was unsuccessful."); } else { this.OutputLine("Join Session was successful (sessionId=" + joinResults.SessionId + ")."); } // Create the proxy for the service interface by introspecting the service bus object ProxyBusObject proxyBusObject = new ProxyBusObject(busAtt, BasicClientGlobals.WellKnownServiceName, BasicClientGlobals.ServicePath, 0); if (QStatus.ER_OK == status) { IntrospectRemoteObjectResult introResult = await proxyBusObject.IntrospectRemoteObjectAsync(null); status = introResult.Status; if (QStatus.ER_OK != status) { this.OutputLine("Introspection of the service bus object failed."); } else { this.OutputLine("Introspection of the service bus object was successful."); } } if (QStatus.ER_OK == status) { // Call 'cat' method with the two string to be concatenated ("Hello" and " World!") MsgArg[] catMe = new MsgArg[2]; catMe[0] = new MsgArg("s", new object[] { "Hello" }); catMe[1] = new MsgArg("s", new object[] { " World!" }); InterfaceDescription interfaceDescription = proxyBusObject.GetInterface(BasicClientGlobals.InterfaceName); InterfaceMember interfaceMember = interfaceDescription.GetMember("cat"); this.OutputLine("Calling the 'cat' method of the service with args 'Hello' and ' World!'"); MethodCallResult callResults = await proxyBusObject.MethodCallAsync(interfaceMember, catMe, null, 100000, 0); Message msg = callResults.Message; if (msg.Type == AllJoynMessageType.MESSAGE_METHOD_RET) { string strRet = msg.GetArg(0).Value as string; this.OutputLine("Sender '" + msg.Sender + "' returned the value '" + strRet + "'"); } else { this.OutputLine("The 'cat' method call produced errors of type: " + msg.Type.ToString()); } } TearDown(); } catch (Exception ex) { QStatus s = AllJoynException.GetErrorCode(ex.HResult); } }); task.Start(); } }