/// <summary> /// Do the stuff required to join the session. /// </summary> /// <returns>True if successfully joined the session.</returns> private async Task <bool> JoinSessionAsync() { bool returnValue = true; SessionOpts opts = new SessionOpts( TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); SessionOpts[] opts_out = new SessionOpts[1]; JoinSessionResult result = await this.Bus.JoinSessionAsync( App.ServiceName, App.ServicePort, this.Listeners, opts, opts_out, null); if (result.Status == QStatus.ER_OK) { App.OutputLine("Successfully joined session."); } else { string errorMessage = string.Format("Join session failed with error {0:X}.", result.Status); App.OutputLine(errorMessage); returnValue = false; } return(returnValue); }
async void InitializeAllJoyn() { Debug.UseOSLogging(true); Debug.SetDebugLevel("ALLJOYN", 7); _bus = new BusAttachment(APPLICATION_NAME, true, 4); string connectSpec = "null:"; _bus.Start(); try { _mp3Reader = new MP3Reader(); if (_streamingSong != null) { _streamingSongBasicProperties = await _streamingSong.GetBasicPropertiesAsync(); if (_streamingSongBasicProperties != null) { _streamingSongMusicProperties = await _streamingSong.Properties.GetMusicPropertiesAsync(); if (_streamingSongMusicProperties != null) { await _mp3Reader.SetFileAsync(_streamingSong); _bus.ConnectAsync(connectSpec).AsTask().Wait(); _connected = true; _listeners = new Listeners(_bus, this); _bus.RegisterBusListener(_listeners); _mediaSource = new MediaSource(_bus); _audioStream = new AudioStream(_bus, "mp3", _mp3Reader, 100, 1000); _mediaSource.AddStream(_audioStream); /* Register MediaServer bus object */ _bus.RegisterBusObject(_mediaSource.MediaSourceBusObject); /* Request a well known name */ _bus.RequestName(MediaServerName, (int)(RequestNameType.DBUS_NAME_REPLACE_EXISTING | RequestNameType.DBUS_NAME_DO_NOT_QUEUE)); /* Advertise name */ _bus.AdvertiseName(MediaServerName, TransportMaskType.TRANSPORT_ANY); /* Bind a session for incoming client connections */ SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); ushort[] portOut = new ushort[1]; _bus.BindSessionPort(SESSION_PORT, portOut, opts, _listeners); } } } } catch (Exception ex) { string message = ex.Message; QStatus status = AllJoynException.GetErrorCode(ex.HResult); string errMsg = AllJoynException.GetErrorMessage(ex.HResult); } }
public void JoinSessionAsyncTest() { BusAttachment service = new BusAttachment("service", true, 4); ServiceSessionPortListener spl = new ServiceSessionPortListener(service); service.Start(); service.ConnectAsync(connectSpec).AsTask().Wait(); service.RequestName("org.alljoyn.testing.service", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE); SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); service.BindSessionPort(77, new ushort[1], opts, spl.spl); service.AdvertiseName("org.alljoyn.testing.service", TransportMaskType.TRANSPORT_ANY); BusAttachment client = new BusAttachment("client", true, 4); BusListener cbl = new BusListener(client); ClientSessionListener csl = new ClientSessionListener(client); cbl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler( (string name, TransportMaskType transport, string namePrefix) => { if (namePrefix == "org.alljoyn.testing.service") { clientFoundService.Set(); } }); client.RegisterBusListener(cbl); client.Start(); client.ConnectAsync(connectSpec).AsTask().Wait(); client.FindAdvertisedName("org.alljoyn.testing.service"); clientFoundService.WaitOne(); SessionOpts[] optsOut = new SessionOpts[1]; Task <JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.testing.service", (ushort)77, csl.sl, opts, optsOut, null).AsTask <JoinSessionResult>(); joinTask.Wait(); //The wait of 10ms ensures that the acceptSessionJoiner and sessionJoined callbacks are completed onthe service side. Task.Delay(10).Wait(); if (QStatus.ER_OK == joinTask.Result.Status) { Assert.IsTrue(spl.AcceptSessionJoinerCalled && spl.SessionJoinedCalled); Assert.AreEqual(joinTask.Result.SessionId, spl.SessionId); Assert.AreEqual(joinTask.Result.Opts.IsMultipoint, optsOut[0].IsMultipoint); Assert.AreEqual(joinTask.Result.Opts.Proximity, optsOut[0].Proximity); Assert.AreEqual(joinTask.Result.Opts.Traffic, optsOut[0].Traffic); Assert.AreEqual(joinTask.Result.Opts.TransportMask, optsOut[0].TransportMask); Assert.AreEqual(joinTask.Result.Opts.IsMultipoint, opts.IsMultipoint); Assert.AreEqual(joinTask.Result.Opts.Proximity, opts.Proximity); Assert.AreEqual(joinTask.Result.Opts.Traffic, opts.Traffic); Assert.AreEqual(joinTask.Result.Opts.TransportMask, opts.TransportMask); } else { Assert.IsFalse(true); } service.LeaveSession(spl.SessionId); sessionLost.WaitOne(); }
/// <summary> /// connects with the bus, creates an interface and advertises a well-known name for /// clients to join a session with. /// </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 (busObject == null && busAtt == null) { Task task = new Task(async() => { try { busAtt = new BusAttachment("SignalServiceApp", true, 4); busObject = new SignalServiceBusObject(busAtt); OutputLine("BusObject Created."); busListener = new SignalServiceBusListener(busAtt); OutputLine("BusAttachment and BusListener Created."); busAtt.RegisterBusListener(busListener); OutputLine("BusListener Registered."); busAtt.Start(); await busAtt.ConnectAsync(SignalServiceGlobals.ConnectSpec); OutputLine("Bundled Daemon Registered."); OutputLine("BusAttachment Connected to " + SignalServiceGlobals.ConnectSpec + "."); SessionOpts sessionOpts = new SessionOpts( SignalServiceGlobals.SessionProps.TrType, SignalServiceGlobals.SessionProps.IsMultiPoint, SignalServiceGlobals.SessionProps.PrType, SignalServiceGlobals.SessionProps.TmType); try { ushort[] portOut = new ushort[1]; busAtt.BindSessionPort(SignalServiceGlobals.SessionProps.SessionPort, portOut, sessionOpts, busListener); busAtt.RequestName(SignalServiceGlobals.WellKnownServiceName, (int)RequestNameType.DBUS_NAME_DO_NOT_QUEUE); busAtt.AdvertiseName(SignalServiceGlobals.WellKnownServiceName, TransportMaskType.TRANSPORT_ANY); OutputLine("Name is Being Advertised as: " + SignalServiceGlobals.WellKnownServiceName); } catch (COMException ce) { QStatus s = AllJoynException.GetErrorCode(ce.HResult); OutputLine("Errors were produced while establishing the service."); TearDown(); } } catch (Exception ex) { OutputLine("Errors occurred while setting up the service."); QStatus status = AllJoynException.GetErrorCode(ex.HResult); busObject = null; busAtt = null; } }); task.Start(); } }
public QStatus BindSessionPort(ref ushort sessionPort, SessionOpts opts, SessionPortListener listener) { QStatus ret = QStatus.OK; ushort otherSessionPort = sessionPort; ret = alljoyn_busattachment_bindsessionport(_busAttachment, ref otherSessionPort, opts.UnmanagedPtr, listener.UnmanagedPtr); sessionPort = otherSessionPort; return(ret); }
public QStatus JoinSession(string sessionHost, ushort sessionPort, SessionListener listener, out uint sessionId, SessionOpts opts) { IntPtr optsPtr = opts.UnmanagedPtr; uint sessionId_out = 0; int qstatus = alljoyn_busattachment_joinsession( _busAttachment, sessionHost, sessionPort, (listener == null ? IntPtr.Zero : listener.UnmanagedPtr), ref sessionId_out, optsPtr); sessionId = sessionId_out; return(qstatus); }
/// <summary> /// Run the service stress op which stresses the bus attachment in a service type /// configuration by advertising a well known name which an implementation of the /// 'cat' method /// </summary> /// <param name="isMultipoint">True if operation uses multipoint sessions</param> private void RunService(bool isMultipoint) { try { ServiceBusListener serviceBusListener = new ServiceBusListener(this.busAtt, this); ServiceBusObject serviceBusObject = new ServiceBusObject(this.busAtt, this); this.DebugPrint("Registered the Service BusListener and BusObject"); uint flags = (uint)(RequestNameType.DBUS_NAME_REPLACE_EXISTING | RequestNameType.DBUS_NAME_DO_NOT_QUEUE); string randServiceName = null; lock (rand) { randServiceName = ServiceName + ".n" + rand.Next(10000000); } this.busAtt.RequestName(randServiceName, flags); SessionOpts optsIn = new SessionOpts( TrafficType.TRAFFIC_MESSAGES, isMultipoint, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); ushort[] portOut = new ushort[1]; this.busAtt.BindSessionPort(ServicePort, portOut, optsIn, (SessionPortListener)serviceBusListener); this.busAtt.AdvertiseName(randServiceName, TransportMaskType.TRANSPORT_ANY); this.DebugPrint("Advertising WKN : " + randServiceName); int wait = 0; lock (rand) { wait = 8000 + rand.Next(6000); } Task.Delay(wait).AsAsyncAction().AsTask().Wait(); this.DebugPrint("Unraveling the service opertaion"); this.busAtt.CancelAdvertiseName(randServiceName, TransportMaskType.TRANSPORT_ANY); this.busAtt.UnbindSessionPort(ServicePort); this.busAtt.ReleaseName(randServiceName); this.busAtt.UnregisterBusObject((BusObject)serviceBusObject); this.busAtt.UnregisterBusListener((BusListener)serviceBusListener); this.DebugPrint("Successfully unraveled the service opertaion"); } catch (Exception ex) { var errMsg = AllJoynException.GetErrorMessage(ex.HResult); this.DebugPrint(">>>> Service Exectution Execution Error >>>> : " + errMsg); } }
public async void OnFoundMediaServer() { if (_sessionId == 0) { /* * Join the session - if we need a specific qos we would check it here. */ SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); SessionOpts[] opts_out = new SessionOpts[1]; JoinSessionResult result = await _bus.JoinSessionAsync(MEDIA_SERVER_NAME, SESSION_PORT, _listeners, opts, opts_out, null); _sessionId = result.SessionId; ConnectToServer(); } }
/// <summary> /// Bind the session port /// </summary> /// <param name="port">Port number to bind</param> /// <param name="opts">Session options for binding the port</param> public void DoBind(uint port, SessionOpts opts) { try { ushort[] sessionPortOut = new ushort[1]; this.busAtt.BindSessionPort((ushort)port, sessionPortOut, opts, (SessionPortListener)this.busListener); lock (this.sessionPortMap) { this.sessionPortMap.Add(port, new SessionPortInfo(port, this.busAtt.UniqueName, opts)); } } catch (Exception ex) { var errMsg = AllJoynException.GetErrorMessage(ex.HResult); this.mainPage.Output("BusAttachment.BindSessionPort for port " + port + " failed: " + errMsg); } }
public void BindSessionPortTest() { BusAttachment bus = new BusAttachment("bindports", true, 4); bus.Start(); bus.ConnectAsync(connectSpec).AsTask().Wait(); SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); SessionPortListener spl = new SessionPortListener(bus); for (ushort i = 1; i <= 10; i++) { ushort[] portOut = new ushort[1]; bus.BindSessionPort((ushort)(i * 10), portOut, opts, spl); Assert.AreEqual((ushort)(i * 10), portOut[0]); } }
public QStatus BindSessionPort(ref ushort sessionPort, SessionOpts opts, SessionPortListener listener) { QStatus ret = QStatus.OK; ushort otherSessionPort = sessionPort; Thread bindThread = new Thread((object o) => { ret = alljoyn_busattachment_bindsessionport(_busAttachment, ref otherSessionPort, opts.UnmanagedPtr, listener.UnmanagedPtr); }); bindThread.Start(); while (bindThread.IsAlive) { AllJoyn.TriggerCallbacks(); Thread.Sleep(0); } sessionPort = otherSessionPort; return(ret); }
/// <summary> /// Start up the channel we are hosting. /// </summary> /// <param name="name">The name, minus the name prefix, for the channel we are hosting.</param> private void StartChannel(string name) { try { this.channelHosted = name; string wellKnownName = this.MakeWellKnownName(name); this.bus.RequestName(wellKnownName, (int)RequestNameType.DBUS_NAME_DO_NOT_QUEUE); this.bus.AdvertiseName(wellKnownName, alljoynTransports); ushort[] portOut = new ushort[1]; SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, alljoynTransports); this.bus.BindSessionPort(ContactPort, portOut, opts, this.busListeners); DisplayStatus("Start Chat channel " + name + " successfully"); } catch (Exception ex) { QStatus stat = AllJoynException.GetErrorCode(ex.HResult); string errMsg = AllJoynException.GetErrorMessage(ex.HResult); DisplayStatus("StartChannel Error : " + errMsg); } }
/// <summary> /// Joins a session with specified nameprefix using specs provided /// </summary> /// <param name="name">Name prefix or well-known name to join session with</param> /// <param name="sessionPort">Port for session</param> /// <param name="opts">Session Opts for session</param> public async void DoJoinAsync(string name, uint sessionPort, SessionOpts opts) { SessionOpts[] optsOut = new SessionOpts[1]; JoinSessionResult joinResult = await this.busAtt.JoinSessionAsync(name, (ushort)sessionPort, (SessionListener)this.busListener, opts, optsOut, null); QStatus status = joinResult.Status; if (QStatus.ER_OK == status) { this.mainPage.Output("BusAttachment.JoinSessionAsync(" + name + ", " + sessionPort + ", ...) succeeded with id=" + joinResult.SessionId); lock (this.sessionMap) { this.sessionMap.Add(joinResult.SessionId, new SessionInfo(joinResult.SessionId, new SessionPortInfo(sessionPort, name, opts))); } } else { this.mainPage.Output("BusAttachment.JoinSessionAsync(" + name + ", " + sessionPort + ", ...) failed: " + status.ToString()); } }
/// <summary> /// Do the stuff required to join the session. /// </summary> /// <returns>True if successfully joined the session.</returns> private async Task <bool> JoinSessionAsync() { bool returnValue = true; SessionOpts opts = new SessionOpts( ClientGlobals.SessionProps.TrType, ClientGlobals.SessionProps.IsMultiPoint, ClientGlobals.SessionProps.PrType, ClientGlobals.SessionProps.TmType); SessionOpts[] opts_out = new SessionOpts[1]; App app = Application.Current as App; JoinSessionResult result = await this.Bus.JoinSessionAsync( ClientGlobals.ServiceName, ClientGlobals.SessionProps.SessionPort, app.Listeners, opts, opts_out, null); string message = string.Format("Join Session status = {0}.", result.Status.ToString()); App.OutputLine(message); if (QStatus.ER_OK == result.Status) { this.SessionId = result.SessionId; message = string.Format("SessionId='{0}'.", result.SessionId); App.OutputLine(message); } else { string errorMessage = string.Format("Join session failed with error {0:X}.", result.Status); App.OutputLine(errorMessage); returnValue = false; } return(returnValue); }
public QStatus JoinSession(string sessionHost, ushort sessionPort, SessionListener listener, out uint sessionId, SessionOpts opts) { IntPtr optsPtr = opts.UnmanagedPtr; uint sessionId_out = 0; int qstatus = 0; Thread joinSessionThread = new Thread((object o) => { qstatus = alljoyn_busattachment_joinsession(_busAttachment, sessionHost, sessionPort, (listener == null ? IntPtr.Zero : listener.UnmanagedPtr), ref sessionId_out, optsPtr); }); joinSessionThread.Start(); while (joinSessionThread.IsAlive) { AllJoyn.TriggerCallbacks(); Thread.Sleep(1); } sessionId = sessionId_out; return(qstatus); }
/// <summary> /// Determines whether to accept a session. Returns true if yes, false otherwise. /// </summary> /// <param name="sessionPort">The session port being joined.</param> /// <param name="joiner">The client name attempting to join.</param> /// <param name="opts">The sessions options for the join.</param> /// <returns>true if joining is acceptable. false if not acceptable.</returns> private bool AcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { if (sessionPort != App.ServicePort) { string rejectMessage = string.Format("Rejecting join attempt on unexpected session port {0}.", sessionPort); App.OutputLine(rejectMessage); return(false); } string successMessage = string.Format( "Accepting join session request from {0} (opts.proximity={1}, opts.traffic={2}, opts.transports={3}).", joiner, opts.Proximity.ToString(), opts.Traffic.ToString(), opts.TransportMask.ToString()); App.OutputLine(successMessage); return(true); }
/// <summary> /// Join an existing channel with the given name. /// </summary> /// <param name="name">The name of the channel to join.</param> private async void JoinChannel(string name) { try { this.DisplayStatus("Joining chat session: " + name); string wellKnownName = this.MakeWellKnownName(name); SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, alljoynTransports); SessionOpts[] opts_out = new SessionOpts[1]; this.channelJoined = name; JoinSessionResult result = await this.bus.JoinSessionAsync( wellKnownName, ContactPort, this.busListeners, opts, opts_out, null); if (result.Status == QStatus.ER_OK) { this.SessionId = result.SessionId; this.DisplayStatus("Join chat session " + this.SessionId + " successfully"); await this.coreDispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { this.JoinChannelButton.Content = "Leave Channel"; }); } else { this.DisplayStatus("Join chat session " + result.SessionId + " failed. Error: " + result.Status); } } catch (Exception ex) { QStatus stat = AllJoynException.GetErrorCode(ex.HResult); string errMsg = AllJoynException.GetErrorMessage(ex.HResult); DisplayStatus("JoinChannel Error : " + errMsg); } }
/** * Compare SessionOpts * * @param one the SessionOpts being compared to * @param other the SessionOpts being compared against * @return true if all of the SessionOpts parameters are the same * */ public static int Compare(SessionOpts one, SessionOpts other) { return alljoyn_sessionopts_cmp(one._sessionOpts, other._sessionOpts); }
/// <summary> /// This callback is only used by session creators. Therefore it is only called on listeners /// passed to BusAttachment::BindSessionPort. /// </summary> /// <param name="sessionPort">Session port that was joined.</param> /// <param name="joiner">Unique name of potential joiner.</param> /// <param name="opts">Session options requested by the joiner.</param> /// <returns>True, iff the listener is accepting the join</returns> private bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { if (this.AcceptSessionJoiner != null) { return(this.AcceptSessionJoiner(sessionPort, joiner, opts)); } return(true); }
/// <summary> /// Initializes a new instance of the <see cref="SessionPortInfo"/> class /// </summary> /// <param name="sessPort">Port Number</param> /// <param name="host">Host for this session port</param> /// <param name="sessOpts">Session options this port uses</param> public SessionPortInfo(uint sessPort, string host, SessionOpts sessOpts) { this.SessionPort = sessPort; this.SessionHost = host; this.Opts = sessOpts; }
public QStatus BindSessionPort(ref ushort sessionPort, SessionOpts opts, SessionPortListener listener) { QStatus ret = QStatus.OK; ushort otherSessionPort = sessionPort; Thread bindThread = new Thread((object o) => { ret = alljoyn_busattachment_bindsessionport(_busAttachment, ref otherSessionPort, opts.UnmanagedPtr, listener.UnmanagedPtr); }); bindThread.Start(); while(bindThread.IsAlive) { AllJoyn.TriggerCallbacks(); Thread.Sleep(0); } sessionPort = otherSessionPort; return ret; }
public QStatus JoinSession(string sessionHost, ushort sessionPort, SessionListener listener, out uint sessionId, SessionOpts opts) { IntPtr optsPtr = opts.UnmanagedPtr; uint sessionId_out = 0; int qstatus = alljoyn_busattachment_joinsession( _busAttachment, sessionHost, sessionPort, (listener == null ? IntPtr.Zero : listener.UnmanagedPtr), ref sessionId_out, optsPtr); sessionId = sessionId_out; return qstatus; }
/// <summary> /// Called when the user has pressed the enter key to submit a command to the application /// </summary> /// <param name="sender">Obect which intiated the event</param> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> private async void Enter_Command(object sender, KeyRoutedEventArgs e) { if (e.Key == Windows.System.VirtualKey.Enter && string.Empty != this.input.Text && !this.btnUpDown) { string lineInput = this.input.Text.Trim(); string[] tokens = lineInput.Split(new char[] { ' ', '\t' }); for (uint i = 0; i < tokens.Length; i++) { tokens[i] = tokens[i].Trim(); } this.Output(string.Empty); this.Output(">>>>> " + lineInput); switch (tokens[0].ToLower()) { case "debug": try { if (3 == tokens.Length && string.Empty != tokens[1] && string.Empty != tokens[2]) { uint level = Convert.ToUInt32(tokens[2]); this.sessionOps.DoDebug(tokens[1], level); } else { this.Output("Usage: debug <modulename> <level>"); } } catch (Exception ex) { string errMsg = ex.Message; this.Output("Invalid Debug Level"); } break; case "requestname": if (2 == tokens.Length && string.Empty != tokens[1]) { this.sessionOps.DoRequestName(tokens[1]); } else { this.Output("Usage: requestname <name>"); } break; case "releasename": if (2 == tokens.Length && string.Empty != tokens[1]) { this.sessionOps.DoReleaseName(tokens[1]); } else { this.Output("Usage: releasename <name>"); } break; case "bind": try { if (2 == tokens.Length || 6 == tokens.Length) { uint port = Convert.ToUInt32(tokens[1]); if (0 == port) { this.Output("Invalid Port Number"); } else { SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); if (6 == tokens.Length) { string[] optsInput = { tokens[2], tokens[3], tokens[4], tokens[5] }; opts = this.GetSessionOpts(optsInput); } if (null != opts) { this.sessionOps.DoBind(port, opts); } else { this.Output("Usage: bind <port> [traffic] [isMultipoint] [proximity] [transports]"); } } } else { this.Output("Usage: bind <port> [traffic] [isMultipoint] [proximity] [transports]"); } } catch (Exception ex) { string errMsg = ex.Message; this.Output("Invalid Port Number"); } break; case "unbind": try { if (2 == tokens.Length) { uint port = Convert.ToUInt32(tokens[1]); if (0 == port) { this.Output("Invalid Port Number"); } else { this.sessionOps.DoUnbind(port); } } else { this.Output("Usage: unbind <port>"); } } catch (Exception ex) { string errMsg = ex.Message; this.Output("Invalid Port Number"); } break; case "advertise": try { if ((2 == tokens.Length || 3 == tokens.Length) && string.Empty != tokens[1]) { TransportMaskType transport = TransportMaskType.TRANSPORT_ANY; if (3 == tokens.Length) { uint tp = Convert.ToUInt32(tokens[2]); transport = (TransportMaskType)tp; } this.sessionOps.DoAdvertise(tokens[1], transport); } else { this.Output("Usage: advertise <name> [transports]"); } } catch (Exception ex) { string errMsg = ex.Message; this.Output("Invalid Transport Mask"); } break; case "canceladvertise": try { if ((2 == tokens.Length || 3 == tokens.Length) && string.Empty != tokens[1]) { TransportMaskType transport = TransportMaskType.TRANSPORT_ANY; if (3 == tokens.Length) { uint tp = Convert.ToUInt32(tokens[2]); transport = (TransportMaskType)tp; } this.sessionOps.DoCancelAdvertise(tokens[1], transport); } else { this.Output("Usage: canceladvertise <name> [transports]"); } } catch (Exception ex) { string errMsg = ex.Message; this.Output("Invalid Transport Mask"); } break; case "find": if (2 == tokens.Length && string.Empty != tokens[1]) { this.sessionOps.DoFind(tokens[1]); } else { this.Output("Usage: find <name_prefix>"); } break; case "cancelfind": if (2 == tokens.Length && string.Empty != tokens[1]) { this.sessionOps.DoCancelFind(tokens[1]); } else { this.Output("Usage: cancelfind <name_prefix>"); } break; case "list": this.sessionOps.DoList(); break; case "join": try { if ((3 == tokens.Length || 7 == tokens.Length) && string.Empty != tokens[1]) { uint port = Convert.ToUInt32(tokens[2]); if (0 == port) { this.Output("Invalid Port Number"); } else { SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); if (7 == tokens.Length) { string[] optsInput = { tokens[3], tokens[4], tokens[5], tokens[6] }; opts = this.GetSessionOpts(optsInput); } if (null != opts) { this.sessionOps.DoJoinAsync(tokens[1], port, opts); } else { this.Output("Usage: join <name> <port> [traffic] [isMultipoint] [proximity] [transports]"); } } } else { this.Output("Usage: join <name> <port> [traffic] [isMultipoint] [proximity] [transports]"); } } catch (Exception ex) { string errMsg = ex.Message; this.Output("Invalid Port Number"); } break; case "leave": if (2 == tokens.Length) { uint sessionId = this.GetSessionId(tokens[1]); if (sessionId == 0) { this.Output("Invalid Session ID"); } else { this.sessionOps.DoLeave(sessionId); } } else { this.Output("Usage: leave <sessionId>"); } break; case "timeout": try { if (3 == tokens.Length) { uint sessionId = this.GetSessionId(tokens[1]); uint timeOut = Convert.ToUInt32(tokens[2]); if (sessionId == 0 || timeOut == 0) { this.Output("Usage: timeout <sessionId> <timeout>"); } else { this.sessionOps.DoSetLinkTimeoutAsync(sessionId, timeOut); } } else { this.Output("Usage: timeout <sessionId> <timeout>"); } } catch (Exception ex) { string errMsg = ex.Message; this.Output("Invalid Timeout argument"); } break; case "chat": byte flags1 = (byte)AllJoyn.AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST; if (3 <= tokens.Length) { uint sessionId = this.GetSessionId(tokens[1]); string msg = string.Join(" ", tokens, 2, tokens.Length - 2); if (sessionId == 0) { this.Output("Usage: chat <sessionId> <msg>"); } else { this.sessionOps.SendChatSignal(sessionId, msg, flags1); } } else { this.Output("Usage: chat <sessionId> <msg>"); } break; case "cchat": byte flags2 = (byte)AllJoyn.AllJoynFlagType.ALLJOYN_FLAG_COMPRESSED; if (3 <= tokens.Length) { uint sessionId = this.GetSessionId(tokens[1]); string msg = string.Join(" ", tokens, 2, tokens.Length - 2); if (sessionId == 0 || msg == string.Empty) { this.Output("Usage: cchat <sessionId> <msg>"); } else { this.sessionOps.SendChatSignal(sessionId, msg, flags2); } } else { this.Output("Usage: cchat <sessionId> <msg>"); } break; case "schat": byte flags3 = (byte)AllJoyn.AllJoynFlagType.ALLJOYN_FLAG_SESSIONLESS; if (2 <= tokens.Length) { string msg = string.Join(" ", tokens, 1, tokens.Length - 1); if (msg == string.Empty) { this.Output("Usage: schat <msg>"); } else { this.sessionOps.SendSessionlessChatSignal(msg, flags3); } } else { this.Output("Usage: schat <msg>"); } break; case "addmatch": if (2 <= tokens.Length) { string msg = string.Join(" ", tokens, 1, tokens.Length - 1); if (msg == string.Empty) { this.Output("Usage: addmatch <filter>"); } else { this.sessionOps.AddRule(msg); } } else { this.Output("Usage: addmatch <filter>"); } break; case "chatecho": if (2 == tokens.Length) { if (tokens[1] == "on") { this.sessionOps.SetChatEcho(true); } else if (tokens[1] == "off") { this.sessionOps.SetChatEcho(false); } else { this.Output("Usage: chatecho [on|off]"); } } else { this.Output("Usage: chatecho [on|off]"); } break; case "exit": this.sessionOps.Exit(); break; case "help": this.sessionOps.PrintHelp(); break; default: this.Output("Unknown command: " + tokens[0]); break; } this.btnUpDown = true; await Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { this.input.Text = string.Empty; }); } else if (e.Key == Windows.System.VirtualKey.Enter && string.Empty == this.input.Text && !this.btnUpDown) { this.Output(">>>>>"); this.btnUpDown = true; } }
/// <summary> /// Accept or reject an incoming JoinSession request. The session does not exist until /// after this function returns. /// </summary> /// <param name="sessionPort">Session port that was joined.</param> /// <param name="joiner">Unique name of potential joiner.</param> /// <param name="opts">Session options requested by the joiner.</param> /// <returns>Return true if JoinSession request is accepted. false if rejected</returns> private bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { App.OutputLine("JoinSessionRequest was accepted by " + joiner); return true; }
/// <summary> /// This callback is only used by session creators. Therefore it is only called on listeners /// passed to BusAttachment::BindSessionPort. /// </summary> /// <param name="sessionPort">Session port that was joined.</param> /// <param name="joiner">Unique name of potential joiner.</param> /// <param name="opts">Session options requested by the joiner.</param> /// <returns>True, iff the listener is accepting the join</returns> private bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { if (this.AcceptSessionJoiner != null) { return this.AcceptSessionJoiner(sessionPort, joiner, opts); } return true; }
public void JoinSessionAsyncTest() { BusAttachment service = new BusAttachment("service", true, 4); ServiceSessionPortListener spl = new ServiceSessionPortListener(service); service.Start(); service.ConnectAsync(connectSpec).AsTask().Wait(); service.RequestName("org.alljoyn.testing.service", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE); SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); service.BindSessionPort(77, new ushort[1], opts, spl.spl); service.AdvertiseName("org.alljoyn.testing.service", TransportMaskType.TRANSPORT_ANY); BusAttachment client = new BusAttachment("client", true, 4); BusListener cbl = new BusListener(client); ClientSessionListener csl = new ClientSessionListener(client); cbl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler( (string name, TransportMaskType transport, string namePrefix) => { if (namePrefix == "org.alljoyn.testing.service") { clientFoundService.Set(); } }); client.RegisterBusListener(cbl); client.Start(); client.ConnectAsync(connectSpec).AsTask().Wait(); client.FindAdvertisedName("org.alljoyn.testing.service"); clientFoundService.WaitOne(); SessionOpts[] optsOut = new SessionOpts[1]; Task<JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.testing.service", (ushort)77, csl.sl, opts, optsOut, null).AsTask<JoinSessionResult>(); joinTask.Wait(); //The wait of 10ms ensures that the acceptSessionJoiner and sessionJoined callbacks are completed onthe service side. Task.Delay(10).Wait(); if (QStatus.ER_OK == joinTask.Result.Status) { Assert.IsTrue(spl.AcceptSessionJoinerCalled && spl.SessionJoinedCalled); Assert.AreEqual(joinTask.Result.SessionId, spl.SessionId); Assert.AreEqual(joinTask.Result.Opts.IsMultipoint, optsOut[0].IsMultipoint); Assert.AreEqual(joinTask.Result.Opts.Proximity, optsOut[0].Proximity); Assert.AreEqual(joinTask.Result.Opts.Traffic, optsOut[0].Traffic); Assert.AreEqual(joinTask.Result.Opts.TransportMask, optsOut[0].TransportMask); Assert.AreEqual(joinTask.Result.Opts.IsMultipoint, opts.IsMultipoint); Assert.AreEqual(joinTask.Result.Opts.Proximity, opts.Proximity); Assert.AreEqual(joinTask.Result.Opts.Traffic, opts.Traffic); Assert.AreEqual(joinTask.Result.Opts.TransportMask, opts.TransportMask); } else { Assert.IsFalse(true); } service.LeaveSession(spl.SessionId); sessionLost.WaitOne(); }
/// <summary> /// connects with the bus, creates an interface and advertises a well-known name for /// clients to join a session with. /// </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 (busObject == null && busAtt == null) { Task task = new Task(async () => { try { busAtt = new BusAttachment("SignalServiceApp", true, 4); busObject = new SignalServiceBusObject(busAtt); OutputLine("BusObject Created."); busListener = new SignalServiceBusListener(busAtt); OutputLine("BusAttachment and BusListener Created."); busAtt.RegisterBusListener(busListener); OutputLine("BusListener Registered."); busAtt.Start(); await busAtt.ConnectAsync(SignalServiceGlobals.ConnectSpec); OutputLine("Bundled Daemon Registered."); OutputLine("BusAttachment Connected to " + SignalServiceGlobals.ConnectSpec + "."); SessionOpts sessionOpts = new SessionOpts( SignalServiceGlobals.SessionProps.TrType, SignalServiceGlobals.SessionProps.IsMultiPoint, SignalServiceGlobals.SessionProps.PrType, SignalServiceGlobals.SessionProps.TmType); try { ushort[] portOut = new ushort[1]; busAtt.BindSessionPort(SignalServiceGlobals.SessionProps.SessionPort, portOut, sessionOpts, busListener); busAtt.RequestName(SignalServiceGlobals.WellKnownServiceName, (int)RequestNameType.DBUS_NAME_DO_NOT_QUEUE); busAtt.AdvertiseName(SignalServiceGlobals.WellKnownServiceName, TransportMaskType.TRANSPORT_ANY); OutputLine("Name is Being Advertised as: " + SignalServiceGlobals.WellKnownServiceName); } catch (COMException ce) { QStatus s = AllJoynException.GetErrorCode(ce.HResult); OutputLine("Errors were produced while establishing the service."); TearDown(); } } catch (Exception ex) { OutputLine("Errors occurred while setting up the service."); QStatus status = AllJoynException.GetErrorCode(ex.HResult); busObject = null; busAtt = null; } }); task.Start(); } }
/// <summary> /// Accept or reject an incoming JoinSession request. The session does not exist until /// after this function returns. /// </summary> /// <param name="sessionPort">Session port that was joined.</param> /// <param name="joiner">Unique name of potential joiner.</param> /// <param name="opts">Session options requested by the joiner.</param> /// <returns>Return true if JoinSession request is accepted. false if rejected</returns> private bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { bool ret = this.sessionOps.AcceptSessionJoiner(sessionPort); if (ret) { this.sessionOps.Output("Accepting join request on " + sessionPort + " from " + joiner); } else { this.sessionOps.Output("Rejecting join attempt to unregistered port " + sessionPort + " from " + joiner); } return ret; }
/** * Determine whether this SessionOpts is compatible with the SessionOpts offered by other * * @param other Options to be compared against this one. * @return true iff this SessionOpts can use the option set offered by other. */ public bool IsCompatible(SessionOpts other) { return(alljoyn_sessionopts_iscompatible(_sessionOpts, other._sessionOpts) == 1 ? true : false); }
public QStatus BindSessionPort(ref ushort sessionPort, SessionOpts opts, SessionPortListener listener) { QStatus ret = QStatus.OK; ushort otherSessionPort = sessionPort; ret = alljoyn_busattachment_bindsessionport(_busAttachment, ref otherSessionPort, opts.UnmanagedPtr, listener.UnmanagedPtr); sessionPort = otherSessionPort; return ret; }
/// <summary> /// Accept or reject an incoming JoinSession request. The session does not exist until /// after this function returns. /// </summary> /// <param name="sessionPort">Session port that was joined.</param> /// <param name="joiner">Unique name of potential joiner.</param> /// <param name="opts">Session options requested by the joiner.</param> /// <returns>Return true if JoinSession request is accepted. false if rejected</returns> private bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { App.OutputLine("Accepting JoinSessionRequest from " + joiner); return(true); }
private bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts sessionOpts) { return true; }
/// <summary> /// Connects to the bus and registers a signal handler for when the 'name' property changes. /// </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 (busAtt == null) { Task task = new Task(async () => { try { busAtt = new BusAttachment("SignalConsumerApp", true, 4); // create and activate the interface InterfaceDescription[] interfaceDescription = new InterfaceDescription[1]; busAtt.CreateInterface(SignalConsumerGlobals.InterfaceName, interfaceDescription, false); interfaceDescription[0].AddSignal("nameChanged", "s", "newName", (byte)0, string.Empty); interfaceDescription[0].AddProperty("name", "s", (byte)PropAccessType.PROP_ACCESS_RW); interfaceDescription[0].Activate(); busListener = new SignalConsumerBusListener(busAtt, foundNameEvent); OutputLine("BusAttachment and BusListener Created."); busAtt.RegisterBusListener(busListener); OutputLine("BusListener Registered."); busAtt.Start(); busAtt.ConnectAsync(SignalConsumerGlobals.ConnectSpec).AsTask().Wait(); OutputLine("Bundled Daemon Registered."); OutputLine("BusAttachment Connected to " + SignalConsumerGlobals.ConnectSpec + "."); busAtt.FindAdvertisedName(SignalConsumerGlobals.WellKnownServiceName); foundNameEvent.WaitOne(); /* Configure session properties and request a session with device with wellKnownName */ SessionOpts sessionOpts = new SessionOpts( SignalConsumerGlobals.SessionProps.TrType, SignalConsumerGlobals.SessionProps.IsMultiPoint, SignalConsumerGlobals.SessionProps.PrType, SignalConsumerGlobals.SessionProps.TmType); SessionOpts[] sessionOptsOut = new SessionOpts[1]; OutputLine("Requesting a session with the well known service name."); JoinSessionResult joinResult = await busAtt.JoinSessionAsync( SignalConsumerGlobals.WellKnownServiceName, SignalConsumerGlobals.SessionProps.SessionPort, busListener, sessionOpts, sessionOptsOut, null); if (QStatus.ER_OK == joinResult.Status) { OutputLine("Join Session was successful (sessionId=" + joinResult.SessionId + ")."); busAtt.AddMatch("type='signal',interface='org.alljoyn.Bus.signal_sample',member='nameChanged'"); OutputLine("Subscribed to the 'nameChanged' signal."); } else { OutputLine("Join Session was unsuccessful."); } } catch (Exception ex) { OutputLine("Errors were produced while establishing the application."); QStatus status = AllJoynException.GetErrorCode(ex.HResult); busAtt = null; } }); task.Start(); } }
async void InitializeAllJoyn(){ Debug.UseOSLogging(true); Debug.SetDebugLevel("ALLJOYN", 7); _bus = new BusAttachment(APPLICATION_NAME, true, 4); string connectSpec = "null:"; _bus.Start(); try { _mp3Reader = new MP3Reader(); if (_streamingSong != null) { _streamingSongBasicProperties = await _streamingSong.GetBasicPropertiesAsync(); if (_streamingSongBasicProperties != null) { _streamingSongMusicProperties = await _streamingSong.Properties.GetMusicPropertiesAsync(); if (_streamingSongMusicProperties != null) { await _mp3Reader.SetFileAsync(_streamingSong); _bus.ConnectAsync(connectSpec).AsTask().Wait(); _connected = true; _listeners = new Listeners(_bus, this); _bus.RegisterBusListener(_listeners); _mediaSource = new MediaSource(_bus); _audioStream = new AudioStream(_bus, "mp3", _mp3Reader, 100, 1000); _mediaSource.AddStream(_audioStream); /* Register MediaServer bus object */ _bus.RegisterBusObject(_mediaSource.MediaSourceBusObject); /* Request a well known name */ _bus.RequestName(MediaServerName, (int)(RequestNameType.DBUS_NAME_REPLACE_EXISTING | RequestNameType.DBUS_NAME_DO_NOT_QUEUE)); /* Advertise name */ _bus.AdvertiseName(MediaServerName, TransportMaskType.TRANSPORT_ANY); /* Bind a session for incoming client connections */ SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); ushort[] portOut = new ushort[1]; _bus.BindSessionPort(SESSION_PORT, portOut, opts, _listeners); } } } } catch (Exception ex) { string message = ex.Message; QStatus status = AllJoynException.GetErrorCode(ex.HResult); string errMsg = AllJoynException.GetErrorMessage(ex.HResult); } }
/// <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> /// Do the stuff required to join the session. /// </summary> /// <returns>True if successfully joined the session.</returns> private async Task<bool> JoinSessionAsync() { bool returnValue = true; SessionOpts opts = new SessionOpts( TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); SessionOpts[] opts_out = new SessionOpts[1]; JoinSessionResult result = await this.Bus.JoinSessionAsync( App.ServiceName, App.ServicePort, this.Listeners, opts, opts_out, null); if (result.Status == QStatus.ER_OK) { App.OutputLine("Successfully joined session."); } else { string errorMessage = string.Format("Join session failed with error {0:X}.", result.Status); App.OutputLine(errorMessage); returnValue = false; } return returnValue; }
private bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts sessionOpts) { return(true); }
/** * Determine whether this SessionOpts is compatible with the SessionOpts offered by other * * @param other Options to be compared against this one. * @return true iff this SessionOpts can use the option set offered by other. */ public bool IsCompatible(SessionOpts other) { return (alljoyn_sessionopts_iscompatible(_sessionOpts, other._sessionOpts) == 1 ? true : false); }
/// <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(); } }
public bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { Assert.AreEqual(77, sessionPort); AcceptSessionJoinerCalled = true; return true; }
/// <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(); } }
protected virtual bool AcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { return false; }
/// <summary> /// Accept or reject an incoming JoinSession request. The session does not exist until /// after this function returns. /// </summary> /// <param name="sessionPort">Session port that was joined.</param> /// <param name="joiner">Unique name of potential joiner.</param> /// <param name="opts">Session options requested by the joiner.</param> /// <returns>Return true if JoinSession request is accepted. false if rejected</returns> private bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { bool ret = this.sessionOps.AcceptSessionJoiner(sessionPort); if (ret) { this.sessionOps.Output("Accepting join request on " + sessionPort + " from " + joiner); } else { this.sessionOps.Output("Rejecting join attempt to unregistered port " + sessionPort + " from " + joiner); } return(ret); }
public QStatus JoinSession(string sessionHost, ushort sessionPort, SessionListener listener, out uint sessionId, SessionOpts opts) { IntPtr optsPtr = opts.UnmanagedPtr; uint sessionId_out = 0; int qstatus = 0; Thread joinSessionThread = new Thread((object o) => { qstatus = alljoyn_busattachment_joinsession(_busAttachment, sessionHost, sessionPort, (listener == null ? IntPtr.Zero : listener.UnmanagedPtr), ref sessionId_out, optsPtr); }); joinSessionThread.Start(); while(joinSessionThread.IsAlive) { AllJoyn.TriggerCallbacks(); Thread.Sleep(1); } sessionId = sessionId_out; return qstatus; }
/// <summary> /// Connects to the bus and registers a signal handler for when the 'name' property changes. /// </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 (busAtt == null) { Task task = new Task(async() => { try { busAtt = new BusAttachment("SignalConsumerApp", true, 4); // create and activate the interface InterfaceDescription[] interfaceDescription = new InterfaceDescription[1]; busAtt.CreateInterface(SignalConsumerGlobals.InterfaceName, interfaceDescription, false); interfaceDescription[0].AddSignal("nameChanged", "s", "newName", (byte)0, string.Empty); interfaceDescription[0].AddProperty("name", "s", (byte)PropAccessType.PROP_ACCESS_RW); interfaceDescription[0].Activate(); busListener = new SignalConsumerBusListener(busAtt, foundNameEvent); OutputLine("BusAttachment and BusListener Created."); busAtt.RegisterBusListener(busListener); OutputLine("BusListener Registered."); busAtt.Start(); busAtt.ConnectAsync(SignalConsumerGlobals.ConnectSpec).AsTask().Wait(); OutputLine("Bundled Daemon Registered."); OutputLine("BusAttachment Connected to " + SignalConsumerGlobals.ConnectSpec + "."); busAtt.FindAdvertisedName(SignalConsumerGlobals.WellKnownServiceName); foundNameEvent.WaitOne(); /* Configure session properties and request a session with device with wellKnownName */ SessionOpts sessionOpts = new SessionOpts( SignalConsumerGlobals.SessionProps.TrType, SignalConsumerGlobals.SessionProps.IsMultiPoint, SignalConsumerGlobals.SessionProps.PrType, SignalConsumerGlobals.SessionProps.TmType); SessionOpts[] sessionOptsOut = new SessionOpts[1]; OutputLine("Requesting a session with the well known service name."); JoinSessionResult joinResult = await busAtt.JoinSessionAsync( SignalConsumerGlobals.WellKnownServiceName, SignalConsumerGlobals.SessionProps.SessionPort, busListener, sessionOpts, sessionOptsOut, null); if (QStatus.ER_OK == joinResult.Status) { OutputLine("Join Session was successful (sessionId=" + joinResult.SessionId + ")."); busAtt.AddMatch("type='signal',interface='org.alljoyn.Bus.signal_sample',member='nameChanged'"); OutputLine("Subscribed to the 'nameChanged' signal."); } else { OutputLine("Join Session was unsuccessful."); } } catch (Exception ex) { OutputLine("Errors were produced while establishing the application."); QStatus status = AllJoynException.GetErrorCode(ex.HResult); busAtt = null; } }); task.Start(); } }
/// <summary> /// Initializes the global bus attachment /// </summary> private void InitializeAllJoyn() { InterfaceDescription[] iface = new InterfaceDescription[1]; this.Bus = new BusAttachment("SRPSecurityServiceA", true, 4); this.Bus.CreateInterface(App.InterfaceName, iface, true); iface[0].AddMethod("Ping", "s", "s", "inStr,outStr", 0, string.Empty); iface[0].Activate(); this.BusObject = new SecureBusObject(this.Bus, iface); this.Listeners = new Listeners(this.Bus); this.Listeners.NameOwnerChange += this.NameOwnerChanged; this.Listeners.AcceptSessionJoiner += this.AcceptSessionJoiner; this.Bus.RegisterBusListener(this.Listeners); this.Bus.Start(); // Enable security. // Note the location of the keystore file has been specified and the // isShared parameter is being set to true. So this keystore file can // be used by multiple applications. this.AuthenticationListener = new AuthListener(this.Bus); this.AuthenticationListener.RequestCredentials += this.AuthRequestCredentals; this.Bus.EnablePeerSecurity( App.SecurityType, this.AuthenticationListener, "/.alljoyn_keystore/s_central.ks", true); this.Bus.ConnectAsync(App.ConnectSpec).AsTask().Wait(); SessionOpts sessionOpts = new SessionOpts( TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY); ushort[] portOut = new ushort[1]; this.Bus.BindSessionPort(App.ServicePort, portOut, sessionOpts, this.Listeners); try { uint flags = (uint)RequestNameType.DBUS_NAME_REPLACE_EXISTING + (uint)RequestNameType.DBUS_NAME_DO_NOT_QUEUE; this.Bus.RequestName(App.ServiceName, flags); } catch (COMException ce) { QStatus exceptionStatus = AllJoynException.GetErrorCode(ce.HResult); string error = string.Format( "Well known name '{0}' was not accepted. QStatus = 0x{1:X}", App.ServiceName, exceptionStatus); System.Diagnostics.Debug.WriteLine(error); App.OutputLine(error); } this.Bus.AdvertiseName(App.ServiceName, sessionOpts.TransportMask); App.OutputLine(string.Format("Name is being advertised as: '{0}'.", App.ServiceName)); }
public bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { Assert.AreEqual(77, sessionPort); AcceptSessionJoinerCalled = true; return(true); }
/// <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(); } }
/** * Compare SessionOpts * * @param one the SessionOpts being compared to * @param other the SessionOpts being compared against * @return true if all of the SessionOpts parameters are the same * */ public static int Compare(SessionOpts one, SessionOpts other) { return(alljoyn_sessionopts_cmp(one._sessionOpts, other._sessionOpts)); }
/// <summary> /// Do the stuff required to join the session. /// </summary> /// <returns>True if successfully joined the session.</returns> private async Task<bool> JoinSessionAsync() { bool returnValue = true; SessionOpts opts = new SessionOpts( ClientGlobals.SessionProps.TrType, ClientGlobals.SessionProps.IsMultiPoint, ClientGlobals.SessionProps.PrType, ClientGlobals.SessionProps.TmType); SessionOpts[] opts_out = new SessionOpts[1]; App app = Application.Current as App; JoinSessionResult result = await this.Bus.JoinSessionAsync( ClientGlobals.ServiceName, ClientGlobals.SessionProps.SessionPort, app.Listeners, opts, opts_out, null); string message = string.Format("Join Session status = {0}.", result.Status.ToString()); App.OutputLine(message); if (QStatus.ER_OK == result.Status) { this.SessionId = result.SessionId; message = string.Format("SessionId='{0}'.", result.SessionId); App.OutputLine(message); } else { string errorMessage = string.Format("Join session failed with error {0:X}.", result.Status); App.OutputLine(errorMessage); returnValue = false; } return returnValue; }
/** * Accept or reject an incoming JoinSession request. The session does not exist until this * after this function returns. * * This callback is only used by session creators. Therefore it is only called on listeners * passed to BusAttachment.BindSessionPort. * * @param sessionPort Session port that was joined. * @param joiner Unique name of potential joiner. * @param opts Session options requested by the joiner. * @return Return true if JoinSession request is accepted. false if rejected. */ protected virtual bool AcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { return(false); }
/// <summary> /// Accept or reject an incoming JoinSession request. The session does not exist until /// after this function returns. /// </summary> /// <param name="sessionPort">Session port that was joined.</param> /// <param name="joiner">Unique name of potential joiner.</param> /// <param name="opts">Session options requested by the joiner.</param> /// <returns>Return true if JoinSession request is accepted. false if rejected</returns> public bool SessionPortListenerAcceptSessionJoiner(ushort sessionPort, string joiner, SessionOpts opts) { if (ServicePort == sessionPort) { this.DebugPrint("Accepting join session request from " + joiner + " (opts.proximity=" + opts.Proximity + ", opts.traffic=" + opts.Traffic + ", opts.transports=" + opts.TransportMask + ")"); return true; } else { this.DebugPrint("Rejecting join attempt on unexpected session port " + sessionPort); return false; } }