/** * Implementation of the functionality related to disconnecting our app from the AllJoyn bus. We * expect that this method will only be called in the context of the AllJoyn bus handler thread. * We expect that this method will only be called in the context of the AllJoyn bus handler * thread; and while we are in the CONNECTED state. */ private boolean doDisconnect() { Log.i(TAG, "doDisonnect()"); assert (mBusAttachmentState == BusAttachmentState.CONNECTED); mBus.unregisterBusListener(mBusListener); mBus.disconnect(); mBusAttachmentState = BusAttachmentState.DISCONNECTED; return true; }
/** * This method will be called by the AJ bus when a notification is received * * @see org.alljoyn.ns.transport.interfaces.NotificationTransport#notify(int, int, short, String, * String, byte[], String, Map, Map, TransportNotificationText[]) */ @Override public void notify( int version, int msgId, short messageType, String deviceId, String deviceName, byte[] appId, String appName, Map<Integer, Variant> attributes, Map<String, String> customAttributes, TransportNotificationText[] text) { Transport transport = Transport.getInstance(); BusAttachment busAttachment = transport.getBusAttachment(); busAttachment.enableConcurrentCallbacks(); try { GenericLogger logger = NativePlatformFactory.getPlatformObject().getNativeLogger(); try { String sender = busAttachment.getMessageContext().sender; logger.debug( TAG, "Received notification from: '" + sender + "' by '" + servicePath + "' object, notification id: '" + msgId + "', handling"); logger.debug( TAG, "Forwarding the received notification id: '" + msgId + "' to PayloadAdapter"); PayloadAdapter.receivePayload( version, msgId, sender, messageType, deviceId, deviceName, appId, appName, attributes, customAttributes, text); } catch (NotificationServiceException nse) { logger.error(TAG, "Failed to read the received notification, Error: " + nse.getMessage()); } } catch (NativePlatformFactoryException npfe) { System.out.println(TAG + ": Unexpected error occured: " + npfe.getMessage()); } } // notify
/** Implementation of the functionality related to joining an existing remote session. */ private void doLeaveSession() { Log.i(TAG, "doLeaveSession()"); if (mJoinedToSelf == false) { mBus.leaveSession(mUseSessionId); } mUseSessionId = -1; mJoinedToSelf = false; mUseChannelState = UseChannelState.IDLE; mChatApplication.useSetChannelState(mUseChannelState); }
/** * Implementation of the functionality related to discovering remote apps which are hosting chat * channels. We expect that this method will only be called in the context of the AllJoyn bus * handler thread; and while we are in the CONNECTED state. Since this is a core bit of * functionalty for the "use" side of the app, we always do this at startup. */ private void doStartDiscovery() { Log.i(TAG, "doStartDiscovery()"); assert (mBusAttachmentState == BusAttachmentState.CONNECTED); Status status = mBus.findAdvertisedName(NAME_PREFIX); if (status == Status.OK) { mBusAttachmentState = BusAttachmentState.DISCOVERING; return; } else { mActivity.alljoynError( MainActivity.Module.USE, "Unable to start finding advertised names: (" + status + ")"); return; } }
/** * Implementation of the functionality related to connecting our app to the AllJoyn bus. We expect * that this method will only be called in the context of the AllJoyn bus handler thread; and * while we are in the DISCONNECTED state. */ private void doConnect() { Log.i(TAG, "doConnect()"); org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(getApplicationContext()); assert (mBusAttachmentState == BusAttachmentState.DISCONNECTED); mBus.useOSLogging(true); mBus.setDebugLevel("ALLJOYN_JAVA", 7); mBus.registerBusListener(mBusListener); mBus.registerAboutListener(mTestListener); /* * To make a service available to other AllJoyn peers, first * register a BusObject with the BusAttachment at a specific * object path. Our service is implemented by the ChatService * BusObject found at the "/chatService" object path. */ // Status status = mBus.registerBusObject(mChatService, OBJECT_PATH); // if (Status.OK != status) { // mChatApplication.alljoynError(ChatApplication.Module.HOST, "Unable to register the chat bus // object: (" + status + ")"); // return; // } Status status = mBus.connect(); if (status != Status.OK) { mActivity.alljoynError( MainActivity.Module.GENERAL, "Unable to connect to the bus: (" + status + ")"); return; } status = mBus.registerSignalHandlers(this); if (status != Status.OK) { mActivity.alljoynError( MainActivity.Module.GENERAL, "Unable to register signal handlers: (" + status + ")"); return; } mBusAttachmentState = BusAttachmentState.CONNECTED; }
public void handleMessage(Message msg) { switch (msg.what) { case (CONNECT): { org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(getApplicationContext()); mBus = new BusAttachment(getPackageName(), BusAttachment.RemoteMessage.Receive); mBus.registerBusListener( new BusListener() { @Override public void foundAdvertisedName(String name, short transport, String namePrefix) { logInfo( String.format( "MyBusListener.foundAdvertisedName(%s, 0x%04x, %s)", name, transport, namePrefix)); /* * This client will only join the first service that it sees advertising * the indicated well-known name. If the program is already a member of * a session (i.e. connected to a service) we will not attempt to join * another session. * It is possible to join multiple session however joining multiple * sessions is not shown in this sample. */ if (!mIsConnected) { Message msg = obtainMessage(JOIN_SESSION, name); sendMessage(msg); } } }); // Connect the BusAttachment with the bus. Status status = mBus.connect(); logStatus("BusAttachment.connect()", status); if (Status.OK != status) { finish(); return; } status = mBus.findAdvertisedName(SERVICE_NAME); logStatus("BusAttachement.findAdvertisedName()", status); if (Status.OK != status) { finish(); return; } break; } case (JOIN_SESSION): { /* * If discovery is currently being stopped don't join to any other sessions. */ if (mIsStoppingDiscovery) { break; } /* * In order to join the session, we need to provide the well-known * contact port. This is pre-arranged between both sides as part * of the definition of the chat service. As a result of joining * the session, we get a session identifier which we must use to * identify the created session communication channel whenever we * talk to the remote side. */ short contactPort = CONTACT_PORT; SessionOpts sessionOpts = new SessionOpts(); Mutable.IntegerValue sessionId = new Mutable.IntegerValue(); Status status = mBus.joinSession( (String) msg.obj, contactPort, sessionId, sessionOpts, new SessionListener() { @Override public void sessionLost(int sessionId, int reason) { mIsConnected = false; logInfo( String.format( "MyBusListener.sessionLost(sessionId = %d, reason = %d)", sessionId, reason)); mHandler.sendEmptyMessage(MESSAGE_START_PROGRESS_DIALOG); } }); logStatus("BusAttachment.joinSession()", status); if (status == Status.OK) { mProxyObj = mBus.getProxyBusObject( SERVICE_NAME, "/testProperties", sessionId.value, new Class<?>[] {PropertiesInterface.class}); mPropertiesInterface = mProxyObj.getInterface(PropertiesInterface.class); mSessionId = sessionId.value; mIsConnected = true; mHandler.sendEmptyMessage(MESSAGE_STOP_PROGRESS_DIALOG); } break; } case (DISCONNECT): { mIsStoppingDiscovery = true; if (mIsConnected) { Status status = mBus.leaveSession(mSessionId); logStatus("BusAttachment.leaveSession()", status); } mBus.disconnect(); getLooper().quit(); break; } case (GET_BACKGROUND_COLOR_PROPERTY): { if (!mIsConnected) { break; } try { String backgroundColor = mPropertiesInterface.getBackGroundColor(); mHandler.sendMessage( mHandler.obtainMessage(MESSAGE_UPDATE_BACKGROUND_COLOR, backgroundColor)); } catch (BusException e) { } break; } case (SET_BACKGROUND_COLOR_PROPERTY): { if (!mIsConnected) { break; } try { mPropertiesInterface.setBackGroundColor((String) msg.obj); mHandler.sendMessage( mHandler.obtainMessage(MESSAGE_UPDATE_BACKGROUND_COLOR, (String) msg.obj)); } catch (BusException e) { logException(getString(R.string.get_properties_error), e); } break; } case (GET_TEXT_SIZE_PROPERTY): { if (!mIsConnected) { break; } try { int textSize = mPropertiesInterface.getTextSize(); Message textMsg = mHandler.obtainMessage(MESSAGE_UPDATE_TEXT_SIZE); textMsg.arg1 = textSize; mHandler.sendMessage(textMsg); } catch (BusException e) { logException(getString(R.string.get_properties_error), e); } break; } case (SET_TEXT_SIZE_PROPERTY): { if (!mIsConnected) { break; } try { mPropertiesInterface.setTextSize(msg.arg1); Message textMsg = mHandler.obtainMessage(MESSAGE_UPDATE_TEXT_SIZE); textMsg.arg1 = msg.arg1; mHandler.sendMessage(textMsg); } catch (BusException e) { logException(getString(R.string.get_properties_error), e); } break; } default: break; } }
public static void main(String[] args) { class MyBusListener extends BusListener { public void foundAdvertisedName(String name, short transport, String namePrefix) { System.out.println( String.format( "BusListener.foundAdvertisedName(%s, %d, %s)", name, transport, namePrefix)); short contactPort = CONTACT_PORT; SessionOpts sessionOpts = new SessionOpts(); sessionOpts.traffic = SessionOpts.TRAFFIC_MESSAGES; sessionOpts.isMultipoint = false; sessionOpts.proximity = SessionOpts.PROXIMITY_ANY; sessionOpts.transports = SessionOpts.TRANSPORT_ANY; Mutable.IntegerValue sessionId = new Mutable.IntegerValue(); mBus.enableConcurrentCallbacks(); Status status = mBus.joinSession(name, contactPort, sessionId, sessionOpts, new SessionListener()); if (status != Status.OK) { return; } System.out.println( String.format("BusAttachement.joinSession successful sessionId = %d", sessionId.value)); } public void nameOwnerChanged(String busName, String previousOwner, String newOwner) { if ("com.my.well.known.name".equals(busName)) { System.out.println( "BusAttachement.nameOwnerChagned(" + busName + ", " + previousOwner + ", " + newOwner); } } } mBus = new BusAttachment("AppName", BusAttachment.RemoteMessage.Receive); BusListener listener = new MyBusListener(); mBus.registerBusListener(listener); Status status = mBus.connect(); if (status != Status.OK) { return; } System.out.println("BusAttachment.connect successful"); SampleSignalHandler mySignalHandlers = new SampleSignalHandler(); status = mBus.registerSignalHandlers(mySignalHandlers); if (status != Status.OK) { return; } System.out.println("BusAttachment.registerSignalHandlers successful"); status = mBus.findAdvertisedName("com.my.well.known.name"); if (status != Status.OK) { return; } System.out.println("BusAttachment.findAdvertisedName successful " + "com.my.well.known.name"); while (true) { try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("Program interupted"); } } }
@Override public void handleMessage(Message msg) { switch (msg.what) { /* Connect to a remote instance of an object implementing the BasicInterface. */ case CONNECT: { org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(getApplicationContext()); /* * All communication through AllJoyn begins with a BusAttachment. * * A BusAttachment needs a name. The actual name is unimportant except for internal * security. As a default we use the class name as the name. * * By default AllJoyn does not allow communication between devices (i.e. bus to bus * communication). The second argument must be set to Receive to allow communication * between devices. */ mBus = new BusAttachment(getPackageName(), BusAttachment.RemoteMessage.Receive); /* * Create a bus listener class */ mBus.registerBusListener( new BusListener() { @Override public void foundAdvertisedName( String name, short transport, String namePrefix) { logInfo( String.format( "MyBusListener.foundAdvertisedName(%s, 0x%04x, %s)", name, transport, namePrefix)); /* * This client will only join the first service that it sees advertising * the indicated well-known name. If the program is already a member of * a session (i.e. connected to a service) we will not attempt to join * another session. * It is possible to join multiple session however joining multiple * sessions is not shown in this sample. */ if (!mIsConnected) { Message msg = obtainMessage(JOIN_SESSION); msg.arg1 = transport; msg.obj = name; sendMessage(msg); } } }); /* To communicate with AllJoyn objects, we must connect the BusAttachment to the bus. */ Status status = mBus.connect(); logStatus("BusAttachment.connect()", status); if (Status.OK != status) { finish(); return; } /* * Now find an instance of the AllJoyn object we want to call. We start by looking for * a name, then connecting to the device that is advertising that name. * * In this case, we are looking for the well-known SERVICE_NAME. */ status = mBus.findAdvertisedName(SERVICE_NAME); logStatus( String.format("BusAttachement.findAdvertisedName(%s)", SERVICE_NAME), status); if (Status.OK != status) { finish(); return; } break; } case (JOIN_SESSION): { /* * If discovery is currently being stopped don't join to any other sessions. */ if (mIsStoppingDiscovery) { break; } /* * In order to join the session, we need to provide the well-known * contact port. This is pre-arranged between both sides as part * of the definition of the chat service. As a result of joining * the session, we get a session identifier which we must use to * identify the created session communication channel whenever we * talk to the remote side. */ short contactPort = CONTACT_PORT; SessionOpts sessionOpts = new SessionOpts(); sessionOpts.transports = (short) msg.arg1; Mutable.IntegerValue sessionId = new Mutable.IntegerValue(); Status status = mBus.joinSession( (String) msg.obj, contactPort, sessionId, sessionOpts, new SessionListener() { @Override public void sessionLost(int sessionId, int reason) { mIsConnected = false; logInfo( String.format( "MyBusListener.sessionLost(sessionId = %d, reason = %d)", sessionId, reason)); mHandler.sendEmptyMessage(MESSAGE_ALLJOYN_START_PROGRESS_DIALOG); } }); logStatus("BusAttachment.joinSession() - sessionId: " + sessionId.value, status); if (status == Status.OK) { /* * To communicate with an AllJoyn object, we create a ProxyBusObject. * A ProxyBusObject is composed of a name, path, sessionID and interfaces. * * This ProxyBusObject is located at the well-known SERVICE_NAME, under path * "/sample", uses sessionID of CONTACT_PORT, and implements the BasicInterface. */ mProxyObj = mBus.getProxyBusObject( SERVICE_NAME, OBJ_PATH, sessionId.value, new Class<?>[] {BasicInterface.class}); /* We make calls to the methods of the AllJoyn object through one of its interfaces. */ mBasicInterface = mProxyObj.getInterface(BasicInterface.class); mSessionId = sessionId.value; mIsConnected = true; mHandler.sendEmptyMessage(MESSAGE_ALLJOYN_STOP_PROGRESS_DIALOG); } break; } /* Release all resources acquired in the connect. */ case DISCONNECT: { mIsStoppingDiscovery = true; if (mIsConnected) { Status status = mBus.leaveSession(mSessionId); logStatus("BusAttachment.leaveSession()", status); } mBus.disconnect(); getLooper().quit(); break; } /* * Call the service's Cat method through the ProxyBusObject. * * This will also print the String that was sent to the service and the String that was * received from the service to the user interface. */ case GET_TOPIC: { try { if (mBasicInterface != null) { // sendUiMessage(MESSAGE_PING, msg.obj + " and " + msg.obj); // String reply = mBasicInterface.cat((String) msg.obj, (String) msg.obj); String reply = mBasicInterface.get_topic((String) msg.obj); sendUiMessage(MESSAGE_ALLJOYN_GETTOPIC_REPLY, reply); } } catch (BusException ex) { logException("BasicInterface.cat()", ex); } break; } default: break; } }
@Override public void handleMessage(Message msg) { switch (msg.what) { /* * Connect to a remote instance of an object implementing the * SimpleInterface. */ case CONNECT: { mBus = new BusAttachment(getPackageName(), BusAttachment.RemoteMessage.Receive); mBus.registerBusListener( new BusListener() { @Override public void foundAdvertisedName(String name, short transport, String namePrefix) { logInfo( String.format( "MyBusListener.foundAdvertisedName(%s, 0x%04x, %s)", name, transport, namePrefix)); if (!mIsConnected) { Message msg = obtainMessage(JOIN_SESSION, name); sendMessage(msg); } } }); Status status = mBus.connect(); logStatus("BusAttachment.connect()", status); if (Status.OK != status) { finish(); return; } status = mBus.findAdvertisedName(SERVICE_NAME); logStatus(String.format("BusAttachement.findAdvertisedName(%s)", SERVICE_NAME), status); if (Status.OK != status) { finish(); return; } break; } case (JOIN_SESSION): { if (mIsStoppingDiscovery) { break; } short contactPort = CONTACT_PORT; SessionOpts sessionOpts = new SessionOpts(); Mutable.IntegerValue sessionId = new Mutable.IntegerValue(); Status status = mBus.joinSession( (String) msg.obj, contactPort, sessionId, sessionOpts, new SessionListener() { @Override public void sessionLost(int sessionId) { mIsConnected = false; logInfo(String.format("MyBusListener.sessionLost(%d)", sessionId)); mHandler.sendEmptyMessage(MESSAGE_START_PROGRESS_DIALOG); } }); logStatus("BusAttachment.joinSession() - sessionId: " + sessionId.value, status); if (status == Status.OK) { mProxyObj = mBus.getProxyBusObject( SERVICE_NAME, "/SimpleService", sessionId.value, new Class<?>[] {SimpleInterface.class}); mSimpleInterface = mProxyObj.getInterface(SimpleInterface.class); mSessionId = sessionId.value; mIsConnected = true; mHandler.sendEmptyMessage(MESSAGE_STOP_PROGRESS_DIALOG); try { starttime = System.currentTimeMillis(); timer_flag = 1; System.out.println("In Client!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); System.out.println("In Client!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); System.out.println("In Client!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); System.out.println("In Client!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); System.out.println("In Client!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); System.out.println("In Client!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); System.out.println("In Client!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); System.out.println("In Client!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); double[] numbers = new double[capacity]; int clientid = mSimpleInterface.getClientID(); System.out.println("Client ID is " + clientid); System.out.println("Client ID is " + clientid); System.out.println("Client ID is " + clientid); System.out.println("Client ID is " + clientid); System.out.println("Client ID is " + clientid); System.out.println("Client ID is " + clientid); if (clientid != -1) { double frequency = mSimpleInterface.getFrequencyToRunAt(); System.out.println("Frequency is " + frequency); System.out.println("Frequency is " + frequency); System.out.println("Frequency is " + frequency); System.out.println("Frequency is " + frequency); System.out.println("Frequency is " + frequency); System.out.println("Frequency is " + frequency); // then set scaling governor to userspace and then write the frequency to the file // next 13 lines commented out for facebook hackathon /*String f=(new Integer((int)frequency)).toString(); String min="echo 100000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq"; String max="echo 1400000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq"; String temp="echo "+f+" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed"; Process p; p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); os.writeBytes("echo userspace > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"+"\n"); os.writeBytes(max+"\n"); os.writeBytes(min+"\n"); os.writeBytes(temp+"\n"); os.writeBytes("exit\n"); os.flush();*/ int no = mSimpleInterface .giveImageData(); // no specifies how many times the giveActualImageData // needs to be called int size_of_each_chunk = mSimpleInterface.getSizeOfEachChunk(); // get this value from the server int[] imageData = new int[no * size_of_each_chunk]; // for(int e=0;e<12;e++) // { for (int i = 0; i < no; i++) { System.out.println("hahaha"); int[] data_from_server = new int[size_of_each_chunk]; data_from_server = mSimpleInterface.giveActualImageData(clientid, i); System.arraycopy( data_from_server, 0, imageData, i * size_of_each_chunk, data_from_server.length); } // } // start smoothing // for( int e=0;e<12;e++) // { for (int k = 0; k < 50; k++) { System.out.println("client iteration no. " + k + " and freq is " + frequency); for (int i = 1; i < imageData.length - 1; i++) { // first extract argb values from pixels int a0 = Color.alpha(imageData[i - 1]); int r0 = Color.red(imageData[i - 1]); int g0 = Color.green(imageData[i - 1]); int b0 = Color.blue(imageData[i - 1]); int a = Color.alpha(imageData[i]); int r = Color.red(imageData[i]); int g = Color.green(imageData[i]); int b = Color.blue(imageData[i]); int a1 = Color.alpha(imageData[i + 1]); int r1 = Color.red(imageData[i + 1]); int g1 = Color.green(imageData[i + 1]); int b1 = Color.blue(imageData[i + 1]); int afinal = (a0 + a + a1) / 3; int rfinal = (r0 + r + r1) / 3; int gfinal = (g0 + g + g1) / 3; int bfinal = (b0 + b + b1) / 3; imageData[i] = Color.argb(afinal, rfinal, gfinal, bfinal); } // facebook hackathon // every 10 iterations you can send the smoothed data back to the server if (k % 5 == 0) { for (int i = 0; i < no; i++) { int[] localarray = new int[size_of_each_chunk]; System.arraycopy( imageData, i * size_of_each_chunk, localarray, 0, size_of_each_chunk); mSimpleInterface.takeImageData(localarray, clientid, i); } } } // this is the loop to repeat smoothing 20 30 40 50 times // } // for(int e=0;e<12;e++) // { // for(int i=0;i<no;i++) // { // int[] localarray=new int[size_of_each_chunk]; // System.arraycopy(imageData, i*size_of_each_chunk, localarray, 0, // size_of_each_chunk); // mSimpleInterface.takeImageData(localarray,clientid,i); // } // } timer_flag = 0; File file1 = new File(Environment.getExternalStorageDirectory(), "done_file"); file1.createNewFile(); } // end if clientid != -1 } catch (Exception e) { // TODO Auto-generated catch block System.out.println("damn an error occurred"); e.printStackTrace(); } } break; } case DISCONNECT: { mIsStoppingDiscovery = true; if (mIsConnected) { Status status = mBus.leaveSession(mSessionId); logStatus("BusAttachment.leaveSession()", status); } mBus.disconnect(); getLooper().quit(); break; } case PING: { try { if (mSimpleInterface != null) { sendUiMessage(MESSAGE_PING, msg.obj); int[] values = {2, 4, 6, 8, 10, 255, 1024, 1056, 0, 9999}; double[] array = new double[capacity]; for (int t = 0; t < capacity; t++) array[t] = (int) (Math.random() * 10); String reply = null; for (int i = 0; i < no_of_times; i++) reply = mSimpleInterface.Ping(array, "client2"); sendUiMessage(MESSAGE_PING_REPLY, reply); } } catch (BusException ex) { logException("SimpleInterface.Ping()", ex); } break; } default: break; } }
@Override public void handleMessage(Message msg) { switch (msg.what) { /* Connect to the bus and start our service. */ case CONNECT: { // System.out.println("\n\n\n\n\n\n\nService is getting started!\n\n\n\n\n\n"); mBus = new BusAttachment(getPackageName(), BusAttachment.RemoteMessage.Receive); mBus.registerBusListener(new BusListener()); Status status = mBus.registerBusObject(mSimpleService, "/SimpleService"); logStatus("BusAttachment.registerBusObject()", status); if (status != Status.OK) { finish(); return; } status = mBus.connect(); logStatus("BusAttachment.connect()", status); if (status != Status.OK) { finish(); return; } Mutable.ShortValue contactPort = new Mutable.ShortValue(CONTACT_PORT); SessionOpts sessionOpts = new SessionOpts(); sessionOpts.traffic = SessionOpts.TRAFFIC_MESSAGES; sessionOpts.isMultipoint = false; sessionOpts.proximity = SessionOpts.PROXIMITY_ANY; sessionOpts.transports = SessionOpts.TRANSPORT_ANY; status = mBus.bindSessionPort( contactPort, sessionOpts, new SessionPortListener() { @Override public boolean acceptSessionJoiner( short sessionPort, String joiner, SessionOpts sessionOpts) { if (sessionPort == CONTACT_PORT) { return true; } else { return false; } } }); logStatus( String.format( "BusAttachment.bindSessionPort(%d, %s)", contactPort.value, sessionOpts.toString()), status); if (status != Status.OK) { finish(); return; } int flag = BusAttachment.ALLJOYN_REQUESTNAME_FLAG_REPLACE_EXISTING | BusAttachment.ALLJOYN_REQUESTNAME_FLAG_DO_NOT_QUEUE; status = mBus.requestName(SERVICE_NAME, flag); logStatus( String.format("BusAttachment.requestName(%s, 0x%08x)", SERVICE_NAME, flag), status); if (status == Status.OK) { status = mBus.advertiseName(SERVICE_NAME, SessionOpts.TRANSPORT_ANY); logStatus(String.format("BusAttachement.advertiseName(%s)", SERVICE_NAME), status); if (status != Status.OK) { status = mBus.releaseName(SERVICE_NAME); logStatus(String.format("BusAttachment.releaseName(%s)", SERVICE_NAME), status); finish(); return; } } break; } case DISCONNECT: { mBus.unregisterBusObject(mSimpleService); mBus.disconnect(); mClientBusHandler.getLooper().quit(); break; } default: break; } }
/** Implementation of the functionality related to joining an existing local or remote session. */ private void doJoinSession() { Log.i(TAG, "doJoinSession()"); /* * There is a relatively non-intuitive behavior of multipoint sessions * that one needs to grok in order to understand the code below. The * important thing to uderstand is that there can be only one endpoint * for a multipoint session in a particular bus attachment. This * endpoint can be created explicitly by a call to joinSession() or * implicitly by a call to bindSessionPort(). An attempt to call * joinSession() on a session port we have created with bindSessionPort() * will result in an error. * * When we call bindSessionPort(), we do an implicit joinSession() and * thus signals (which correspond to our chat messages) will begin to * flow from the hosted chat channel as soon as we begin to host a * corresponding session. * * To achieve sane user interface behavior, we need to block those * signals from the implicit join done by the bind until our user joins * the bound chat channel. If we do not do this, the chat messages * from the chat channel hosted by the application will appear in the * chat channel joined by the application. * * Since the messages flow automatically, we can accomplish this by * turning a filter on and off in the chat signal handler. So if we * detect that we are hosting a channel, and we find that we want to * join the hosted channel we turn the filter off. * * We also need to be able to send chat messages to the hosted channel. * This means we need to point the mChatInterface at the session ID of * the hosted session. There is another complexity here since the * hosted session doesn't exist until a remote session has joined. * This means that we don't have a session ID to use to create a * SignalEmitter until a remote device does a joinSession on our * hosted session. This, in turn, means that we have to create the * SignalEmitter after we get a sessionJoined() callback in the * SessionPortListener passed into bindSessionPort(). We chose to * create the signal emitter for this case in the sessionJoined() * callback itself. Note that this hosted channel signal emitter * must be distinct from one constructed for the usual joinSession * since a hosted channel may have a remote device do a join at any * time, even when we are joined to another session. If they were * not separated, a remote join on the hosted session could redirect * messages from the joined session unexpectedly. * * So, to summarize, these next few lines handle a relatively complex * case. When we host a chat channel, we do a bindSessionPort which * *enables* the creation of a session. As soon as a remote device * joins the hosted chat channel, a session is actually created, and * the SessionPortListener sessionJoined() callback is fired. At that * point, we create a separate SignalEmitter using the hosted session's * sessionId that we can use to send chat messages to the channel we * are hosting. As soon as the session comes up, we begin receiving * chat messages from the session, so we need to filter them until the * user joins the hosted chat channel. In a separate timeline, the * user can decide to join the chat channel she is hosting. She can * do so either before or after the corresponding session has been * created as a result of a remote device joining the hosted session. * If she joins the hosted channel before the underlying session is * created, her chat messages will be discarded. If she does so after * the underlying session is created, there will be a session emitter * waiting to use to send chat messages. In either case, the signal * filter will be turned off in order to listen to remote chat * messages. */ if (mHostChannelState != HostChannelState.IDLE) { if (mChatApplication.useGetChannelName().equals(mChatApplication.hostGetChannelName())) { mUseChannelState = UseChannelState.JOINED; mChatApplication.useSetChannelState(mUseChannelState); mJoinedToSelf = true; return; } } /* * We depend on the user interface and model to work together to provide * a reasonable name. */ String wellKnownName = NAME_PREFIX + "." + mChatApplication.useGetChannelName(); /* * Since we can act as the host of a channel, we know what the other * side is expecting to see. */ short contactPort = CONTACT_PORT; SessionOpts sessionOpts = new SessionOpts( SessionOpts.TRAFFIC_MESSAGES, true, SessionOpts.PROXIMITY_ANY, SessionOpts.TRANSPORT_ANY); Mutable.IntegerValue sessionId = new Mutable.IntegerValue(); Status status = mBus.joinSession( wellKnownName, contactPort, sessionId, sessionOpts, new SessionListener() { /** * This method is called when the last remote participant in the chat session leaves * for some reason and we no longer have anyone to chat with. * * <p>In the class documentation for the BusListener note that it is a requirement for * this method to be multithread safe. This is accomplished by the use of a monitor on * the ChatApplication as exemplified by the synchronized attribute of the * removeFoundChannel method there. */ public void sessionLost(int sessionId, int reason) { Log.i( TAG, "BusListener.sessionLost(sessionId=" + sessionId + ",reason=" + reason + ")"); mChatApplication.alljoynError( ChatApplication.Module.USE, "The chat session has been lost"); mUseChannelState = UseChannelState.IDLE; mChatApplication.useSetChannelState(mUseChannelState); } }); if (status == Status.OK) { Log.i(TAG, "doJoinSession(): use sessionId is " + mUseSessionId); mUseSessionId = sessionId.value; } else { mChatApplication.alljoynError( ChatApplication.Module.USE, "Unable to join chat session: (" + status + ")"); return; } SignalEmitter emitter = new SignalEmitter(mChatService, mUseSessionId, SignalEmitter.GlobalBroadcast.Off); mChatInterface = emitter.getInterface(ChatInterface.class); mUseChannelState = UseChannelState.JOINED; mChatApplication.useSetChannelState(mUseChannelState); }
/** * Implementation of the functionality related to stopping discovery of remote apps which are * hosting chat channels. */ private void doStopDiscovery() { Log.i(TAG, "doStopDiscovery()"); assert (mBusAttachmentState == BusAttachmentState.CONNECTED); mBus.cancelFindAdvertisedName(NAME_PREFIX); mBusAttachmentState = BusAttachmentState.CONNECTED; }