diff --git a/.gitmodules b/.gitmodules
index f9ecabc0..6aa63c6d 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -22,3 +22,6 @@
[submodule "android/libs/armeabi"]
path = android/libs/armeabi
url = https://github.com/SKKU-ESLAB/ant-android-libs-armeabi.git
+[submodule "subprojects/selective-connection"]
+ path = subprojects/selective-connection
+ url = https://github.com/SKKU-ESLAB/selective-connection
diff --git a/subprojects/sc/.gitignore b/subprojects/sc/.gitignore
deleted file mode 100644
index cafe80e5..00000000
--- a/subprojects/sc/.gitignore
+++ /dev/null
@@ -1,26 +0,0 @@
-tags
-cscope
-cscope.out
-.vscode
-*.o
-bin/*
-dhcpd.conf
-!bin/.git_empty_file
-SelectiveConnection.IAB
-SelectiveConnection.IAD
-SelectiveConnection.IMB
-SelectiveConnection.IMD
-SelectiveConnection.PFI
-SelectiveConnection.PO
-SelectiveConnection.PR
-SelectiveConnection.PRI
-SelectiveConnection.PS
-*.iml
-.gradle
-android/local.properties
-android/.idea
-.DS_Store
-android/build
-android/captures
-.externalNativeBuild
-*.swp
diff --git a/subprojects/sc/README.md b/subprojects/sc/README.md
deleted file mode 100644
index 6807cfa2..00000000
--- a/subprojects/sc/README.md
+++ /dev/null
@@ -1,128 +0,0 @@
-# P2PForYourThings
-C++ APIs for you to easily setup and communicate via smart P2P (using available p2p modules among Wi-Fi Direct / Bluetooth / Bluetooth LE)
-
-## Supported Devices
-* Raspberry-pi 3
-* NVIDIA Jetson-TX1
-
-# Android
-[P2PForYourThings-android](https://github.com/sinban04/P2PForYourThings-android)
-
-
-# Quick Start
-## How to Get the Source Code
-```
-$ git clone https://github.com/sinban04/P2PForYourThings.git
-$ cd P2PForYourThings
-```
-
-## Pre-requisite
-- Install Bluetooth library
-```
-$ sudo apt-get install libbluetooth-dev
-```
-
-Check your bluetooth version and if it is equal to or higher than 5.0, then
-```
-$ sudo vi /etc/systemd/system/dbus-org.bluez.service
-
-ExecStart=/usr/lib/bluetooth/bluetoothd --compat
-
-$ sudo systemctl daemon-reload
-$ sudo systemctl restart bluetooth
-$ sudo chmod 777 /var/run/sdp
-```
-
-- Check the wifi module support p2p
-```
-$ iw list
-```
-
-- Modify the wpa_supplicant.conf (```/etc/wpa_supplicant/wpa_supplicant.conf```)
-Add two parameters
-
-> update_config=1
->
-> driver_param=p2p_device=1
-
-- Install UDHCPD for wifi-direct
-```
-$ sudo apt-get install udhcpd
-$ sudo touch /var/lib/misc/udhcpd.leases
-```
-
-- Set ```wpa_supplicant``` configuration
-```
-sudo wpa_supplicant -iwlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf
-```
-
-
-## How to Build the Source Code
-```
-// No need to make the new directories now (Already exists)
-$ mkdir bin obj ./device/obj
-$ make
-```
-Then you can find the binary file of the communicator test example,
-which is in the ```tests/``` directory.
-
-## How to Run
-```
-$ sudo ./bin/test
-```
-
-# Notes
-## Bluetooth Issues
-### Bluetooth Version Compatibility
-Check your bluetooth version using
-```
-$ sudo vi /etc/systemd/system/dbus-org.bluez.service
-
-ExecStart=/usr/lib/bluetooth/bluetoothd --compat
-
-$ sudo systemctl daemon-reload
-$ sudo systemctl restart bluetooth
-$ sudo chmod 777 /var/run/sdp
-```
-
-### Check the bluetooth HCI interface
-```
-$ hciconfig -a
-```
-
-### Change hci0 interface to Scan Mode
-Set page scan and inquiry can (Discoverable)
-```
-$ sudo hciconfig hci0 piscan
-```
-
-### Change the hci0 interface name
-e.g., change the name of the bluetooth interface to ```pi```
-```
-$ sudo hciconfig hci0 name pi
-```
-
-### Turn on the interface
-```
-$ sudo hciconfig hci0 up
-```
-
-### Turn on the bluetoothd (For the case, it's off)
-```
-sudo service bluetooth start
-```
-When the bluetooth.target is masked, unmask it
-```
-$ sudo systemctl unmask bluetooth
-```
-Check the bluetoothd exists
-```
-$ ps -ef | grep bluetooth
-```
-
-## Wifi-Direct Issues
-### Remove the P2P group (Wifi-direct) on the wifi interface
-remove group ```p2p-wlan0-0``` on the wifi interface ```wlan0```
-```
-sudo wpa_cli -i wlan0 p2p_group_remove p2p-wlan0-0
-```
diff --git a/subprojects/sc/android/.project b/subprojects/sc/android/.project
deleted file mode 100644
index 3964dd3f..00000000
--- a/subprojects/sc/android/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
- android
- Project android created by Buildship.
-
-
-
-
- org.eclipse.buildship.core.gradleprojectbuilder
-
-
-
-
-
- org.eclipse.buildship.core.gradleprojectnature
-
-
diff --git a/subprojects/sc/android/.settings/org.eclipse.buildship.core.prefs b/subprojects/sc/android/.settings/org.eclipse.buildship.core.prefs
deleted file mode 100644
index e8895216..00000000
--- a/subprojects/sc/android/.settings/org.eclipse.buildship.core.prefs
+++ /dev/null
@@ -1,2 +0,0 @@
-connection.project.dir=
-eclipse.preferences.version=1
diff --git a/subprojects/sc/android/Readme.md b/subprojects/sc/android/Readme.md
deleted file mode 100644
index 98b9bfe0..00000000
--- a/subprojects/sc/android/Readme.md
+++ /dev/null
@@ -1 +0,0 @@
-[P2PForYourThings](https://github.com/esevan/P2PForYourThings)
diff --git a/subprojects/sc/android/app/.classpath b/subprojects/sc/android/app/.classpath
deleted file mode 100644
index eb19361b..00000000
--- a/subprojects/sc/android/app/.classpath
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
diff --git a/subprojects/sc/android/app/.gitignore b/subprojects/sc/android/app/.gitignore
deleted file mode 100755
index 3543521e..00000000
--- a/subprojects/sc/android/app/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/build
diff --git a/subprojects/sc/android/app/.project b/subprojects/sc/android/app/.project
deleted file mode 100644
index ac485d7c..00000000
--- a/subprojects/sc/android/app/.project
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
- app
- Project app created by Buildship.
-
-
-
-
- org.eclipse.jdt.core.javabuilder
-
-
-
-
- org.eclipse.buildship.core.gradleprojectbuilder
-
-
-
-
-
- org.eclipse.jdt.core.javanature
- org.eclipse.buildship.core.gradleprojectnature
-
-
diff --git a/subprojects/sc/android/app/.settings/org.eclipse.buildship.core.prefs b/subprojects/sc/android/app/.settings/org.eclipse.buildship.core.prefs
deleted file mode 100644
index b1886adb..00000000
--- a/subprojects/sc/android/app/.settings/org.eclipse.buildship.core.prefs
+++ /dev/null
@@ -1,2 +0,0 @@
-connection.project.dir=..
-eclipse.preferences.version=1
diff --git a/subprojects/sc/android/app/build.gradle b/subprojects/sc/android/app/build.gradle
deleted file mode 100755
index ec825f69..00000000
--- a/subprojects/sc/android/app/build.gradle
+++ /dev/null
@@ -1,29 +0,0 @@
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 25
- buildToolsVersion '27.0.3'
- defaultConfig {
- applicationId "com.redcarrottt.sc"
- minSdkVersion 19
- targetSdkVersion 25
- versionCode 1
- versionName "1.0"
- testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
-}
-
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
- androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
- exclude group: 'com.android.support', module: 'support-annotations'
- })
- compile 'com.android.support:appcompat-v7:25.0.0'
- testCompile 'junit:junit:4.12'
-}
diff --git a/subprojects/sc/android/app/proguard-rules.pro b/subprojects/sc/android/app/proguard-rules.pro
deleted file mode 100755
index fa3c8f5e..00000000
--- a/subprojects/sc/android/app/proguard-rules.pro
+++ /dev/null
@@ -1,17 +0,0 @@
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in C:\Users\eslab\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the proguardFiles
-# directive in build.gradle.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
diff --git a/subprojects/sc/android/app/src/androidTest/java/com/redcarrottt/testapp/ExampleInstrumentedTest.java b/subprojects/sc/android/app/src/androidTest/java/com/redcarrottt/testapp/ExampleInstrumentedTest.java
deleted file mode 100755
index 832a7b5d..00000000
--- a/subprojects/sc/android/app/src/androidTest/java/com/redcarrottt/testapp/ExampleInstrumentedTest.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package kr.ac.skku.nyx.selectiveconnection;
-
-import android.content.Context;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.*;
-
-/**
- * Instrumentation test, which will execute on an Android device.
- *
- * @see Testing documentation
- */
-@RunWith(AndroidJUnit4.class)
-public class ExampleInstrumentedTest {
- @Test
- public void useAppContext() throws Exception {
- // Context of the app under test.
- Context appContext = InstrumentationRegistry.getTargetContext();
-
- assertEquals("kr.ac.skku.nyx.selectiveconnection", appContext.getPackageName());
- }
-}
diff --git a/subprojects/sc/android/app/src/main/AndroidManifest.xml b/subprojects/sc/android/app/src/main/AndroidManifest.xml
deleted file mode 100755
index 992dd9fb..00000000
--- a/subprojects/sc/android/app/src/main/AndroidManifest.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/ic_launcher-web.png b/subprojects/sc/android/app/src/main/ic_launcher-web.png
deleted file mode 100644
index 2321e583..00000000
Binary files a/subprojects/sc/android/app/src/main/ic_launcher-web.png and /dev/null differ
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/api/API.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/api/API.java
deleted file mode 100755
index a8dcdc22..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/api/API.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.redcarrottt.sc.api;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import com.redcarrottt.sc.internal.ClientAdapter;
-import com.redcarrottt.sc.internal.Core;
-
-public class API {
- public static void startSC(OnStartSCResult resultListener) {
- Core.singleton().start(resultListener);
- }
-
- public static void stopSC(OnStopSCResult resultListener) {
- Core.singleton().stop(resultListener);
- }
-
- public static void registerAdapter(ClientAdapter adapter) {
- Core.singleton().registerAdapter(adapter);
- }
-
- public static int send(byte[] dataBuffer, int dataLength) {
- return Core.singleton().send(dataBuffer, dataLength, false);
- }
-
- public static int receive(byte[] dataBuffer) {
- return Core.singleton().receive(dataBuffer, false);
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/api/OnStartSCResult.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/api/OnStartSCResult.java
deleted file mode 100644
index 5646c9e5..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/api/OnStartSCResult.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.redcarrottt.sc.api;
-
-/* Copyright (c) 2018, contributors. All rights reserved.
- *
- * Contributor: Gyeonghwan Hong
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-public interface OnStartSCResult {
- public void onDoneStartSC(boolean isSuccess);
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/api/OnStopSCResult.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/api/OnStopSCResult.java
deleted file mode 100644
index c5a6a1ef..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/api/OnStopSCResult.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.redcarrottt.sc.api;
-
-/* Copyright (c) 2018, contributors. All rights reserved.
- *
- * Contributor: Gyeonghwan Hong
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-public interface OnStopSCResult {
- public void onDoneStopSC(boolean isSuccess);
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ClientAdapter.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ClientAdapter.java
deleted file mode 100644
index ebd8110f..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ClientAdapter.java
+++ /dev/null
@@ -1,901 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import android.util.Log;
-
-import com.redcarrottt.testapp.Logger;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Date;
-
-import static com.redcarrottt.sc.internal.ExpConfig.VERBOSE_CLIENT_ADAPTER;
-import static com.redcarrottt.sc.internal.ExpConfig.VERBOSE_RECEIVER_TIME;
-import static com.redcarrottt.sc.internal.ExpConfig.VERBOSE_SEGMENT_DEQUEUE_CTRL;
-import static com.redcarrottt.sc.internal.ExpConfig.VERBOSE_SEGMENT_DEQUEUE_DATA;
-import static com.redcarrottt.sc.internal.SegmentManager.kDeqSendControlData;
-import static com.redcarrottt.sc.internal.SegmentManager.kSQRecvControl;
-import static com.redcarrottt.sc.internal.SegmentManager.kSQRecvData;
-import static com.redcarrottt.sc.internal.SegmentManager.kSegFlagControl;
-import static com.redcarrottt.sc.internal.SegmentManager.kSegHeaderSize;
-import static com.redcarrottt.sc.internal.SegmentManager.kSegSize;
-
-public class ClientAdapter {
- private final String kTag = "ClientAdapter";
- private final ClientAdapter self = this;
-
- // Main Functions: connect, disconnect, send, receive
- public void connect(ConnectResultListener listener, boolean isSendRequest) {
- int state = this.getState();
- if (state != State.kDisconnected) {
- Logger.ERR(kTag, "Connect Failed: Already connected or connect/disconnection is in "
- + "progress: " + this.getName() + " / " + this.getState());
- listener.onConnectResult(false);
- return;
- }
-
- if (isSendRequest) {
- Core.singleton().getControlMessageSender().sendRequestConnect(this.getId());
- }
-
- ConnectThread thread = new ConnectThread(listener);
- thread.start();
- }
-
- public void disconnectOnCommand(DisconnectResultListener listener) {
- // Check if the adapter is not sleeping
- int state = this.getState();
- if (state == State.kGoingSleep) {
- Logger.VERB(kTag, this.getName() + ": Disconnect - waiting for sleeping...");
- while (state != State.kSleeping) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- state = this.getState();
- }
- } else if (state != State.kSleeping) {
- Logger.ERR(kTag, this.getName() + ": Disconnect fail - not sleeping - " + state);
- listener.onDisconnectResult(false);
- return;
- }
-
- // Set this disconnection is on purpose
- this.startDisconnectingOnPurpose();
-
- // Get my final seq_no
- SegmentManager sm = SegmentManager.singleton();
- int my_final_seq_no_control = sm.getLastSeqNoControl();
- int my_final_seq_no_data = sm.getLastSeqNoData();
-
- // Send disconnect request
- Core.singleton().getControlMessageSender().sendRequestDisconnect(this.getId(),
- my_final_seq_no_control, my_final_seq_no_data);
-
- disconnectInternal(listener);
- }
-
- public void disconnectOnPeerCommand(DisconnectResultListener listener, int
- peerFinalSeqNoControl, int peerFinalSeqNoData) {
- // Check if the adapter is not sleeping
- int state = this.getState();
-
- // TODO: wait for sleeping should be implemented
-
- // Set this disconnection is on purpose
- this.startDisconnectingOnPurpose();
- this.peerKnowsDisconnectingOnPurpose();
-
- // Start wait receiving
- SegmentManager sm = SegmentManager.singleton();
- sm.waitReceiving(peerFinalSeqNoControl, peerFinalSeqNoData);
-
- // Send disconnect ack
- Core.singleton().getControlMessageSender().sendRequestDisconnectAck(this.getId());
-
- disconnectInternal(listener);
- }
-
- public void disconnectOnFailure(DisconnectResultListener listener) {
- // Check if the adapter is not sleeping
- int state = this.getState();
- if (state == State.kDisconnected || state == State.kDisconnecting) {
- Logger.VERB(kTag, this.getName() + ": Disconnect - already disconnecting or " +
- "disconnected - " + state);
- listener.onDisconnectResult(false);
- return;
- }
-
- disconnectInternal(listener);
- }
-
- private void disconnectInternal(DisconnectResultListener listener) {
- // Spawn disconnect thread
- DisconnectThread thread = new DisconnectThread(listener);
- thread.start();
- }
-
- int send(byte[] dataBuffer, int dataLength) {
- int state = this.getState();
- if (state == State.kSleeping || state == State.kGoingSleep || state == State.kWakingUp) {
- if (!this.isDisconnectingOnPurpose()) {
- Logger.ERR(kTag, "Send Failed: Already sleeping: " + this.getName() + " / " +
- this.getState());
- }
- return -1;
- } else if (state != State.kActive) {
- Logger.ERR(kTag, "Send Failed: Already disconnected or connect/disconnection is in "
- + "progress: " + this.getName() + " / " + this.getState());
- return -1;
- }
-
- if (this.mClientSocket == null) {
- return -2;
- }
-
- Logger.VERB(this.getName(), "Send data: length=" + dataLength);
-
- // Omit Implementing Statistics: SendDataSize
- return this.mClientSocket.send(dataBuffer, dataLength);
- }
-
- int receive(byte[] dataBuffer, int dataLength) {
- int state = this.getState();
- if (state != State.kActive && state != State.kGoingSleep && state != State.kSleeping &&
- state != State.kWakingUp) {
- if (!this.isDisconnectingOnPurpose()) {
- Logger.ERR(kTag, "Receive Failed: Already disconnected or connect/disconnection "
- + "is " + "in" + " progress: " + this.getName() + " / " + this.getState());
- }
- return -1;
- }
-
- if (this.mClientSocket == null) {
- return -2;
- }
-
- // Omit Implementing Statistics: ReceiveDataSize
- return this.mClientSocket.receive(dataBuffer, dataLength);
- }
-
- // Connect/Disconnect Threads & Callbacks
- class ConnectThread extends Thread implements TurnOnResultListener,
- DiscoverAndConnectResultListener {
- @Override
- public void run() {
- this.setName(self.getName() + "/Connect");
- Logger.VERB(kTag, self.getName() + "'s Connect Thread Spawned! (id:" + this.getId() +
- ")");
- setState(ClientAdapter.State.kConnecting);
-
- if (self.mDevice == null || self.mP2PClient == null || self.mClientSocket == null) {
- this.onFail();
- return;
- }
-
- // Turn on device
- self.mDevice.turnOn(this);
- }
-
- @Override
- public void onTurnOnResult(boolean isSuccess) {
- int deviceState = self.mDevice.getState();
- if (!isSuccess || deviceState != Device.State.kOn) {
- Logger.ERR(kTag, "Cannot connect the server adapter - turn-on fail: " + self
- .getName());
- this.onFail();
- return;
- }
-
- Logger.VERB(kTag, "Turn on success: " + self.getName());
-
- // Discover and connect to server
- self.mP2PClient.discoverAndConnect(this);
- }
-
- @Override
- public void onDiscoverAndConnectResult(boolean isSuccess) {
- // Check the result of "Discover and connect"
- int p2pClientState = self.mP2PClient.getState();
- if (!isSuccess || p2pClientState != P2PClient.State.kConnected) {
- Logger.ERR(kTag, "Cannot connect the server adapter - discover fail:" + self
- .getName());
- self.mDevice.turnOff(null);
- this.onFail();
- return;
- }
-
- Logger.VERB(kTag, "P2P connect success: " + self.getName());
-
- this.mSocketOpenThread = new SocketOpenThread();
- this.mSocketOpenThread.start();
- }
-
- private SocketOpenThread mSocketOpenThread;
-
- class SocketOpenThread extends Thread {
- @Override
- public void run() {
- // Open client socket
- this.setName(self.getName() + "/SocketOpen");
- int socketState = self.mClientSocket.getState();
- if (socketState != ClientSocket.State.kOpened) {
- boolean res = self.mClientSocket.open();
-
- socketState = self.mClientSocket.getState();
- if (!res || socketState != ClientSocket.State.kOpened) {
- Logger.ERR(kTag, "Cannot connect the server adapter - socket open fail: "
- + self.getName());
- self.mP2PClient.disconnect(null);
- self.mDevice.turnOff(null);
- onFail();
- return;
- }
- }
-
- Logger.VERB(kTag, "Socket connect success: " + self.getName());
-
- // Run sender & receiver threads
- if (self.mSenderThread != null && !self.mSenderThread.isOn()) {
- self.mSenderThread.start();
- }
-
- if (self.mReceiverThread != null && !self.mReceiverThread.isOn()) {
- self.mReceiverThread.start();
- }
-
- // Report result success
- self.setState(ClientAdapter.State.kActive);
- if (mResultListener != null) {
- mResultListener.onConnectResult(true);
- mResultListener = null;
- }
- }
- }
-
- private void onFail() {
- self.setState(ClientAdapter.State.kDisconnected);
-
- // Report result fail
- if (this.mResultListener != null) {
- this.mResultListener.onConnectResult(false);
- this.mResultListener = null;
- }
- }
-
- private ConnectResultListener mResultListener;
-
- ConnectThread(ConnectResultListener resultListener) {
- this.mResultListener = resultListener;
- }
- }
-
- class DisconnectThread extends Thread implements com.redcarrottt.sc.internal
- .DisconnectResultListener, TurnOffResultListener {
- @Override
- public void run() {
- this.setName(self.getName() + "/Disconnect");
- Logger.VERB(kTag, self.getName() + "'s Disconnect Thread Spawned! (id:" + this.getId
- () + ")");
- int oldState = self.getState();
- setState(ClientAdapter.State.kDisconnecting);
-
- if (isDisconnectingOnPurpose() && !isDisconnectingOnPurposePeer()) {
- waitForDisconnectingOnPurposePeer();
- }
-
- boolean res = this.__disconnect_thread(oldState);
-
- finishDisconnectingOnPurpose();
-
- if (!res) {
- this.onFail();
- }
-
- Logger.VERB(kTag, self.getName() + "'s Disconnect Thread Finished. (id:" + this.getId
- () + ")");
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- private boolean __disconnect_thread(int oldState) {
- // Finish sender & receiver threads
- if (self.mSenderThread != null) {
- self.mSenderThread.finish();
- if (oldState == ClientAdapter.State.kSleeping) {
- self.wakeUpInternal();
- }
- }
- if (self.mReceiverThread != null) {
- self.mReceiverThread.finish();
- }
-
- // Wake up sender thread waiting segment queue
- SegmentManager sm = SegmentManager.singleton();
- sm.wakeUpDequeueWaiting(kDeqSendControlData);
-
- // Close client socket
- if (self.mClientSocket == null) {
- return false;
- }
- int socketState = self.mClientSocket.getState();
- if (socketState != ClientSocket.State.kClosed) {
- boolean res = self.mClientSocket.close();
-
- socketState = self.mClientSocket.getState();
- if (!res || socketState != ClientSocket.State.kClosed) {
- Logger.ERR(kTag, "Cannot disconnect the server adapter - socket " + "close "
- + "fail: " + "" + "" + self.getName());
- return false;
- }
- }
-
- // P2P Disconnect
- self.mP2PClient.disconnect(this);
-
- // Wait for sender/receiver thread
- try {
- synchronized (self.mWaitSenderThread) {
- if (self.mSenderThread.isOn()) {
- Logger.DEBUG(kTag, "Waiting for sender thread... " + mName);
- synchronized (self.mIsWaitSenderThread) {
- self.mIsWaitSenderThread = true;
- }
- self.mWaitSenderThread.wait();
- }
- Logger.DEBUG(kTag, "Sender thread's end is detected... " + mName);
- }
- synchronized (self.mWaitReceiverThread) {
- if (self.mReceiverThread.isOn()) {
- Logger.DEBUG(kTag, "Waiting for receiver thread..." + mName);
- synchronized (self.mIsWaitReceiverThread) {
- self.mIsWaitReceiverThread = true;
- }
- self.mWaitReceiverThread.wait();
- }
- Logger.DEBUG(kTag, "Receiver thread's end is detected... " + mName);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return true;
- }
-
- @Override
- public void onDisconnectResult(boolean isSuccess) {
- // Check the result of "P2P Disconnect"
- int p2pClientState = self.mP2PClient.getState();
- if (!isSuccess) {
- Logger.ERR(kTag, "Cannot disconnect the server adapter - " + "disconnect P2P " +
- "client fail: " + self.getName());
- this.onFail();
- return;
- }
-
- // Turn off device
- self.mDevice.turnOff(this);
- }
-
- @Override
- public void onTurnOffResult(boolean isSuccess) {
- int deviceState = self.mDevice.getState();
- if (!isSuccess) {
- Logger.ERR(kTag, "Cannot disconnect the server adapter - turn-off " + "fail:" +
- "" + " " + self.getName());
- this.onFail();
- return;
- }
-
- // Report result success
- self.setState(ClientAdapter.State.kDisconnected);
- if (this.mResultListener != null) {
- this.mResultListener.onDisconnectResult(true);
- this.mResultListener = null;
- }
- }
-
- private void onFail() {
- self.setState(ClientAdapter.State.kActive);
-
- // Report result fail
- if (this.mResultListener != null) {
- this.mResultListener.onDisconnectResult(false);
- this.mResultListener = null;
- }
- }
-
- private DisconnectResultListener mResultListener;
-
- DisconnectThread(DisconnectResultListener resultListener) {
- this.mResultListener = resultListener;
- }
- }
-
- interface ConnectResultListener {
- void onConnectResult(boolean isSuccess);
- }
-
- interface DisconnectResultListener {
- void onDisconnectResult(boolean isSuccess);
- }
-
- // Sender/Receiver Threads
- @SuppressWarnings("SynchronizeOnNonFinalField")
- class SenderThread extends Thread {
- @Override
- public void run() {
- this.setName(self.getName() + "/Sender");
- synchronized (this.mIsOn) {
- this.mIsOn = true;
- }
- synchronized (this.mIsSuspended) {
- this.mIsSuspended = false;
- }
-
- synchronized (self.mIsWaitSenderThread) {
- self.mIsWaitSenderThread = false;
- }
-
- this.senderThreadLoop();
-
-// NetworkSwitcher.singleton().reconnectAdapter(ClientAdapter.this);
- Logger.VERB(kTag, ClientAdapter.this.getName() + "'s Sender thread ends");
-
- synchronized (self.mIsWaitSenderThread) {
- if (self.mIsWaitSenderThread) {
- self.mWaitSenderThread.notifyAll();
- }
- }
- }
-
- private void senderThreadLoop() {
- Logger.VERB(kTag, ClientAdapter.this.getName() + "'s Sender thread starts");
- while (this.mIsOn) {
- SegmentManager sm = SegmentManager.singleton();
- Segment segmentToSend;
-
- // If this sender is set to be suspended, wait until it wakes up
- {
- boolean sender_suspended;
- do {
- synchronized (mSenderSuspended) {
- sender_suspended = mSenderSuspended;
- }
- if (!sender_suspended) {
- break;
- }
- Logger.VERB(kTag, "Sender thread suspended: " + this.getName());
- setState(ClientAdapter.State.kSleeping);
- synchronized (mSenderSuspended) {
- try {
- mSenderSuspended.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- setState(ClientAdapter.State.kActive);
- } while (true);
- }
-
- // Dequeue from a queue (one of the three queues)
- // Priority 1. Failed sending queue
- segmentToSend = sm.get_failed_sending();
- // Priority 2. Send control queue
- // Priority 3. Send data queue
- if (segmentToSend == null) {
- segmentToSend = sm.dequeue(kDeqSendControlData);
- }
-
- if (segmentToSend == null) {
- // Nothing to send.
- // SegmentManager::wake_up_dequeue_waiting() function may make this case
- continue;
- }
-
- int state = self.getState();
- if (state == ClientAdapter.State.kDisconnecting || state == ClientAdapter.State
- .kDisconnected || isDisconnectingOnPurpose()) {
- sm.failed_sending(segmentToSend);
- continue;
- }
-
- // If it is suspended, push the segment to the send-fail queue
- {
- boolean sender_suspended;
- synchronized (mSenderSuspended) {
- sender_suspended = mSenderSuspended;
- }
- if (sender_suspended) {
- Logger.VERB(kTag, "Sending segment is pushed to failed queue at " + this
- .getName() + " (suspended)");
- sm.failed_sending(segmentToSend);
- continue;
- }
- }
-
- Logger.DEBUG(ClientAdapter.this.getName(), "SEND Segment " + segmentToSend.seq_no
- + " / " + segmentToSend.len + "" + " / " + segmentToSend.flag);
-
- int res = send(segmentToSend.data, kSegHeaderSize + kSegSize);
- if (res < 0) {
- Logger.WARN(kTag, "Sending failed at " + ClientAdapter.this.getName());
- sm.failed_sending(segmentToSend);
- break;
- }
- sm.free_segment(segmentToSend);
- }
- }
-
- public void finish() {
- synchronized (this.mIsOn) {
- this.mIsOn = false;
- }
- synchronized (this.mIsSuspended) {
- this.mIsSuspended = false;
- }
- }
-
- SenderThread() {
- this.mIsOn = false;
- this.mIsSuspended = false;
- }
-
- public boolean isOn() {
- return this.mIsOn;
- }
-
- private Boolean mIsOn;
- private Boolean mIsSuspended;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- class ReceiverThread extends Thread {
- @Override
- public void run() {
- this.setName(self.getName() + "/Receiver");
- synchronized (this.mIsOn) {
- this.mIsOn = true;
- }
- synchronized (self.mIsWaitReceiverThread) {
- self.mIsWaitReceiverThread = false;
- }
-
- this.receiverThreadLoop(self);
-
- synchronized (self.mIsWaitReceiverThread) {
- if (self.mIsWaitReceiverThread) {
- self.mWaitReceiverThread.notifyAll();
- }
- }
- }
-
- private int mReceiveCount = 0;
- private Date mDates[] = new Date[5];
- private long mIntervals[] = new long[4];
-
- public void receiverThreadLoop(ClientAdapter adapter) {
- Logger.VERB(kTag, ClientAdapter.this.getName() + "'s Receiver thread starts");
- byte prevData[] = new byte[SegmentManager.kSegSize + SegmentManager.kSegHeaderSize];
-
- while (this.isOn()) {
- if (VERBOSE_RECEIVER_TIME) this.mDates[0] = new Date();
-
- SegmentManager sm = SegmentManager.singleton();
- Segment segmentToReceive = sm.get_free_segment();
- int len = kSegSize + kSegHeaderSize;
-
- if (VERBOSE_RECEIVER_TIME) this.mDates[1] = new Date();
-
- if (VERBOSE_CLIENT_ADAPTER) {
- Logger.DEBUG(kTag, adapter.getName() + ": Receiving...");
- }
- int res = adapter.receive(segmentToReceive.data, len);
- if (res < len) {
- Logger.WARN(kTag, "Receiving failed at " + adapter.getName());
- break;
- }
-
- if (VERBOSE_RECEIVER_TIME) this.mDates[2] = new Date();
-
- // Read segment metadata
- ByteBuffer buffer = ByteBuffer.allocate(4);
- buffer.put(segmentToReceive.data, 0, 4);
- segmentToReceive.seq_no = buffer.getInt(0);
-
- buffer = ByteBuffer.allocate(4);
- buffer.put(segmentToReceive.data, 4, 4);
- segmentToReceive.len = buffer.getInt(0);
-
- buffer = ByteBuffer.allocate(4);
- buffer.put(segmentToReceive.data, 8, 4);
- segmentToReceive.flag = buffer.getInt(0);
-
- //Logger.DEBUG(kTag, "RECEIVE " + segmentToReceive.seq_no + " / " +
- // segmentToReceive.len + " / " + segmentToReceive.flag);
-
- if (VERBOSE_RECEIVER_TIME) this.mDates[3] = new Date();
-
- boolean is_control = ((segmentToReceive.flag & kSegFlagControl) != 0);
-
- if (VERBOSE_SEGMENT_DEQUEUE_CTRL && is_control) {
- Logger.DEBUG(getName(), "Receive Segment: seqno=" + segmentToReceive.seq_no +
- " / type=ctrl");
- }
- if (VERBOSE_SEGMENT_DEQUEUE_DATA && !is_control) {
- Logger.DEBUG(getName(), "Receive Segment: seqno=" + segmentToReceive.seq_no +
- " / type=data");
- }
-
- if (is_control) {
- sm.enqueue(kSQRecvControl, segmentToReceive);
- } else {
- sm.enqueue(kSQRecvData, segmentToReceive);
- }
-
- if (VERBOSE_RECEIVER_TIME) this.mDates[4] = new Date();
-
- if (VERBOSE_RECEIVER_TIME) {
- this.mReceiveCount++;
- for (int i = 0; i < 4; i++) {
- this.mIntervals[i] += this.mDates[i + 1].getTime() - this.mDates[i]
- .getTime();
- }
- if (this.mReceiveCount % 500 == 0) {
- Log.d(kTag, "Receive Time " + this.mIntervals[0] + " / " + this
- .mIntervals[1] + " / " + this.mIntervals[2] + " / " + this
- .mIntervals[3]);
- for (int i = 0; i < 4; i++) {
- this.mIntervals[i] = 0;
- }
- }
- }
- }
-
-// NetworkSwitcher.singleton().reconnectAdapter(ClientAdapter.this);
- Logger.VERB(kTag, ClientAdapter.this.getName() + "'s Receiver thread ends");
- }
-
- public void finish() {
- synchronized (this.mIsOn) {
- this.mIsOn = false;
- }
- }
-
- ReceiverThread() {
- this.mIsOn = false;
- }
-
- public boolean isOn() {
- return this.mIsOn;
- }
-
- private Boolean mIsOn;
- }
-
- private SenderThread mSenderThread;
- private ReceiverThread mReceiverThread;
- private Boolean mSenderSuspended;
-
- private Boolean mIsWaitSenderThread;
- private Boolean mIsWaitReceiverThread;
- private Object mWaitSenderThread = new Object();
- private Object mWaitReceiverThread = new Object();
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- public boolean sleep(boolean isSendRequest) {
- int state = this.getState();
- if (state != State.kActive) {
- Logger.ERR(kTag, "Failed to sleep: " + this.getName() + "(state: " + state + ")");
- return false;
- }
-
- synchronized (this.mSenderSuspended) {
- if (this.mSenderSuspended) {
- Logger.ERR(kTag, "Sender has already been suspended!: " + this.getName());
- return false;
- } else {
- if (isSendRequest) {
- // Send Request
- Core.singleton().getControlMessageSender().sendRequestSleep(this.getId());
- }
-
- // Sleep
- this.setState(State.kGoingSleep);
- this.mSenderSuspended = true;
-
- // Wake up sender thread waiting segment queue
- SegmentManager sm = SegmentManager.singleton();
- sm.wakeUpDequeueWaiting(kDeqSendControlData);
- return true;
- }
- }
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- public boolean wakeUp(boolean isSendRequest) {
- int state = this.getState();
- if (state != State.kSleeping) {
- Logger.ERR(kTag, "Failed to wake up: " + this.getName() + "(state: " + state + ")");
- return false;
- }
- boolean sender_suspended;
- synchronized (this.mSenderSuspended) {
- sender_suspended = this.mSenderSuspended;
- }
- if (sender_suspended) {
- // Send Request
- Core.singleton().getControlMessageSender().sendRequestWakeup(this.getId());
-
- // Wake up
- this.setState(State.kWakingUp);
- this.wakeUpInternal();
-
- return true;
- } else {
- Logger.ERR(kTag, "Sender has not been suspended!: " + this.getName());
- return false;
- }
- }
-
- private void wakeUpInternal() {
- synchronized (this.mSenderSuspended) {
- this.mSenderSuspended = false;
- this.mSenderSuspended.notifyAll();
- }
- }
-
- // Initialize
- public ClientAdapter(int id, String name) {
- this.mId = id;
- this.mName = name;
- this.mState = State.kDisconnected;
- this.mListeners = new ArrayList<>();
- this.mSenderSuspended = false;
- this.mIsDisconnectingOnPurpose = false;
- this.mIsDisconnectingOnPurposePeer = false;
- this.mIsWaitReceiverThread = false;
- this.mIsWaitSenderThread = false;
-
- this.mSenderThread = new SenderThread();
- this.mReceiverThread = new ReceiverThread();
- }
-
- protected void initialize(Device device, P2PClient p2pClient, ClientSocket clientSocket) {
- this.mDevice = device;
- this.mP2PClient = p2pClient;
- this.mClientSocket = clientSocket;
- }
-
- // Attribute getters
- public int getId() {
- return this.mId;
- }
-
- public String getName() {
- return this.mName;
- }
-
- public boolean isDisconnectingOnPurpose() {
- return this.mIsDisconnectingOnPurpose;
- }
-
- public boolean isDisconnectingOnPurposePeer() {
- return this.mIsDisconnectingOnPurposePeer;
- }
-
- // Attribute setters
- public void startDisconnectingOnPurpose() {
- this.mIsDisconnectingOnPurpose = true;
- }
-
- public void waitForDisconnectingOnPurposePeer() {
- synchronized (mWaitForDisconnectAck) {
- try {
- mWaitForDisconnectAck.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-
- public void peerKnowsDisconnectingOnPurpose() {
- this.mIsDisconnectingOnPurposePeer = true;
- synchronized (this.mWaitForDisconnectAck) {
- this.mWaitForDisconnectAck.notifyAll();
- }
- }
-
- private void finishDisconnectingOnPurpose() {
- this.mIsDisconnectingOnPurpose = false;
- this.mIsDisconnectingOnPurposePeer = false;
- }
-
- // Attributes
- private int mId;
- private String mName;
-
- // Disconnecting on purpose by a device
- private boolean mIsDisconnectingOnPurpose;
- private boolean mIsDisconnectingOnPurposePeer;
- private Object mWaitForDisconnectAck = new Object();
-
- // State
- class State {
- public static final int kDisconnected = 0;
- public static final int kConnecting = 1;
- public static final int kActive = 2;
- public static final int kDisconnecting = 3;
- public static final int kGoingSleep = 4;
- public static final int kSleeping = 5;
- public static final int kWakingUp = 6;
- public static final int kASNum = 7;
- }
-
- public static String stateToString(int state) {
- final String[] stateStr = {"Disconnected", "Connecting", "Active", "Disconnecting",
- "GoingSleep", "Sleeping", "WakingUp"};
- if (state >= State.kASNum || state < 0) {
- return "";
- } else {
- return stateStr[state];
- }
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- public int getState() {
- int state;
- synchronized (this.mState) {
- state = this.mState;
- }
- return state;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- private void setState(int newState) {
- int oldState;
- synchronized (this.mState) {
- oldState = this.mState;
- this.mState = newState;
- }
-
- Logger.DEBUG(this.getName(), "State(" + stateToString(oldState) + "->" + stateToString
- (newState) + ")");
-
- for (ClientAdapterStateListener listener : this.mListeners) {
- listener.onUpdateClientAdapterState(this, oldState, newState);
- }
- }
-
- public void listenState(ClientAdapterStateListener listener) {
- synchronized (this.mListeners) {
- this.mListeners.add(listener);
- }
- }
-
- // State
- private Integer mState;
-
- // State Listener
- private final ArrayList mListeners;
-
- // Main Components : Device, P2PClient, ClientSocket
- private Device mDevice;
- private P2PClient mP2PClient;
-
- private ClientSocket mClientSocket;
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ClientAdapterStateListener.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ClientAdapterStateListener.java
deleted file mode 100644
index c12efee6..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ClientAdapterStateListener.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2018, contributors. All rights reserved.
- *
- * Contributor: Gyeonghwan Hong
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-public interface ClientAdapterStateListener {
- void onUpdateClientAdapterState(ClientAdapter adapter, int oldState, int newState);
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ClientSocket.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ClientSocket.java
deleted file mode 100644
index 8fe485c9..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ClientSocket.java
+++ /dev/null
@@ -1,120 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import com.redcarrottt.testapp.Logger;
-
-public abstract class ClientSocket {
- private final String kTag = "ClientSocket";
-
- // Main Functions
- public boolean open() {
- if (this.getState() != State.kClosed) {
- Logger.ERR(kTag, "It's already opened or opening/closing is in progress");
- return false;
- }
-
- this.setState(State.kOpening);
- boolean res = this.openImpl();
- if (!res) {
- this.setState(State.kClosed);
- } else {
- this.setState(State.kOpened);
- }
- return res;
- }
-
- public boolean close() {
- if (this.getState() != State.kOpened) {
- Logger.ERR(kTag, "It's already closed or opening/closing is in progress");
- return false;
- }
-
- this.setState(State.kClosing);
- boolean res = this.closeImpl();
- this.setState(State.kClosed);
-
- return res;
- }
-
- public int send(byte[] dataBuffer, int dataLength) {
- if (this.getState() != State.kOpened) {
- Logger.ERR(kTag, "Socket is not opened");
- return -1;
- }
-
- int res = this.sendImpl(dataBuffer, dataLength);
- if (res < 0) {
- this.setState(State.kClosed);
- }
- return res;
- }
-
- public int receive(byte[] dataBuffer, int dataLength) {
- if (this.getState() != State.kOpened) {
- Logger.ERR(kTag, "Socket is not opened");
- return -1;
- }
-
- int res = this.receiveImpl(dataBuffer, dataLength);
- if (res < 0) {
- this.setState(State.kClosed);
- }
- return res;
- }
-
- // Implemented by child classes
- protected abstract boolean openImpl();
-
- protected abstract boolean closeImpl();
-
- protected abstract int sendImpl(byte[] dataBuffer, int dataLength);
-
- protected abstract int receiveImpl(byte[] dataBuffer, int dataLength);
-
- // State
- class State {
- public static final int kClosed = 0;
- public static final int kOpening = 1;
- public static final int kOpened = 2;
- public static final int kClosing = 3;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- protected int getState() {
- int state;
- synchronized (this.mState) {
- state = this.mState;
- }
- return state;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- private void setState(int newState) {
- synchronized (this.mState) {
- this.mState = newState;
- }
- }
-
- protected ClientSocket() {
- }
-
- // Attributes
-
- // State
- private Integer mState = State.kClosed;
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageListener.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageListener.java
deleted file mode 100644
index a5ab60cd..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageListener.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2018, contributors. All rights reserved.
- *
- * Contributor: Gyeonghwan Hong
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// Control Message Listener
-public interface ControlMessageListener {
- void onReceiveControlMessage(int privateType, String privateMessage);
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageProtocol.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageProtocol.java
deleted file mode 100644
index 7b4c16c6..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageProtocol.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2018, contributors. All rights reserved.
- *
- * Contributor: Gyeonghwan Hong
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-public class ControlMessageProtocol {
- // Control Request Code
- class CMCode {
- public static final char kConnect = 1;
- public static final char kSleep = 2;
- public static final char kWakeup = 3;
- public static final char kDisconnect = 4;
- public static final char kPriv = 10;
- public static final char kDisconnectAck = 24;
- }
-
- // Priv Type Code
- public class PrivType {
- public static final char kWFDInfo = 1;
- public static final char kWFDUnknown = 999;
- }
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageReceiver.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageReceiver.java
deleted file mode 100644
index 6be22426..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageReceiver.java
+++ /dev/null
@@ -1,195 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-import android.util.Log;
-
-import com.redcarrottt.testapp.Logger;
-
-import java.util.ArrayList;
-
-/* Copyright (c) 2018, contributors. All rights reserved.
- *
- * Contributor: Gyeonghwan Hong
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-public class ControlMessageReceiver {
- private static final String kTag = "ControlMessageReceiver";
- private static final String kThreadName = "Control Message Receiving";
-
- public void startReceivingThread() {
- this.mReceivingThread = new ReceivingThread();
- this.mReceivingThread.start();
- }
-
- public void stopReceivingThread() {
- this.mReceivingThread.finish();
- }
-
- // Thread
- private class ReceivingThread extends Thread {
- @Override
- public void run() {
- this.setName("ControlMsgReceiver");
- this.mIsOn = true;
- Logger.THREAD_LAUNCH(kThreadName);
-
- while (this.mIsOn) {
- this.loopInternal();
- }
-
- Logger.THREAD_FINISH(kThreadName);
- this.mIsOn = false;
- }
-
- public boolean loopInternal() {
- byte[] messageBuffer = new byte[10 * 1024];
- int res = Core.singleton().receive(messageBuffer, true);
- if (res <= 0) {
- return false;
- }
-
- String message = new String(messageBuffer).trim();
-
- // Find separator location (between first line and other lines)
- Log.d(kTag, "Control message incoming: " + message);
- int separatorPos = message.indexOf('\n');
-
- // Divide the message into first line & other lines
- String firstLine = message.substring(0, separatorPos);
- String otherLines = message.substring(separatorPos + 1);
-
- int controlMessageCode = Integer.parseInt(firstLine);
-
- switch (controlMessageCode) {
- case ControlMessageProtocol.CMCode.kConnect:
- case ControlMessageProtocol.CMCode.kSleep:
- case ControlMessageProtocol.CMCode.kWakeup:
- case ControlMessageProtocol.CMCode.kDisconnectAck: {
- // Normal type
- int adapterId = Integer.parseInt(otherLines);
- onReceiveNormalMessage(controlMessageCode, adapterId);
- break;
- }
- case ControlMessageProtocol.CMCode.kDisconnect: {
- // Disconnect type
- // Divide the message into second line, third line, fourth line
- separatorPos = otherLines.indexOf('\n');
- String secondLine = otherLines.substring(0, separatorPos);
- String thirdFourthLine = otherLines.substring(separatorPos + 1);
- separatorPos = thirdFourthLine.indexOf('\n');
- String thirdLine = thirdFourthLine.substring(0, separatorPos);
- String fourthLine = thirdFourthLine.substring(separatorPos + 1);
-
- int adapterId = Integer.parseInt(secondLine);
- int finalSeqNoControl = Integer.parseInt(thirdLine);
- int finalSeqNoData = Integer.parseInt(fourthLine);
-
- onReceiveDisconnectMessage(adapterId, finalSeqNoControl, finalSeqNoData);
- break;
- }
- case ControlMessageProtocol.CMCode.kPriv: {
- // Priv type
- onReceivePrivateMessage(otherLines);
- break;
- }
- default: {
- Logger.ERR(kTag, "Unknown control message code (" + controlMessageCode + ")"
- + "!\n" + message);
- break;
- }
- }
-
- return true;
- }
-
- public void finish() {
- this.mIsOn = false;
- }
-
- // Constructor
- public ReceivingThread() {
- this.mIsOn = false;
- }
-
- // Attributes
- private boolean mIsOn;
- }
-
- private void onReceiveNormalMessage(int controlMessageCode, int adapterId) {
- switch (controlMessageCode) {
- case ControlMessageProtocol.CMCode.kConnect: {
- Logger.VERB(kTag, "Receive(Control Msg): Request(Connect " + adapterId + ")");
- NetworkSwitcher.singleton().connectAdapterByPeer(adapterId);
- break;
- }
- case ControlMessageProtocol.CMCode.kSleep: {
- Logger.VERB(kTag, "Receive(Control Msg): Request(Sleep " + adapterId + ")");
- NetworkSwitcher.singleton().sleepAdapterByPeer(adapterId);
- break;
- }
- case ControlMessageProtocol.CMCode.kWakeup: {
- Logger.VERB(kTag, "Receive(Control Msg): Request(WakeUp " + adapterId + ")");
- NetworkSwitcher.singleton().wakeUpAdapterByPeer(adapterId);
- break;
- }
- case ControlMessageProtocol.CMCode.kDisconnectAck: {
- Logger.VERB(kTag, "Receive(Control Msg): Request(DisconenctAck " + adapterId + ")");
- ClientAdapter disconnectAdapter = Core.singleton().findAdapterById(adapterId);
- if (disconnectAdapter == null) {
- Logger.WARN(kTag, "Cannot find adapter " + adapterId);
- } else {
- disconnectAdapter.peerKnowsDisconnectingOnPurpose();
- }
- break;
- }
- }
- }
-
- private void onReceiveDisconnectMessage(int adapterId, int finalSeqNoControl, int
- finalSeqNoData) {
- Logger.VERB(kTag, "Receive(Control Msg): Request(Disconnect " + adapterId + " / " +
- "final_seq_no_control=" + finalSeqNoControl + " / final_seq_no_data=" +
- finalSeqNoData + ")");
- NetworkSwitcher.singleton().disconnectAdapterByPeer(adapterId, finalSeqNoControl,
- finalSeqNoData);
- }
-
- private void onReceivePrivateMessage(String contents) {
- // Find separator location
- int separatorPos = contents.indexOf('\n');
-
- // Divide the message into second line & other lines
- String secondLine = contents.substring(0, separatorPos);
- String privateMessage = contents.substring(separatorPos + 1);
-
- int privateType = Integer.parseInt(secondLine);
-
- // Notify the private message
- for (ControlMessageListener listener : mControlMessageListeners) {
- listener.onReceiveControlMessage(privateType, privateMessage);
- }
- }
-
- public void addControlMessageListener(ControlMessageListener listener) {
- this.mControlMessageListeners.add(listener);
- }
-
- public ControlMessageReceiver() {
- this.mReceivingThread = null;
- this.mControlMessageListeners = new ArrayList<>();
- }
-
- // Attributes
- private ReceivingThread mReceivingThread;
- private ArrayList mControlMessageListeners;
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageSender.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageSender.java
deleted file mode 100644
index 82786e39..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ControlMessageSender.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-import com.redcarrottt.testapp.Logger;
-
-/* Copyright (c) 2018, contributors. All rights reserved.
- *
- * Contributor: Gyeonghwan Hong
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-public class ControlMessageSender {
- private static final String kTag = "ControlMessageSender";
-
- public void sendRequestConnect(int adapterId) {
- this.sendRequest(ControlMessageProtocol.CMCode.kConnect, adapterId);
- Logger.VERB(kTag, "Send(Control Msg): Request(Connect " + adapterId + ")");
- }
-
- public void sendRequestDisconnect(int adapterId, int final_seq_no_control, int
- final_seq_no_data) {
- String message = "" + ControlMessageProtocol.CMCode.kDisconnect + "\n" + adapterId + "\n"
- + final_seq_no_control + "\n" + final_seq_no_data;
- this.sendControlMessage(message);
- Logger.VERB(kTag, "Send(Control Msg): Request(Disconnect " + adapterId + "; " +
- "final_seq_no_control=" + final_seq_no_control + "; final_seq_no_data=" +
- final_seq_no_data + ")");
- }
-
- public void sendRequestDisconnectAck(int adapterId) {
- this.sendRequest(ControlMessageProtocol.CMCode.kDisconnectAck, adapterId);
- Logger.VERB(kTag, "Send(Control Msg): Request(DisconnectAck " + adapterId + ")");
- }
-
- public void sendRequestSleep(int adapterId) {
- this.sendRequest(ControlMessageProtocol.CMCode.kSleep, adapterId);
- Logger.VERB(kTag, "Send(Control Msg): Request(Sleep " + adapterId + ")");
- }
-
- public void sendRequestWakeup(int adapterId) {
- this.sendRequest(ControlMessageProtocol.CMCode.kWakeup, adapterId);
- Logger.VERB(kTag, "Send(Control Msg): Request(WakeUp " + adapterId + ")");
- }
-
- public void sendNotiPrivateData(int privateType, String privateMessage) {
- String message = "" + ControlMessageProtocol.CMCode.kPriv + "\n" + privateType + "\n" +
- privateMessage;
- this.sendControlMessage(message);
- }
-
- private void sendRequest(int requestCode, int adapterId) {
- String message = "" + requestCode + "\n" + adapterId;
- this.sendControlMessage(message);
- }
-
- private void sendControlMessage(String controlMessage) {
- byte[] messageBuffer = controlMessage.getBytes();
- Core.singleton().send(messageBuffer, messageBuffer.length, true);
- }
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/Core.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/Core.java
deleted file mode 100644
index 56e43997..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/Core.java
+++ /dev/null
@@ -1,357 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import com.redcarrottt.sc.api.OnStartSCResult;
-import com.redcarrottt.sc.api.OnStopSCResult;
-import com.redcarrottt.testapp.Logger;
-
-import java.util.ArrayList;
-
-public class Core {
- private static final String kTag = "Core";
-
- // APIs: These functions are mapped to ones in API.
- public void start(OnStartSCResult resultListener) {
- if (this.getState() != State.kIdle) {
- Logger.ERR(kTag, "Core has already started");
- doneStart(false, resultListener);
- return;
- } else if (this.mAdapters.isEmpty()) {
- Logger.ERR(kTag, "No adapter is registered!");
- doneStart(false, resultListener);
- return;
- }
- this.setState(State.kStarting);
- runStartCoreTx(this, resultListener);
- }
-
- private void doneStart(boolean isSuccess, OnStartSCResult resultListener) {
- if (isSuccess) {
- Logger.VERB(kTag, "Succeed to start core!");
- this.setState(State.kReady);
-
- // Launch control message receiving thread
- this.mControlMessageReceiver.startReceivingThread();
- } else {
- Logger.ERR(kTag, "Failed to start core!");
- this.setState(State.kIdle);
- }
- if (resultListener != null) resultListener.onDoneStartSC(isSuccess);
- }
-
- public void stop(OnStopSCResult resultListener) {
- int state = this.getState();
- if (state == State.kStarting || state == State.kStopping) {
- Logger.ERR(kTag, "Cannot stop core during starting/stopping!");
- doneStop(false, resultListener);
- return;
- } else if (state == State.kIdle) {
- Logger.ERR(kTag, "Core is already idle state!");
- doneStop(false, resultListener);
- return;
- } else if (this.mAdapters.isEmpty()) {
- Logger.ERR(kTag, "No adapter is registered!");
- doneStop(false, resultListener);
- return;
- }
-
- this.setState(State.kStopping);
- runStopCoreTx(this, resultListener);
- }
-
- private void doneStop(boolean isSuccess, OnStopSCResult resultListener) {
- if (isSuccess) {
- Logger.VERB(kTag, "Succeed to stop core!");
- this.setState(State.kIdle);
-
- // Finish control message receiving thread
- this.mControlMessageReceiver.stopReceivingThread();
- } else {
- Logger.ERR(kTag, "Failed to stop core!");
- this.setState(State.kReady);
- }
- if (resultListener != null) resultListener.onDoneStopSC(isSuccess);
- }
-
- public void registerAdapter(ClientAdapter adapter) {
- if (this.getState() != State.kIdle) {
- Logger.ERR(kTag, "You can register adapter on only idle state!");
- return;
- }
-
- synchronized (this.mAdapters) {
- this.mAdapters.add(adapter);
- }
- }
-
- public int send(byte[] dataBuffer, int dataLength, boolean isControl) {
- int state = this.getState();
- if (state != State.kReady) {
- Logger.ERR(kTag, "Core is not started yet, so you cannot send the data");
- return -1;
- }
-
- int currOffset = 0;
-
- // Attach the protocol header to the payload
- ProtocolData protocolData = ProtocolManager.data_to_protocol_data(dataBuffer, dataLength);
- if (protocolData == null) throw new AssertionError();
-
- int packetSize = ProtocolManager.serialize(protocolData, dataBuffer, currOffset,
- dataLength);
- if (!(packetSize > 0)) {
- Logger.ERR(kTag, "Failed to make protocol data to send(" + currOffset + "/" +
- dataLength + ")");
- throw new AssertionError();
- }
-
- int sentBytes = ProtocolManager.send_packet(packetSize, isControl);
- if (sentBytes < 0) {
- Logger.ERR(kTag, "Sending stopped (" + currOffset + "/" + dataLength + ") by " +
- sentBytes);
- throw new AssertionError();
- }
-
- return sentBytes;
- }
-
- public int receive(byte[] dataBuffer, boolean isControl) {
- int state = this.getState();
- if (state != State.kReady) {
- Logger.ERR(kTag, "Core is not started yet, so you cannot receive data");
- return -1;
- }
-
- return ProtocolManager.recv_packet(dataBuffer, isControl);
- }
-
- // State
- class State {
- public static final int kIdle = 0;
- public static final int kStarting = 1;
- public static final int kReady = 2;
- public static final int kStopping = 3;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- private int getState() {
- int state;
- synchronized (this.mState) {
- state = this.mState;
- }
- return state;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- private void setState(int newState) {
- synchronized (this.mState) {
- this.mState = newState;
- }
- }
-
-
- // Adapters Getter
- public ClientAdapter findAdapterById(int adapterId) {
- for (ClientAdapter adapter : this.mAdapters) {
- if (adapter.getId() == adapterId) {
- return adapter;
- }
- }
- return null;
- }
-
- public ControlMessageReceiver getControlMessageReceiver() {
- return this.mControlMessageReceiver;
- }
-
- public ControlMessageSender getControlMessageSender() {
- return this.mControlMessageSender;
- }
-
- // Components
- private final ArrayList mAdapters;
- private ControlMessageReceiver mControlMessageReceiver;
- private ControlMessageSender mControlMessageSender;
-
- // State
- private Integer mState;
-
- // Singleton
- private static Core sSingleton;
-
- public static Core singleton() {
- if (sSingleton == null) {
- sSingleton = new Core();
- }
- return sSingleton;
- }
-
- // Constructor
- private Core() {
- this.mState = State.kIdle;
- this.mAdapters = new ArrayList<>();
- this.mControlMessageReceiver = new ControlMessageReceiver();
- this.mControlMessageSender = new ControlMessageSender();
- }
-
- // Transactions
- // ----------------------------------------------------------------
- // Singleton runner
- private static void runStartCoreTx(Core caller, OnStartSCResult resultListener) {
- if (sOngoingStartCore == null) {
- sOngoingStartCore = new StartCoreTransaction(caller, resultListener);
- sOngoingStartCore.start();
- } else {
- Logger.WARN(kTag, "Already starting core");
- doneStartCoreTx(caller, false, resultListener);
- }
- }
-
- private static void doneStartCoreTx(Core caller, boolean isSuccess, OnStartSCResult
- resultListener) {
- sOngoingStartCore = null;
- caller.doneStart(isSuccess, resultListener);
- }
-
- private static void runStopCoreTx(Core caller, OnStopSCResult resultListener) {
- if (sOngoingStopCore == null) {
- sOngoingStopCore = new StopCoreTransaction(caller, resultListener);
- sOngoingStopCore.start();
- } else {
- Logger.WARN(kTag, "Already stopping core");
- doneStopCoreTx(caller, false, resultListener);
- }
- }
-
- private static void doneStopCoreTx(Core caller, boolean isSuccess, OnStopSCResult
- resultListener) {
- sOngoingStopCore = null;
- caller.doneStop(isSuccess, resultListener);
- }
-
- private static StartCoreTransaction sOngoingStartCore = null;
- private static StopCoreTransaction sOngoingStopCore = null;
-
- // Start Core
- private static class StartCoreTransaction {
- // Private Constructor
- private StartCoreTransaction(Core caller, OnStartSCResult resultListener) {
- this.mCaller = caller;
- this.mResultListener = resultListener;
- this.onConnectFirstAdapter = new OnConnectFirstAdapter();
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- private void start() {
- // Connect first adapter
- ClientAdapter firstAdapter = this.mCaller.mAdapters.get(0);
- if (firstAdapter == null) {
- Logger.ERR(kTag, "Cannot find first adapter");
- doneStartCoreTx(mCaller, false, mResultListener);
- return;
- }
- firstAdapter.connect(this.onConnectFirstAdapter, false);
- }
-
- private OnConnectFirstAdapter onConnectFirstAdapter;
-
- class OnConnectFirstAdapter implements ClientAdapter.ConnectResultListener {
- @SuppressWarnings("SimplifiableIfStatement")
- @Override
- public void onConnectResult(boolean isSuccess) {
- if (isSuccess) {
- // Done transaction
- doneStartCoreTx(mCaller, true, mResultListener);
- } else {
- Logger.ERR(kTag, "Connecting first adapter is failed");
- doneStartCoreTx(mCaller, false, mResultListener);
- }
- }
- }
-
- // Attributes
- private Core mCaller;
- private OnStartSCResult mResultListener;
- }
-
- // Stop Core
- private static class StopCoreTransaction {
- private StopCoreTransaction(Core caller, OnStopSCResult resultListener) {
- this.mCaller = caller;
- this.mResultListener = resultListener;
- this.onDisconnectAdapter = new OnDisconnectAdapter();
- this.mAdaptersCount = 0;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- void start() {
- // Get active adapter count
- synchronized (this.mCaller.mAdapters) {
- for (ClientAdapter adapter : this.mCaller.mAdapters) {
- int adapterState = adapter.getState();
- if (adapterState != ClientAdapter.State.kDisconnected && adapterState !=
- ClientAdapter.State.kDisconnecting) {
- this.mAdaptersCount++;
- }
- }
- }
-
- // Disconnect only active adapters
- synchronized (this.mCaller.mAdapters) {
- for (ClientAdapter adapter : this.mCaller.mAdapters) {
- int adapterState = adapter.getState();
- if (adapterState != ClientAdapter.State.kDisconnected && adapterState !=
- ClientAdapter.State.kDisconnecting) {
- adapter.disconnectOnCommand(onDisconnectAdapter);
- }
- }
- }
- }
-
- private OnDisconnectAdapter onDisconnectAdapter;
-
- class OnDisconnectAdapter implements ClientAdapter.DisconnectResultListener {
- @Override
- public void onDisconnectResult(boolean isSuccess) {
- if (!isSuccess) {
- Logger.ERR(kTag, "Disconnecting adapter is failed");
- doneStopCoreTx(mCaller, false, mResultListener);
- return;
- }
-
- // Check if all the active adapters are disconnected
- boolean doneDisconnectAll = false;
- synchronized (mAdaptersCount) {
- mAdaptersCount--;
- if (mAdaptersCount == 0) {
- doneDisconnectAll = true;
- }
- }
-
- if (doneDisconnectAll) {
- doneStopCoreTx(mCaller, true, mResultListener);
- }
- }
- }
-
- // Attributes
- private Core mCaller;
- private Integer mAdaptersCount;
- private OnStopSCResult mResultListener;
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/Device.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/Device.java
deleted file mode 100644
index f6c41ccd..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/Device.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-interface TurnOnResultListener {
- void onTurnOnResult(boolean isSuccess);
-}
-
-interface TurnOffResultListener {
- void onTurnOffResult(boolean isSuccess);
-}
-
-public abstract class Device {
- private final String kTag = "Device";
-
- // Main Functions
- @SuppressWarnings("SynchronizeOnNonFinalField")
- void turnOn(TurnOnResultListener resultListener) {
- this.mTurnOnResultListener = resultListener;
-
- this.setState(State.kTurningOn);
- this.turnOnImpl();
- }
-
- private TurnOnResultListener mTurnOnResultListener;
-
- protected void doneTurnOn(boolean isSuccess) {
- if (isSuccess) {
- // Proceed state
- this.setState(State.kOn);
- } else {
- this.setState(State.kOff);
- }
-
- if (this.mTurnOnResultListener != null) {
- this.mTurnOnResultListener.onTurnOnResult(isSuccess);
- }
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- void turnOff(TurnOffResultListener resultListener) {
- this.mTurnOffResultListener = resultListener;
-
- this.setState(State.kTurningOff);
- this.turnOffImpl();
- }
-
- private TurnOffResultListener mTurnOffResultListener;
-
- protected void doneTurnOff(boolean isSuccess) {
- if (isSuccess) {
- // Proceed state
- this.setState(State.kOff);
- } else {
- // Recover original state
- this.setState(State.kOn);
- }
-
- if (this.mTurnOffResultListener != null) {
- this.mTurnOffResultListener.onTurnOffResult(isSuccess);
- }
- }
-
- // Implemented by child classes
- protected abstract void turnOnImpl();
-
- protected abstract void turnOffImpl();
-
- // State
- class State {
- public static final int kOff = 0;
- public static final int kTurningOn = 1;
- public static final int kOn = 2;
- public static final int kTurningOff = 3;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- protected int getState() {
- int state;
- synchronized (this.mState) {
- state = this.mState;
- }
- return state;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- private void setState(int newState) {
- synchronized (this.mState) {
- this.mState = newState;
- }
- }
-
- public Device(String name) {
- this.mState = State.kOff;
- this.mName = name;
- }
-
- // Attributes
- private String mName;
-
- // State
- private Integer mState;
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ExpConfig.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ExpConfig.java
deleted file mode 100644
index 90137bbd..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ExpConfig.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2018, contributors. All rights reserved.
- *
- * Contributor: Gyeonghwan Hong
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-public class ExpConfig {
- public static final boolean VERBOSE_SEGMENT_DEQUEUE_CTRL = true;
- public static final boolean VERBOSE_SEGMENT_DEQUEUE_DATA = false;
- public static final boolean VERBOSE_RECEIVER_TIME = false;
- public static final boolean VERBOSE_CLIENT_ADAPTER = false;
- public static final boolean VERBOSE_BANDWIDTH_UPDATE = false;
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/NetworkSwitcher.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/NetworkSwitcher.java
deleted file mode 100644
index 5e44e560..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/NetworkSwitcher.java
+++ /dev/null
@@ -1,306 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import com.redcarrottt.testapp.Logger;
-
-public class NetworkSwitcher {
- private static final String kTag = "NetworkSwitcher";
-
- // Connect adapter command.
- // It is called by peer through Core.
- void connectAdapterByPeer(int adapterId) {
- int state = this.getState();
- if (state == State.kSwitching) {
- Logger.VERB(kTag, "It's now switching. Cannot connect to adapter " + adapterId);
- return;
- }
- this.setState(State.kSwitching);
- runConnectRequestTx(adapterId);
- }
-
- // Disconnect adapter command.
- // It is called by peer through Core.
- void disconnectAdapterByPeer(int adapterId, int finalSeqNoControl, int finalSeqNoData) {
- int state = this.getState();
- if (state == State.kSwitching) {
- Logger.VERB(kTag, "It's now switching. Cannot disconnect to adapter " + adapterId);
- return;
- }
-
- Core core = Core.singleton();
- ClientAdapter adapter = core.findAdapterById(adapterId);
- if (adapter == null) {
- Logger.WARN(kTag, "Cannot find adapter " + adapterId);
- return;
- }
-
- this.setState(State.kSwitching);
-
- adapter.disconnectOnPeerCommand(onResultDisconnectAdapterByPeer, finalSeqNoControl, finalSeqNoData);
- }
-
- ClientAdapter.DisconnectResultListener onResultDisconnectAdapterByPeer = new ClientAdapter
- .DisconnectResultListener() {
- @Override
- public void onDisconnectResult(boolean isSuccess) {
- NetworkSwitcher switcher = NetworkSwitcher.singleton();
- switcher.doneSwitch();
- }
- };
-
- // Sleep adapter command.
- // It is called by peer through Core.
- void sleepAdapterByPeer(int adapterId) {
- int state = this.getState();
- if (state == State.kSwitching) {
- Logger.VERB(kTag, "It's now switching. Cannot sleep to adapter " + adapterId);
- return;
- }
- this.setState(State.kSwitching);
- ClientAdapter adapter = Core.singleton().findAdapterById(adapterId);
- adapter.sleep(false);
- this.setState(State.kReady);
- }
-
- // Wake up adapter command.
- // It is called by peer through Core.
- void wakeUpAdapterByPeer(int adapterId) {
- int state = this.getState();
- if (state == State.kSwitching) {
- Logger.VERB(kTag, "It's now switching. Cannot sleep to adapter " + adapterId);
- return;
- }
- this.setState(State.kSwitching);
- ClientAdapter adapter = Core.singleton().findAdapterById(adapterId);
- adapter.wakeUp(false);
- this.setState(State.kReady);
- }
-
- // Reconnect adapter command.
- // It is called by Core.
- void reconnectAdapter(ClientAdapter adapter) {
- // If it is disconnecting on purpose, do not reconnect it.
- if (adapter.isDisconnectingOnPurpose()) {
- return;
- }
-
- int state = this.getState();
- if (state == State.kSwitching) {
- Logger.VERB(kTag, adapter.getName() + ": It's now switching. Cannot reconnect " +
- "adapter" + ".");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- this.reconnectAdapter(adapter);
- return;
- }
- this.setState(State.kSwitching);
- runReconnectAdapterTx(adapter);
- }
-
- // Notification of switch done event
- private void doneSwitch() {
- int state = this.getState();
- switch (state) {
- case State.kSwitching:
- this.setState(State.kReady);
- break;
- case State.kReady:
- break;
- }
- }
-
- // State Getter/Setter
- @SuppressWarnings("SynchronizeOnNonFinalField")
- private int getState() {
- int state;
- synchronized (this.mState) {
- state = this.mState;
- }
- return state;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- private void setState(int newState) {
- synchronized (this.mState) {
- this.mState = newState;
- }
- }
-
- class State {
- public static final int kReady = 0;
- public static final int kSwitching = 1;
- }
-
- // State
- private Integer mState;
-
- // Singleton
- private static NetworkSwitcher sSingleton;
-
- public static NetworkSwitcher singleton() {
- if (sSingleton == null) {
- sSingleton = new NetworkSwitcher();
- }
- return sSingleton;
- }
-
- // Constructor
- private NetworkSwitcher() {
- // Since there is no NetworkSwitcher for Android implementation,
- // NetworkSwitcher's initial state goes to Running at beginning.
- this.mState = State.kReady;
- }
-
- // Transactions
- // ----------------------------------------------------------------
- // Singleton runner
- private static boolean runConnectRequestTx(int adapterId) {
- if (sOngoingConnectRequest == null) {
- sOngoingConnectRequest = new ConnectRequestTransaction(adapterId);
- sOngoingConnectRequest.start();
- return true;
- } else {
- Logger.WARN(kTag, "Already connecting");
- return false;
- }
- }
-
- private static void doneConnectRequestTx(boolean isSuccess) {
- sOngoingConnectRequest = null;
- if (!isSuccess) {
- Logger.WARN(kTag, "Connection request failed");
- }
- NetworkSwitcher.singleton().doneSwitch();
- sOngoingConnectRequest = null;
- }
-
- private static void runReconnectAdapterTx(ClientAdapter adapter) {
- if (sOngoingReconnectAdapter == null) {
- sOngoingReconnectAdapter = new ReconnectAdapterTransaction(adapter);
- sOngoingReconnectAdapter.start();
- } else {
- Logger.WARN(kTag, "Already stopping core");
- }
- }
-
- private static void restartReconnectAdapterTx(ClientAdapter adapter) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- sOngoingReconnectAdapter = null;
- runReconnectAdapterTx(adapter);
- }
-
- private static ConnectRequestTransaction sOngoingConnectRequest = null;
- private static ReconnectAdapterTransaction sOngoingReconnectAdapter = null;
-
- private static class ConnectRequestTransaction {
- private ConnectRequestTransaction(int adapterId) {
- this.mAdapterId = adapterId;
- this.onConnectAdapter = new OnConnectAdapter();
- }
-
- void start() {
- ClientAdapter adapter = Core.singleton().findAdapterById(this.mAdapterId);
- if (adapter == null) {
- Logger.ERR(kTag, "Connecting requested adapter is failed");
- doneConnectRequestTx(false);
- return;
- }
- adapter.connect(onConnectAdapter, false);
- }
-
- private OnConnectAdapter onConnectAdapter;
-
- class OnConnectAdapter implements ClientAdapter.ConnectResultListener {
- @Override
- public void onConnectResult(boolean isSuccess) {
- if (!isSuccess) {
- Logger.ERR(kTag, "Connecting requested adapter is failed");
- doneConnectRequestTx(false);
- return;
- }
- Logger.VERB(kTag, "Connecting requested adapter is done");
- doneConnectRequestTx(true);
- }
- }
-
- private int mAdapterId;
- }
-
- private static class ReconnectAdapterTransaction {
- private ReconnectAdapterTransaction(ClientAdapter targetAdapter) {
- this.onConnectAdapter = new OnConnectAdapter();
- this.onDisconnectAdapter = new OnDisconnectAdapter();
- this.mTargetAdapter = targetAdapter;
- }
-
- private ClientAdapter mTargetAdapter;
-
- void start() {
- if (this.mTargetAdapter == null) {
- Logger.ERR(kTag, "Reconnecting adapter is failed: retry");
- restartReconnectAdapterTx(mTargetAdapter);
- return;
- }
- this.mTargetAdapter.disconnectOnFailure(onDisconnectAdapter);
- }
-
- private OnDisconnectAdapter onDisconnectAdapter;
-
- class OnDisconnectAdapter implements ClientAdapter.DisconnectResultListener {
- @Override
- public void onDisconnectResult(boolean isSuccess) {
- if (!isSuccess) {
- Logger.ERR(kTag, "Reconnecting adapter is failed: retry");
- restartReconnectAdapterTx(mTargetAdapter);
- return;
- }
- if (mTargetAdapter == null) {
- Logger.ERR(kTag, "Reconnecting adapter is failed: retry");
- restartReconnectAdapterTx(mTargetAdapter);
- return;
- }
-
- mTargetAdapter.connect(onConnectAdapter, false);
- }
- }
-
- private OnConnectAdapter onConnectAdapter;
-
- class OnConnectAdapter implements ClientAdapter.ConnectResultListener {
- @Override
- public void onConnectResult(boolean isSuccess) {
- if (!isSuccess) {
- Logger.ERR(kTag, "Reconnecting adapter is failed: retry");
- restartReconnectAdapterTx(mTargetAdapter);
- return;
- }
-
- Logger.VERB(kTag, "Reconnecting adapter is done");
- NetworkSwitcher.singleton().doneSwitch();
- }
- }
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/OnConnectResult.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/OnConnectResult.java
deleted file mode 100644
index 460aa60f..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/OnConnectResult.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-public interface OnConnectResult {
- public void onDoneConnect(boolean isSuccess);
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/OnDisconnectResult.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/OnDisconnectResult.java
deleted file mode 100644
index a6848747..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/OnDisconnectResult.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-public interface OnDisconnectResult {
- public void onDoneDisconnect(boolean isSuccess);
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/OnDiscoverResult.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/OnDiscoverResult.java
deleted file mode 100644
index 767da676..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/OnDiscoverResult.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-public interface OnDiscoverResult {
- public void onDoneDiscover(boolean isSuccess);
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/P2PClient.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/P2PClient.java
deleted file mode 100644
index 3a8b2af9..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/P2PClient.java
+++ /dev/null
@@ -1,196 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import com.redcarrottt.testapp.Logger;
-
-interface DiscoverAndConnectResultListener {
- void onDiscoverAndConnectResult(boolean isSuccess);
-}
-
-interface DisconnectResultListener {
- void onDisconnectResult(boolean isSuccess);
-}
-
-public abstract class P2PClient {
- private final String kTag = "P2PClient";
-
- // Main function 1: Discover and connect
- public void discoverAndConnect(DiscoverAndConnectResultListener resultListener) {
- if (this.getState() != State.kDisconnected) {
- Logger.ERR(kTag, "It's already connected or discovering is in progress");
- doneDiscoverAndConnectTx(resultListener, false);
- return;
- }
- runDiscoverAndConnectTx(resultListener);
- }
-
- private void runDiscoverAndConnectTx(DiscoverAndConnectResultListener resultListener) {
- if (sOngoingDiscoverConnectTx == null) {
- sOngoingDiscoverConnectTx = new DiscoverAndConnectTransaction();
- sOngoingDiscoverConnectTx.start(resultListener);
- } else {
- Logger.ERR(kTag, "Discover/Connect has already been in progress.");
- doneDiscoverAndConnectTx(resultListener, false);
- }
- }
-
- private void doneDiscoverAndConnectTx(DiscoverAndConnectResultListener resultListener,
- boolean isSuccess) {
- sOngoingDiscoverConnectTx = null;
- if (isSuccess) {
- this.setState(State.kConnected);
- } else {
- this.setState(State.kDisconnected);
- }
-
- if (resultListener != null) {
- resultListener.onDiscoverAndConnectResult(isSuccess);
- }
- }
-
- private static DiscoverAndConnectTransaction sOngoingDiscoverConnectTx = null;
-
- class DiscoverAndConnectTransaction {
- private DiscoverAndConnectResultListener mResultListener;
-
- DiscoverAndConnectTransaction() {
- }
-
- void start(DiscoverAndConnectResultListener resultListener) {
- this.mResultListener = resultListener;
-
- setState(State.kDiscovering);
- discoverImpl(onDiscoverResult);
- }
-
- private OnDiscoverResult onDiscoverResult = new OnDiscoverResult() {
- @Override
- public void onDoneDiscover(boolean isSuccess) {
- if (isSuccess) {
- setState(State.kConnecting);
- connectImpl(onConnectResult);
- } else {
- doneDiscoverAndConnectTx(mResultListener, false);
- }
- }
- };
-
- private OnConnectResult onConnectResult = new OnConnectResult() {
- @Override
- public void onDoneConnect(boolean isSuccess) {
- doneDiscoverAndConnectTx(mResultListener, isSuccess);
- }
- };
- }
-
- // Main function 2: Disconnect
- public void disconnect(DisconnectResultListener resultListener) {
- int state = this.getState();
- if (state == State.kDisconnected || state == State.kDisconnecting) {
- Logger.ERR(kTag, "It's already disconnected or disconnecting is in progress");
- doneDisconnectTx(resultListener, false);
- return;
- }
- runDisconnectTx(resultListener);
- }
-
- private void runDisconnectTx(DisconnectResultListener resultListener) {
- if (sOngoingDisconnectTx == null) {
- sOngoingDisconnectTx = new DisconnectTransaction();
- sOngoingDisconnectTx.start(resultListener);
- } else {
- Logger.ERR(kTag, "Disconnection has already been in progress.");
- doneDisconnectTx(resultListener, false);
- }
- }
-
- private void doneDisconnectTx(DisconnectResultListener resultListener, boolean isSuccess) {
- sOngoingDisconnectTx = null;
- if (isSuccess) {
- this.setState(State.kDisconnected);
- } else {
- this.setState(State.kConnected);
- }
- if (resultListener != null) {
- resultListener.onDisconnectResult(isSuccess);
- }
- }
-
- private static DisconnectTransaction sOngoingDisconnectTx = null;
-
- class DisconnectTransaction {
- private DisconnectResultListener mResultListener;
-
- DisconnectTransaction() {
- }
-
- void start(DisconnectResultListener resultListener) {
- this.mResultListener = resultListener;
-
- setState(State.kDisconnecting);
- disconnectImpl(onDisconnectResult);
- }
-
- private OnDisconnectResult onDisconnectResult = new OnDisconnectResult() {
- @Override
- public void onDoneDisconnect(boolean isSuccess) {
- doneDisconnectTx(mResultListener, isSuccess);
- }
- };
-
- }
-
- // Implemented by child classes
- protected abstract void discoverImpl(OnDiscoverResult onDiscoverResult);
-
- protected abstract void connectImpl(OnConnectResult onConnectResult);
-
- protected abstract void disconnectImpl(OnDisconnectResult onDisconnectResult);
-
- // State
- class State {
- public static final int kDisconnected = 0;
- public static final int kDiscovering = 1;
- public static final int kConnecting = 2;
- public static final int kConnected = 3;
- public static final int kDisconnecting = 4;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- protected int getState() {
- int state;
- synchronized (this.mState) {
- state = this.mState;
- }
- return state;
- }
-
- @SuppressWarnings("SynchronizeOnNonFinalField")
- private void setState(int newState) {
- synchronized (this.mState) {
- this.mState = newState;
- }
- }
-
- protected P2PClient() {
- this.mState = State.kDisconnected;
- }
-
- // State
- private Integer mState;
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ProtocolManager.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ProtocolManager.java
deleted file mode 100644
index df47ef4a..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/ProtocolManager.java
+++ /dev/null
@@ -1,126 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.nio.ByteBuffer;
-
-class ProtocolData {
- short id;
- int len;
- byte[] data;
-
- ProtocolData() {
- id = 0;
- len = 0;
- data = null;
- }
-}
-
-class ProtocolManager {
- static public final int kProtocolHeaderSize = 6;
-
- static private short sPacketId;
- static private byte[] sSerializedVector = null;
-
- static private void serialize_header(ProtocolData pd, byte[] vec_ptr) {
- if (vec_ptr == null) throw new AssertionError();
-
- int vec_offset = 0;
-
- ByteBuffer buffer = ByteBuffer.allocate(2);
-
- buffer.putShort(pd.id);
- byte[] net_id = buffer.array();
-
- buffer = ByteBuffer.allocate(4);
- buffer.putInt(pd.len);
- byte[] net_len = buffer.array();
-
- System.arraycopy(net_id, 0, vec_ptr, vec_offset, 2);
- vec_offset += 2;
-
- System.arraycopy(net_len, 0, vec_ptr, vec_offset, 4);
- }
-
- static public ProtocolData data_to_protocol_data(byte[] buf, int len) {
- ProtocolData pd = new ProtocolData();
-
- pd.id = sPacketId++;
- pd.len = len;
- pd.data = buf;
-
- return pd;
- }
-
- static public int serialize(ProtocolData protocolData, byte[] buf, int offset, int
- payload_size) {
- int vec_size;
- int data_offset;
-
- data_offset = kProtocolHeaderSize;
- vec_size = data_offset + payload_size;
-
- sSerializedVector = new byte[vec_size];
-
- serialize_header(protocolData, sSerializedVector);
- System.arraycopy(buf, offset, sSerializedVector, data_offset, payload_size);
-
- if (sSerializedVector == null) throw new AssertionError();
-
- return vec_size;
- }
-
- static void parse_header(byte[] serialized, ProtocolData protocolData) {
- if (serialized == null || protocolData == null) throw new AssertionError();
-
- int vec_offset = 0;
- ByteBuffer buffer = ByteBuffer.allocate(2);
-
- buffer.put(serialized, vec_offset, 2);
- protocolData.id = buffer.getShort(0);
- vec_offset += 2;
-
- buffer = ByteBuffer.allocate(4);
- buffer.put(serialized, vec_offset, 4);
- protocolData.len = buffer.getInt(0);
- }
-
- static public int send_packet(int packetSize, boolean isControl) {
- SegmentManager sm = SegmentManager.singleton();
-
- return sm.send_to_segment_manager(sSerializedVector, packetSize, isControl);
- }
-
- static public int recv_packet(byte[] buf, boolean isControl) {
- if (buf == null) throw new AssertionError();
-
- ProtocolData protocolData = new ProtocolData();
- SegmentManager sm = SegmentManager.singleton();
-
- byte[] data = sm.recv_from_segment_manager(protocolData, isControl);
-
- System.arraycopy(data, 0, buf, 0, (protocolData.len < buf.length) ? protocolData.len :
- buf.length);
-
-
- return protocolData.len;
- }
-
-// private static String kTag = "protocol manager";
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/SegmentManager.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/SegmentManager.java
deleted file mode 100644
index 87e8a2bd..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/SegmentManager.java
+++ /dev/null
@@ -1,488 +0,0 @@
-package com.redcarrottt.sc.internal;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import com.redcarrottt.testapp.Logger;
-
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.LinkedList;
-import java.util.ListIterator;
-
-/*
- Segment is the minimum unit of the sending data through the network.
- Segment header (sequence # + len + flag) is 16bytes (4bytes + 4bytes + 4bytes)
- */
-class Segment {
- int seq_no;
- int len;
- int flag;
- byte[] data;
-
- Segment() {
- seq_no = -1;
- len = 0;
- flag = 0;
- data = new byte[SegmentManager.kSegSize + SegmentManager.kSegHeaderSize];
- }
-}
-
-class SegmentManager {
- static private SegmentManager instance = null;
- static public final int kSegSize = 512;
- private static final int kSegFreeThreshold = 256;
-
- static public final int kSegHeaderSize = 12;
-
- static final int kSQSendData = 0;
- static final int kSQRecvData = 1;
- static final int kSQSendControl = 2;
- static final int kSQRecvControl = 3;
- private static final int kNumSQ = 4;
- static final int kSQUnknown = 999;
-
- static final int kDeqSendControlData = 0;
- static final int kDeqRecvData = 1;
- static final int kDeqRecvControl = 2;
- private static final int kNumDeq = 3;
-
- static final int kSNData = 0;
- static final int kSNControl = 1;
- private static final int kNumSN = 2;
-
- static final short kSegFlagMF = 1;
- static final short kSegFlagControl = 2;
-
- private int[] mNextSeqNo;
- private int[] mExpectedSeqNo;
-
- private LinkedList[] mQueues;
- private Object[] mDequeueCond;
- private final LinkedList mFailedSendingQueue;
- private LinkedList[] mPendingQueue;
- private int[] mQueueLengths;
-
- private static String kTag = "SegmentManager";
-
- private final LinkedList mFreeSegments;
- private int mFreeSegmentsSize;
-
- private SegmentManager() {
- this.mQueues = new LinkedList[kNumSQ];
- for (int i = 0; i < kNumSQ; i++) {
- this.mQueues[i] = new LinkedList();
- }
-
- this.mDequeueCond = new Object[kNumDeq];
- for (int i = 0; i < kNumDeq; i++) {
- this.mDequeueCond[i] = new Object();
- }
-
- this.mFailedSendingQueue = new LinkedList();
- this.mPendingQueue = new LinkedList[kNumSQ];
- for (int i = 0; i < kNumSQ; i++) {
- this.mPendingQueue[i] = new LinkedList();
- }
-
- this.mQueueLengths = new int[kNumSQ];
- for (int i = 0; i < kNumSQ; i++) {
- this.mQueueLengths[i] = 0;
- }
-
- this.mExpectedSeqNo = new int[kNumSQ];
- for (int i = 0; i < kNumSQ; i++) {
- this.mExpectedSeqNo[i] = 0;
- }
-
- this.mNextSeqNo = new int[kNumSN];
- for (int i = 0; i < kNumSN; i++) {
- this.mNextSeqNo[i] = 0;
- }
-
- this.mFreeSegments = new LinkedList();
- }
-
-
- static public SegmentManager singleton() {
- if (instance == null) instance = new SegmentManager();
-
- return instance;
- }
-
- private int getNextSeqNo(int seq_num_type, int length) {
- int ret = mNextSeqNo[seq_num_type];
- mNextSeqNo[seq_num_type] += length;
- return ret;
- }
-
- // Wait data before disconnection
- public void waitReceiving(int wait_seq_no_control, int wait_seq_no_data) {
- synchronized (this.mWaitReceiving) {
- this.mIsWaitReceiving = true;
- this.mWaitSeqNoControl = wait_seq_no_control;
- this.mWaitSeqNoData = wait_seq_no_data;
- try {
- this.mWaitReceiving.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-
- public int getLastSeqNoControl() {
- return this.mNextSeqNo[kSNControl] - 1;
- }
-
- public int getLastSeqNoData() {
- return this.mNextSeqNo[kSNData] - 1;
- }
-
- private void checkReceivingDone() {
- boolean is_wakeup = false;
- synchronized (this.mWaitReceiving) {
- if (this.mIsWaitReceiving && this.mExpectedSeqNo[kSQRecvControl] >= this
- .mWaitSeqNoControl && this.mExpectedSeqNo[kSQRecvData] >= this.mWaitSeqNoData) {
- is_wakeup = true;
- }
-
- if (is_wakeup) {
- this.mWaitReceiving.notifyAll();
- this.mIsWaitReceiving = false;
- }
- }
- }
-
- public void wakeUpDequeueWaiting(int dequeueType) {
- synchronized (mDequeueCond[dequeueType]) {
- this.mDequeueCond[dequeueType].notifyAll();
- }
- }
-
- boolean mIsWaitReceiving = false;
- int mWaitSeqNoControl = 0;
- int mWaitSeqNoData = 0;
- Object mWaitReceiving = new Object();
-
- public int send_to_segment_manager(byte[] data, int length, boolean isControl) {
- if (data == null || length <= 0) throw new AssertionError();
-
- int offset = 0;
- int num_of_segments = (length + kSegSize - 1) / kSegSize;
- int seq_num_type = (isControl) ? kSNControl : kSNData;
- int allocated_seq_no = getNextSeqNo(seq_num_type, num_of_segments);
- int seg_idx;
- for (seg_idx = 0; seg_idx < num_of_segments; seg_idx++) {
- int seg_len = (length - offset < kSegSize) ? (length - offset) : kSegSize;
- Segment seg = get_free_segment();
-
- // 0~3: seq_no
- seg.seq_no = allocated_seq_no++;
-
- // 4~7: len
- seg.len = seg_len;
-
- // 8~11: flag
- int flag = 0;
- if (offset + seg_len < length) flag = flag | kSegFlagMF;
- if (isControl) flag = flag | kSegFlagControl;
- seg.flag = flag;
-
- // 12~: data
- System.arraycopy(data, offset, seg.data, kSegHeaderSize, seg_len);
- offset += seg_len;
-
- serialize_segment_header(seg);
-
- if (isControl) {
- enqueue(kSQSendControl, seg);
- } else {
- enqueue(kSQSendData, seg);
- }
- }
-
- return 0;
- }
-
- private void serialize_segment_header(Segment segment) {
- ByteBuffer buffer = ByteBuffer.allocate(4);
- buffer.putInt(segment.seq_no);
- byte[] net_seq_no = buffer.array();
-
- buffer = ByteBuffer.allocate(4);
- buffer.putInt(segment.len);
- byte[] net_len = buffer.array();
-
- buffer = ByteBuffer.allocate(4);
- buffer.putInt(segment.flag);
- byte[] net_flag = buffer.array();
-
- System.arraycopy(net_seq_no, 0, segment.data, 0, 4);
- System.arraycopy(net_len, 0, segment.data, 4, 4);
- System.arraycopy(net_flag, 0, segment.data, 8, 4);
- }
-
- public byte[] recv_from_segment_manager(ProtocolData protocolData, boolean isControl) {
- if (protocolData == null) throw new AssertionError();
-
- byte[] serialized;
- int offset = 0;
- int data_size;
- boolean cont;
-
- Segment seg;
- do {
- if (isControl) {
- seg = dequeue(kDeqRecvControl);
- } else {
- seg = dequeue(kDeqRecvData);
- }
- } while (seg == null);
- ProtocolManager.parse_header(Arrays.copyOfRange(seg.data, kSegHeaderSize, seg.data
- .length), protocolData);
- if (protocolData.len == 0) return null;
-
- //Logger.DEBUG(kTag, "pd.len is " + pd.len);
- serialized = new byte[protocolData.len];
-
- // Handle the first segment of the data bulk, because it contains protocol data
- data_size = seg.len - ProtocolManager.kProtocolHeaderSize;
- System.arraycopy(seg.data, kSegHeaderSize + ProtocolManager.kProtocolHeaderSize,
- serialized, offset, data_size);
- offset += data_size;
-
- cont = ((seg.flag & kSegFlagMF) != 0);
- free_segment(seg);
-
- while (cont) {
- do {
- if (isControl) {
- seg = dequeue(kDeqRecvControl);
- } else {
- seg = dequeue(kDeqRecvData);
- }
- } while (seg == null);
- data_size = seg.len;
- System.arraycopy(seg.data, kSegHeaderSize, serialized, offset, data_size);
- cont = ((seg.flag & kSegFlagMF) != 0);
- offset += data_size;
- free_segment(seg);
- }
-
- return serialized;
- }
-
- @SuppressWarnings("unchecked")
- public void enqueue(int queueType, Segment segment) {
- if (queueType >= kNumSQ) throw new AssertionError();
-
- int dequeueType;
- switch (queueType) {
- case kSQRecvControl:
- dequeueType = kDeqRecvControl;
- break;
- case kSQRecvData:
- dequeueType = kDeqRecvData;
- break;
- case kSQSendControl:
- case kSQSendData:
- dequeueType = kDeqSendControlData;
- break;
- default:
- Logger.ERR(kTag, "Enqueue: Unknown queue type: " + queueType);
- return;
- }
-
-
- boolean segmentEnqueued = false;
-
- synchronized (this.mQueues[queueType]) {
- if (segment.seq_no == this.mExpectedSeqNo[queueType]) {
- // Case 1. this seq no. = expected seq no.
- // In-order segments -> enqueue to the target queue
- this.mExpectedSeqNo[queueType]++;
-
- this.mQueues[queueType].offerLast(segment);
- this.mQueueLengths[queueType]++;
- segmentEnqueued = true;
- } else if (segment.seq_no < this.mExpectedSeqNo[queueType]) {
- // Case 2. this seq no. < expected seq no.
- // Duplicated segments -> ignore
- return;
- } else {
- // Case 3. this seq no. > expected seq no.
- // Out-of-order segments -> insert at the proper position of pending queue
- ListIterator it = this.mPendingQueue[queueType].listIterator();
- while (it.hasNext()) {
- Segment walker = (Segment) it.next();
- if (walker.seq_no > segment.seq_no) break;
- }
- it.add(segment);
- Logger.WARN(kTag, "Pending Queue: (" + queueType + ") incoming=" + segment
- .seq_no + " / expected_next=" + this.mExpectedSeqNo[queueType]);
- }
-
- // TODO: why do that?
- ListIterator it = this.mPendingQueue[queueType].listIterator();
- while (it.hasNext()) {
- Segment walker = (Segment) it.next();
-
- if (walker.seq_no != this.mExpectedSeqNo[queueType]) break;
-
- this.mQueues[queueType].offerLast(walker);
- this.mQueueLengths[queueType]++;
- this.mExpectedSeqNo[queueType]++;
- segmentEnqueued = true;
-
- it.remove();
- }
- }
-
- if (segmentEnqueued) {
- this.wakeUpDequeueWaiting(dequeueType);
- }
-
- this.checkReceivingDone();
- }
-
- public Segment dequeue(int dequeueType) {
- assert (dequeueType < kNumDeq);
- synchronized (this.mDequeueCond[dequeueType]) {
- // If queue is empty, wait until some segment is enqueued
- boolean isWaitRequired = false;
- switch (dequeueType) {
- case kDeqSendControlData:
- isWaitRequired = ((this.mQueueLengths[kSQSendControl] == 0) && (this
- .mQueueLengths[kSQSendData] == 0));
- break;
- case kDeqRecvControl:
- isWaitRequired = (this.mQueueLengths[kSQRecvControl] == 0);
- break;
- case kDeqRecvData:
- isWaitRequired = (this.mQueueLengths[kSQRecvData] == 0);
- break;
- }
- if (isWaitRequired) {
- try {
- this.mDequeueCond[dequeueType].wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- // Set target queue type
- int targetQueueType = kSQUnknown;
- switch (dequeueType) {
- case kDeqSendControlData:
- if (this.mQueueLengths[kSQSendControl] != 0) {
- // Priority 1. Dequeue send control queue
- targetQueueType = kSQSendControl;
- } else if (this.mQueueLengths[kSQSendData] != 0) {
- // Priority 2. Dequeue send data queue
- targetQueueType = kSQSendData;
- } else {
- return null;
- }
- break;
- case kDeqRecvControl:
- targetQueueType = kSQRecvControl;
- break;
- case kDeqRecvData:
- targetQueueType = kSQRecvData;
- break;
- default:
- Logger.ERR(kTag, "Dequeue failed: invalid dequeue type (Dequeue=" +
- dequeueType + ")");
- return null;
- }
-
- // Check queue type
- if (targetQueueType >= kNumSQ) {
- Logger.ERR(kTag, "Dequeue failed: invalid queue type (Dequeue=" + dequeueType +
- ")");
- return null;
- }
-
- // Dequeue from queue
- synchronized (this.mQueues[targetQueueType]) {
- // Check the dequeued segment
- Segment segmentDequeued = (Segment) this.mQueues[targetQueueType].pollFirst();
- if (segmentDequeued == null) {
-// Logger.DEBUG(kTag, "Dequeue interrupted: empty queue (queue=" +
-// targetQueueType + ", dequeue=" + dequeueType + ")");
- return null;
- }
- mQueueLengths[targetQueueType]--;
- return segmentDequeued;
- }
- }
- }
-
- public Segment get_free_segment() {
- Segment ret;
- synchronized (mFreeSegments) {
- if (mFreeSegmentsSize == 0) {
- ret = new Segment();
- } else {
- ret = mFreeSegments.pop();
- mFreeSegmentsSize--;
- }
-
- if (ret == null) throw new AssertionError();
-
- ret.seq_no = -1;
- ret.flag = 0;
- ret.len = 0;
- }
- return ret;
- }
-
- public void free_segment(Segment seg) {
- synchronized (mFreeSegments) {
- mFreeSegments.push(seg);
- mFreeSegmentsSize++;
-
- if (mFreeSegmentsSize > kSegFreeThreshold) {
- release_segment_from_free_list(kSegFreeThreshold / 2);
- }
- }
- }
-
- private void release_segment_from_free_list(int threshold) {
- while (mFreeSegmentsSize > threshold) {
- mFreeSegments.pop();
- mFreeSegmentsSize--;
- }
- }
-
- public void failed_sending(Segment seg) {
- synchronized (mFailedSendingQueue) {
- mFailedSendingQueue.offerLast(seg);
- this.wakeUpDequeueWaiting(kDeqSendControlData);
- }
- }
-
- public Segment get_failed_sending() {
- Segment ret;
- synchronized (mFailedSendingQueue) {
- ret = mFailedSendingQueue.pollFirst();
- }
-
- return ret;
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/BtClientAdapter.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/BtClientAdapter.java
deleted file mode 100644
index 89c2ed19..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/BtClientAdapter.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.redcarrottt.sc.internal.bt;
-
-import android.app.Activity;
-
-import com.redcarrottt.sc.internal.ClientAdapter;
-
-public class BtClientAdapter extends ClientAdapter {
- // Singleton
- static public BtClientAdapter singleton(int id, String name, String targetMacAddr, String
- serviceUuid, Activity ownerActivity) {
- if (sSingleton == null) {
- sSingleton = new BtClientAdapter(id, name, targetMacAddr, serviceUuid, ownerActivity);
- }
- return sSingleton;
- }
-
- static private BtClientAdapter sSingleton = null;
-
- // Constructor
- private BtClientAdapter(int id, String name, String targetMacAddr, String serviceUuid,
- Activity ownerActivity) {
- super(id, name);
-
- // Components
- BtDevice device = new BtDevice(ownerActivity);
- BtP2PClient p2pClient = new BtP2PClient();
- RfcommClientSocket clientSocket = new RfcommClientSocket(targetMacAddr, serviceUuid);
-
- // Initialize
- this.initialize(device, p2pClient, clientSocket);
- }
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/BtDevice.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/BtDevice.java
deleted file mode 100644
index bb9e7221..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/BtDevice.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package com.redcarrottt.sc.internal.bt;
-
-import android.app.Activity;
-import android.bluetooth.BluetoothAdapter;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-
-import com.redcarrottt.sc.internal.Device;
-import com.redcarrottt.testapp.Logger;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-class BtDevice extends Device {
- private static final String kTag = "BtDevice";
-
- // TODO: there is no timeout on turn on/off of BtDevice
- @Override
- protected void turnOnImpl() {
- BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
- if (adapter.isEnabled()) {
- Logger.DEBUG(kTag, "Bluetooth is already turned on");
- this.doneTurnOn(true);
- } else {
- // Register bluetooth device on event receiver
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
- Context context = this.mOwnerActivity.getApplicationContext();
- context.registerReceiver(this.mBtDeviceOnEventReceiver, intentFilter);
-
- // turn on adapter command
- adapter.enable();
- }
- }
-
- @Override
- protected void turnOffImpl() {
- // Register bluetooth device off event receiver
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
- Context context = this.mOwnerActivity.getApplicationContext();
- context.registerReceiver(this.mBtDeviceOffEventReceiver, intentFilter);
-
- // turn off adapter command
- BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
- if(!adapter.isEnabled()) {
- Logger.DEBUG(kTag, "Bluetooth is already turned off");
- this.doneTurnOff(true);
- } else {
- adapter.disable();
- }
- }
-
- private BroadcastReceiver mBtDeviceOnEventReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String action = intent.getAction();
- if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
- final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
- BluetoothAdapter.ERROR);
- Logger.DEBUG(kTag, "Bluetooth Adapter state changed: " + state);
- if (state == BluetoothAdapter.STATE_ON) {
- Logger.DEBUG(kTag, "Bluetooth is turned on successfully");
- doneTurnOn(true);
- context.unregisterReceiver(mBtDeviceOnEventReceiver);
- }
- }
- }
- };
-
- private BroadcastReceiver mBtDeviceOffEventReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String action = intent.getAction();
- if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
- final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
- BluetoothAdapter.ERROR);
- Logger.DEBUG(kTag, "Bluetooth Adapter state changed: " + state);
- if (state == BluetoothAdapter.STATE_OFF) {
- Logger.DEBUG(kTag, "Bluetooth is turned off successfully");
- doneTurnOff(true);
- context.unregisterReceiver(mBtDeviceOffEventReceiver);
- }
- }
- }
- };
-
- private Activity mOwnerActivity;
-
- // Constructor
- public BtDevice(Activity ownerActivity) {
- super("Bluetooth");
- this.mOwnerActivity = ownerActivity;
- }
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/BtP2PClient.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/BtP2PClient.java
deleted file mode 100644
index 2c6c3795..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/BtP2PClient.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.redcarrottt.sc.internal.bt;
-
-import com.redcarrottt.sc.internal.OnConnectResult;
-import com.redcarrottt.sc.internal.OnDisconnectResult;
-import com.redcarrottt.sc.internal.OnDiscoverResult;
-import com.redcarrottt.sc.internal.P2PClient;
-
-class BtP2PClient extends P2PClient {
- @Override
- protected void discoverImpl(OnDiscoverResult onDiscoverResult) {
- // Assume that target device has already been bonded.
- onDiscoverResult.onDoneDiscover(true);
- }
-
- @Override
- protected void connectImpl(OnConnectResult onConnectResult) {
- // Assume that target device has already been bonded.
- onConnectResult.onDoneConnect(true);
- }
-
- @Override
- protected void disconnectImpl(OnDisconnectResult onDisconnectResult) {
- // Assume that target device has already been bonded.
- onDisconnectResult.onDoneDisconnect(true);
- }
-
- // Constructor
- public BtP2PClient() {
- }
-
- // Attributes
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/RfcommClientSocket.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/RfcommClientSocket.java
deleted file mode 100644
index d7d69e8b..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/bt/RfcommClientSocket.java
+++ /dev/null
@@ -1,141 +0,0 @@
-package com.redcarrottt.sc.internal.bt;
-
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothSocket;
-
-import com.redcarrottt.sc.internal.ClientSocket;
-import com.redcarrottt.testapp.Logger;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.IOException;
-import java.util.Set;
-import java.util.UUID;
-
-class RfcommClientSocket extends ClientSocket {
- private static String kTag = "RfcommClientSocket";
-
- @Override
- protected boolean openImpl() {
- // Initialize socket
- this.mSocket = null;
- Set pairedBtDevices = BluetoothAdapter.getDefaultAdapter()
- .getBondedDevices();
- for (BluetoothDevice btDevice : pairedBtDevices) {
- Logger.DEBUG(kTag, "Found Device: " + btDevice.getAddress() + " / " + btDevice
- .getName());
- if (btDevice.getAddress().equals(this.mTargetMacAddr)) {
- try {
- this.mSocket = btDevice.createRfcommSocketToServiceRecord(this.mServiceUuid);
- } catch (IOException e) {
- Logger.ERR(kTag, "Socket initialization failed");
- return false;
- }
- }
- }
- if (this.mSocket == null) {
- Logger.ERR(kTag, "Cannot create bluetooth socket");
- return false;
- }
-
- // Try to open socket
- final int kMaxTries = 10;
- for (int tries = 0; tries < kMaxTries; tries++) {
- try {
- this.mSocket.connect();
- this.mInputStream = new BufferedInputStream(this.mSocket.getInputStream());
- this.mOutputStream = new BufferedOutputStream(this.mSocket.getOutputStream());
- break;
- } catch (IOException e) {
- this.mInputStream = null;
- this.mOutputStream = null;
- Logger.WARN(kTag, "Try socket open " + tries);
- }
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- if (this.mSocket.isConnected()) {
- Logger.VERB(kTag, "Socket open success");
- return true;
- } else {
- Logger.ERR(kTag, "Socket open failed!");
- this.mSocket = null;
- return false;
- }
- }
-
- @Override
- protected boolean closeImpl() {
- if (this.mSocket != null && this.mSocket.isConnected()) {
- try {
- this.mInputStream.close();
- this.mOutputStream.close();
- this.mSocket.close();
- Logger.VERB(kTag, "Socket closed");
- return true;
- } catch (IOException e) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- protected int sendImpl(byte[] dataBuffer, int dataLength) {
- if (this.mSocket == null || !this.mSocket.isConnected() || this.mOutputStream == null) {
- Logger.ERR(kTag, "Socket closed! Send failed!");
- return -1;
- }
- try {
- this.mOutputStream.write(dataBuffer, 0, dataLength);
- this.mOutputStream.flush();
- return dataLength;
- } catch (IOException e) {
- Logger.ERR(kTag, "Send failed! / " + e.getMessage());
- return -2;
- }
- }
-
- @Override
- protected int receiveImpl(byte[] dataBuffer, int dataLength) {
- if (this.mSocket == null || !this.mSocket.isConnected() || this.mInputStream == null) {
- Logger.ERR(kTag, "Socket closed! Receive failed!");
- return -1;
- }
- try {
- int receivedBytes = 0;
- while (receivedBytes < dataLength) {
- int onceReceivedBytes = this.mInputStream.read(dataBuffer, receivedBytes,
- dataLength - receivedBytes);
- if (onceReceivedBytes < 0) {
- Logger.ERR(kTag, "Receive failed! 1");
- return -2;
- }
- receivedBytes += onceReceivedBytes;
- }
- return dataLength;
- } catch (IOException e) {
- Logger.ERR(kTag, "Receive failed! 2 / " + e.getMessage());
- return -3;
- }
- }
-
- // Constructor
- RfcommClientSocket(String targetMacAddr, String serviceUuid) {
- this.mTargetMacAddr = targetMacAddr;
- this.mServiceUuid = UUID.fromString(serviceUuid);
- }
-
- private BluetoothSocket mSocket;
- private BufferedInputStream mInputStream;
- private BufferedOutputStream mOutputStream;
-
- // Attributes
- private String mTargetMacAddr;
- private UUID mServiceUuid;
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/TcpClientSocket.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/TcpClientSocket.java
deleted file mode 100644
index 5e839c7c..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/TcpClientSocket.java
+++ /dev/null
@@ -1,162 +0,0 @@
-package com.redcarrottt.sc.internal.wfd;
-
-import com.redcarrottt.sc.internal.ClientSocket;
-import com.redcarrottt.testapp.Logger;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-
-class TcpClientSocket extends ClientSocket {
- private final String kTag = "TcpClientSocket";
-
- @Override
- protected boolean openImpl() {
- Logger.DEBUG(kTag, "Connect to server " + this.getTargetIpAddress() + ":" + this
- .mTargetPort);
-
- // Try to open socket
- final int kMaxTries = 10;
- for (int tries = 0; tries < kMaxTries; tries++) {
- try {
- this.mSocket = new Socket();
- this.mSocket.setReuseAddress(true);
- this.mSocket.bind(null);
- this.mSocket.connect(new InetSocketAddress(this.getTargetIpAddress(), this
- .mTargetPort));
- this.mInputStream = new BufferedInputStream(this.mSocket.getInputStream());
- this.mOutputStream = new BufferedOutputStream(this.mSocket.getOutputStream());
- break;
- } catch (IOException e) {
- this.mSocket = null;
- this.mInputStream = null;
- this.mOutputStream = null;
- Logger.WARN(kTag, "Try socket open " + tries);
- }
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- if (this.mSocket != null && this.mSocket.isConnected()) {
- Logger.VERB(kTag, "Socket open success");
- return true;
- } else {
- Logger.ERR(kTag, "Socket open failed!");
- this.mSocket = null;
- return false;
- }
- }
-
- @Override
- protected boolean closeImpl() {
- if (this.mSocket != null && this.mSocket.isConnected()) {
- try {
- this.mInputStream.close();
- this.mOutputStream.close();
- this.mSocket.close();
- Logger.VERB(kTag, "Socket closed");
- return true;
- } catch (IOException e) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- protected int sendImpl(byte[] dataBuffer, int dataLength) {
- if (this.mSocket == null || !this.mSocket.isConnected() || this.mOutputStream == null) {
- Logger.ERR(kTag, "Socket closed! Send failed!");
- return -1;
- }
- try {
- this.mOutputStream.write(dataBuffer, 0, dataLength);
- this.mOutputStream.flush();
- return dataLength;
- } catch (IOException e) {
- Logger.ERR(kTag, "Send failed! / " + e.getMessage());
- return -2;
- }
- }
-
- @Override
- protected int receiveImpl(byte[] dataBuffer, int dataLength) {
- if (this.mSocket == null || !this.mSocket.isConnected() || this.mInputStream == null) {
- Logger.ERR(kTag, "Socket closed! Receive failed!");
- return -1;
- }
- try {
- int receivedBytes = 0;
- while (receivedBytes < dataLength) {
- int onceReceivedBytes = this.mInputStream.read(dataBuffer, receivedBytes,
- dataLength - receivedBytes);
- if (onceReceivedBytes < 0) {
- Logger.ERR(kTag, "Receive failed! 1");
- return -2;
- }
- receivedBytes += onceReceivedBytes;
- }
-
-// Logger.DEBUG(kTag, "TCP received " + receivedBytes);
- return dataLength;
- } catch (IOException e) {
- Logger.ERR(kTag, "Receive failed! 2 / " + e.getMessage());
- return -3;
- }
- }
-
- // Constructor
- TcpClientSocket(int targetPort) {
- this.mTargetPort = targetPort;
- this.mIsInfoSet = false;
- this.mInfoSetTrigger = new Object();
- }
-
- public void setTcpClientInfo(String targetIpAddress) {
- this.mTargetIpAddress = targetIpAddress;
-
- Logger.DEBUG(kTag, "Notify: WfdP2PInfo");
- this.mIsInfoSet = true;
- synchronized (this.mInfoSetTrigger) {
- this.mInfoSetTrigger.notifyAll();
- }
- }
-
- private String getTargetIpAddress() {
- // Wait until wps pin is set, then get the information.
- if (this.mIsInfoSet) {
- return this.mTargetIpAddress;
- } else {
- Logger.DEBUG(kTag, "Waiting: mTargetIpAddress");
- while (!this.mIsInfoSet) {
- synchronized (this.mInfoSetTrigger) {
- try {
- this.mInfoSetTrigger.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- return this.mTargetIpAddress;
- }
- }
-
- // Components
- private Socket mSocket;
- private BufferedInputStream mInputStream;
- private BufferedOutputStream mOutputStream;
-
- // TODO: adding port to WFD info would be good.
- // Attributes
- private int mTargetPort;
-
- // TCP Socket Info Attributes
- private boolean mIsInfoSet;
- private final Object mInfoSetTrigger;
- private String mTargetIpAddress;
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/WfdClientAdapter.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/WfdClientAdapter.java
deleted file mode 100644
index 91eb22a8..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/WfdClientAdapter.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package com.redcarrottt.sc.internal.wfd;
-
-import android.app.Activity;
-
-import com.redcarrottt.sc.internal.ClientAdapter;
-import com.redcarrottt.sc.internal.ControlMessageListener;
-import com.redcarrottt.sc.internal.ControlMessageProtocol;
-import com.redcarrottt.sc.internal.Core;
-import com.redcarrottt.testapp.Logger;
-
-public class WfdClientAdapter extends ClientAdapter implements ControlMessageListener {
- private static final String kTag = "WfdClientAdapter";
-
- // Singleton
- static public WfdClientAdapter singleton(int id, String name, int targetPort, Activity
- ownerActivity) {
- if (sSingleton == null) {
- sSingleton = new WfdClientAdapter(id, name, targetPort, ownerActivity);
- }
- return sSingleton;
- }
-
- static private WfdClientAdapter sSingleton;
-
- // Constructor
- private WfdClientAdapter(int id, String name, int targetPort, Activity ownerActivity) {
- super(id, name);
-
- // Components
- WfdDevice device = new WfdDevice(ownerActivity);
- this.mP2pClient = new WfdP2PClient(ownerActivity);
- this.mClientSocket = new TcpClientSocket(targetPort);
-
- // Initialize
- this.initialize(device, this.mP2pClient, this.mClientSocket);
-
- // Add WfdP2PClient as a control message listener
- Core.singleton().getControlMessageReceiver().addControlMessageListener(this);
- }
-
- @Override
- public void onReceiveControlMessage(int privateType, String privateMessage) {
- if (privateType == ControlMessageProtocol.PrivType.kWFDInfo) {
- Logger.DEBUG(kTag, "Received WFD info message: " + privateMessage);
- String wfdInfoLines[] = privateMessage.split("\\r?\\n");
- if (wfdInfoLines.length < 3) {
- Logger.ERR(kTag, "WFD info is insufficient: " + wfdInfoLines.length + " < 3");
- }
- String targetMacAddress = wfdInfoLines[0];
- String wpsPin = wfdInfoLines[1];
- String targetIpAddress = wfdInfoLines[2];
-
- mP2pClient.setWfdP2PInfo(targetMacAddress, wpsPin);
- mClientSocket.setTcpClientInfo(targetIpAddress);
- }
- }
-
- // Components
- private WfdP2PClient mP2pClient;
- private TcpClientSocket mClientSocket;
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/WfdDevice.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/WfdDevice.java
deleted file mode 100644
index dfafe28a..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/WfdDevice.java
+++ /dev/null
@@ -1,101 +0,0 @@
-package com.redcarrottt.sc.internal.wfd;
-
-import android.app.Activity;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.net.wifi.WifiManager;
-
-import com.redcarrottt.sc.internal.Device;
-import com.redcarrottt.testapp.Logger;
-
-class WfdDevice extends Device {
- private static final String kTag = "WFdDevice";
-
- // TODO: there is no timeout on turn on/off of WfdDevice
- @Override
- protected void turnOnImpl() {
- WifiManager wifiManager = (WifiManager) this.mOwnerActivity.getApplicationContext()
- .getSystemService(Context.WIFI_SERVICE);
- if (wifiManager == null) {
- doneTurnOn(false);
- } else if (wifiManager.isWifiEnabled()) {
- Logger.DEBUG(kTag, "Wi-fi Direct is already turned on");
- doneTurnOn(true);
- } else {
- // Register wi-fi device on event receiver
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
- Context context = this.mOwnerActivity.getApplicationContext();
- context.registerReceiver(this.mWfdDeviceOnEventReceiver, intentFilter);
-
- // turn on wi-fi command
- wifiManager.setWifiEnabled(true);
- }
- }
-
- @Override
- protected void turnOffImpl() {
- // Register wi-fi device off event receiver
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
- Context context = this.mOwnerActivity.getApplicationContext();
- context.registerReceiver(this.mWfdDeviceOffEventReceiver, intentFilter);
-
- // turn off wi-fi command
- WifiManager wifiManager = (WifiManager) this.mOwnerActivity.getApplicationContext()
- .getSystemService(Context.WIFI_SERVICE);
- if(wifiManager == null) {
- doneTurnOff(true);
- } else if(!wifiManager.isWifiEnabled()) {
- Logger.DEBUG(kTag, "Wi-fi Direct is already turned off");
- doneTurnOff(true);
- } else {
- wifiManager.setWifiEnabled(false);
- }
- }
-
- private BroadcastReceiver mWfdDeviceOnEventReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String action = intent.getAction();
- if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
- final int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
- WifiManager.WIFI_STATE_UNKNOWN);
- Logger.DEBUG(kTag, "Wi-fi Adapter state changed: " + state);
- if (state == WifiManager.WIFI_STATE_ENABLED) {
- Logger.DEBUG(kTag, "Wi-fi is turned on successfully");
- doneTurnOn(true);
- context.unregisterReceiver(mWfdDeviceOnEventReceiver);
- }
- }
- }
- };
-
- private BroadcastReceiver mWfdDeviceOffEventReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String action = intent.getAction();
- if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
- final int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
- WifiManager.WIFI_STATE_UNKNOWN);
- Logger.DEBUG(kTag, "Wi-fi Adapter state changed: " + state);
- if (state == WifiManager.WIFI_STATE_DISABLED) {
- Logger.DEBUG(kTag, "Wi-fi is turned off successfully");
- doneTurnOff(true);
- context.unregisterReceiver(mWfdDeviceOffEventReceiver);
- }
- }
- }
- };
-
- // Constructor
- public WfdDevice(Activity ownerActivity) {
- super("Wi-fi Direct");
- this.mOwnerActivity = ownerActivity;
- }
-
- // Attributes
- private Activity mOwnerActivity;
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/WfdP2PClient.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/WfdP2PClient.java
deleted file mode 100644
index f9b909de..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/sc/internal/wfd/WfdP2PClient.java
+++ /dev/null
@@ -1,390 +0,0 @@
-package com.redcarrottt.sc.internal.wfd;
-
-import android.app.Activity;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.net.NetworkInfo;
-import android.net.wifi.WpsInfo;
-import android.net.wifi.p2p.WifiP2pConfig;
-import android.net.wifi.p2p.WifiP2pDevice;
-import android.net.wifi.p2p.WifiP2pDeviceList;
-import android.net.wifi.p2p.WifiP2pGroup;
-import android.net.wifi.p2p.WifiP2pManager;
-import android.os.Looper;
-
-import com.redcarrottt.sc.internal.OnConnectResult;
-import com.redcarrottt.sc.internal.OnDisconnectResult;
-import com.redcarrottt.sc.internal.OnDiscoverResult;
-import com.redcarrottt.sc.internal.P2PClient;
-import com.redcarrottt.testapp.Logger;
-
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-class WfdP2PClient extends P2PClient {
- private static final String kTag = "WfdP2PClient";
-
- @Override
- protected void discoverImpl(OnDiscoverResult onDiscoverResult) {
- // Run Discover Transaction
- runDiscoverTx(onDiscoverResult);
- }
-
- private void runDiscoverTx(OnDiscoverResult onDiscoverResult) {
- if (sOngoingDiscover == null) {
- sOngoingDiscover = new DiscoverTransaction();
- sOngoingDiscover.run(onDiscoverResult);
- } else {
- Logger.WARN(kTag, "Already stopping core");
- onDiscoverResult.onDoneDiscover(false);
- }
- }
-
- private static void doneDiscoverTx(OnDiscoverResult onDiscoverResult, boolean isSuccess) {
- onDiscoverResult.onDoneDiscover(isSuccess);
- sOngoingDiscover = null;
- }
-
- private static DiscoverTransaction sOngoingDiscover = null;
-
- private class DiscoverTransaction {
- // TODO: Adding timeout on this transaction would be good.
- private OnDiscoverResult mOnDiscoverResult;
- private int mTries = 0;
- private final int kMaxTries = 100;
-
- void run(OnDiscoverResult onDiscoverResult) {
- this.mTries = 0;
- this.mOnDiscoverResult = onDiscoverResult;
- stopP2PDiscovery();
- }
-
- void retry() {
- stopP2PDiscovery();
- }
-
- // Step 1
- private void stopP2PDiscovery() {
- Logger.DEBUG(kTag, "Stop discovery");
- mWFDManager.stopPeerDiscovery(mWFDChannel, new WifiP2pManager.ActionListener() {
- @Override
- public void onSuccess() {
- startP2PDiscovery();
- }
-
- @Override
- public void onFailure(int i) {
- Logger.ERR(kTag, "Stopping discovery failed / reason=" + i);
- mTries++;
- if (mTries < kMaxTries) {
- retry();
- } else {
- doneDiscoverTx(mOnDiscoverResult, false);
- }
- }
- });
- }
-
- // Step 2
- private void startP2PDiscovery() {
- Logger.DEBUG(kTag, "Start discovery");
-
- // Start to listen peer change
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
- Context context = mOwnerActivity.getApplicationContext();
- this.mPeersChangedReceiver = new PeersChangedReceiver();
- context.registerReceiver(mPeersChangedReceiver, intentFilter);
- this.mPeerListListener = new PeerListListener();
-
- // Discover peers
- mWFDManager.discoverPeers(mWFDChannel, null);
- }
-
- // Step 4
- private PeersChangedReceiver mPeersChangedReceiver;
-
- private class PeersChangedReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- assert action != null;
- if (action.equals(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)) {
- Logger.DEBUG(kTag, "Peers changed event");
-
- // Request peer list
- Logger.DEBUG(kTag, "Request WFD peers");
- mWFDManager.requestPeers(mWFDChannel, mPeerListListener);
- }
- }
- }
-
- ;
-
- // Step 5
- private PeerListListener mPeerListListener;
-
- class PeerListListener implements WifiP2pManager.PeerListListener {
- private Lock mCallbackLock;
- private Boolean mIsPeerFound;
-
- PeerListListener() {
- this.mCallbackLock = new ReentrantLock();
- this.mIsPeerFound = false;
- }
-
- @Override
- public void onPeersAvailable(WifiP2pDeviceList peers) {
- final WifiP2pDeviceList kPeers = peers;
- // Since getting peer device address requires locks, it should run on child thread.
- Thread childThread = new Thread() {
- @Override
- public void run() {
- if (mCallbackLock.tryLock()) {
- try {
- synchronized (mIsPeerFound) {
- if (!mIsPeerFound) {
- Logger.DEBUG(kTag, "Got peer list (Target=" +
- getTargetMacAddress() + ")");
- for (WifiP2pDevice p2pDevice : kPeers.getDeviceList()) {
- Logger.DEBUG(kTag, "Peer: " + p2pDevice.deviceAddress
- + " / " + p2pDevice.deviceName + " / " +
- p2pDevice.status);
-
- if (p2pDevice.deviceAddress.equals
- (getTargetMacAddress()) && p2pDevice.status
- == WifiP2pDevice.AVAILABLE) {
- mFoundWFDDevice = p2pDevice;
- Logger.DEBUG(kTag, "Peer found");
- mIsPeerFound = true;
- break;
- }
- }
- }
- }
-
- // Unregister PeersChangedReceiver
- if (mPeerListListener != null) {
- mOwnerActivity.getApplicationContext().unregisterReceiver
- (mPeersChangedReceiver);
- mPeerListListener = null;
- }
-
- synchronized (mIsPeerFound) {
- if (mIsPeerFound) {
- doneDiscoverTx(mOnDiscoverResult, true);
- } else {
- mTries++;
- if (mTries < kMaxTries) {
- retry();
- } else {
- doneDiscoverTx(mOnDiscoverResult, false);
- }
- }
- }
- } finally {
- mCallbackLock.unlock();
- }
- }
- }
- };
- childThread.start();
- }
- }
- }
-
- private WifiP2pDevice mFoundWFDDevice = null;
-
- // TODO: Adding timeout on this transaction would be good.
- @Override
- protected void connectImpl(OnConnectResult onConnectResult) {
- if (this.mFoundWFDDevice == null) {
- Logger.ERR(kTag, "Not found target WFD device");
- onConnectResult.onDoneConnect(false);
- return;
- }
-
- // Start to listen P2P connection event
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
- Context context = mOwnerActivity.getApplicationContext();
- mWFDConnectionReceiver.setOnConnectResult(onConnectResult);
- context.registerReceiver(mWFDConnectionReceiver, intentFilter);
-
- // Setting P2P config
- Logger.DEBUG(kTag, "Connect WFD Peer");
- WifiP2pDevice p2pDevice = this.mFoundWFDDevice;
- WifiP2pConfig p2pConfig = new WifiP2pConfig();
- p2pConfig.deviceAddress = p2pDevice.deviceAddress;
- if (p2pDevice.wpsKeypadSupported()) {
- Logger.DEBUG(kTag, "WPS Method: Keypad");
- p2pConfig.wps.setup = WpsInfo.KEYPAD;
- p2pConfig.wps.pin = this.getWpsPin();
- } else if (p2pDevice.wpsPbcSupported()) {
- Logger.DEBUG(kTag, "WPS Method: PBC - Unsupported");
- p2pConfig.wps.setup = WpsInfo.PBC;
- onConnectResult.onDoneConnect(false);
- return;
- } else if (p2pDevice.wpsDisplaySupported()) {
- Logger.DEBUG(kTag, "WPS Method: Display - Unsupported");
- onConnectResult.onDoneConnect(false);
- return;
- }
- p2pConfig.groupOwnerIntent = 0;
-
- // P2P connection request
- final OnConnectResult fOnConnectResult = onConnectResult;
- Logger.DEBUG(kTag, "Request to connect: " + p2pDevice.deviceName + " " + p2pDevice
- .deviceAddress + " (" + p2pConfig.wps.pin + ")");
- mWFDManager.connect(mWFDChannel, p2pConfig, new WifiP2pManager.ActionListener() {
- @Override
- public void onSuccess() {
- Logger.DEBUG(kTag, "WFD Connection Success");
- }
-
- @Override
- public void onFailure(int i) {
- Logger.WARN(kTag, "WFD Connection Failure / reason=" + i + " - retry to connect...");
- connectImpl(fOnConnectResult);
- }
- });
- }
-
- private WFDConnectionReceiver mWFDConnectionReceiver = new WFDConnectionReceiver();
-
- private class WFDConnectionReceiver extends BroadcastReceiver {
- private OnConnectResult mOnConnectResult = null;
-
- public void setOnConnectResult(OnConnectResult onConnectResult) {
- this.mOnConnectResult = onConnectResult;
- }
-
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- assert (action != null);
-
- if (action.equals(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)) {
- NetworkInfo netInfo = (NetworkInfo) intent.getParcelableExtra(WifiP2pManager
- .EXTRA_NETWORK_INFO);
- Logger.DEBUG(kTag, "Wi-fi direct connection change detected! " + netInfo.toString
- ());
- if (netInfo.isConnected()) {
- Logger.DEBUG(kTag, "Wi-fi direct Connected!");
- WifiP2pGroup p2pGroup = intent.getParcelableExtra(WifiP2pManager
- .EXTRA_WIFI_P2P_GROUP);
- String goMacAddress = p2pGroup.getOwner().deviceAddress;
- Logger.DEBUG(kTag, "Group owner address: " + goMacAddress);
- if (goMacAddress != null && goMacAddress.equals(getTargetMacAddress())) {
- context.unregisterReceiver(mWFDConnectionReceiver);
- mOnConnectResult.onDoneConnect(true);
- }
- }
- }
- }
- }
-
- @Override
- protected void disconnectImpl(OnDisconnectResult onDisconnectResult) {
- final OnDisconnectResult kOnDisconnectResult = onDisconnectResult;
- mWFDManager.removeGroup(mWFDChannel, new WifiP2pManager.ActionListener() {
- @Override
- public void onSuccess() {
- kOnDisconnectResult.onDoneDisconnect(true);
- }
-
- @Override
- public void onFailure(int i) {
- kOnDisconnectResult.onDoneDisconnect(false);
- }
- });
- }
-
- public void setWfdP2PInfo(String targetMacAddress, String wpsPin) {
- this.mTargetMacAddress = targetMacAddress;
- this.mWpsPin = wpsPin;
-
- Logger.DEBUG(kTag, "Notify: WfdP2PInfo");
- this.mIsInfoSet = true;
- synchronized (this.mInfoSetTrigger) {
- this.mInfoSetTrigger.notifyAll();
- }
- }
-
- private String getTargetMacAddress() {
- // Wait until target mac address is set, then get the information.
- if (this.mIsInfoSet) {
- return this.mTargetMacAddress;
- } else {
- Logger.DEBUG(kTag, "Waiting: mTargetMacAddress");
- while (!this.mIsInfoSet) {
- synchronized (this.mInfoSetTrigger) {
- try {
- this.mInfoSetTrigger.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- Logger.DEBUG(kTag, "Got: mTargetMacAddress");
- return this.mTargetMacAddress;
- }
- }
-
- private String getWpsPin() {
- // Wait until wps pin is set, then get the information.
- if (this.mIsInfoSet) {
- return this.mWpsPin;
- } else {
- Logger.DEBUG(kTag, "Waiting: mWpsPin");
- while (!this.mIsInfoSet) {
- synchronized (this.mInfoSetTrigger) {
- try {
- this.mInfoSetTrigger.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- Logger.DEBUG(kTag, "Got: mWpsPin");
- return this.mWpsPin;
- }
- }
-
- // Constructor
- public WfdP2PClient(Activity ownerActivity) {
- this.mOwnerActivity = ownerActivity;
- this.mIsInfoSet = false;
- this.mInfoSetTrigger = new Object();
-
- // Initialize Android WFD Manager Channel
- this.mWFDManager = (WifiP2pManager) this.mOwnerActivity.getApplicationContext()
- .getSystemService(Context.WIFI_P2P_SERVICE);
- if (this.mWFDManager == null) {
- Logger.ERR(kTag, "Failed to initialize Wi-fi Direct Manager");
- return;
- }
-
-
- this.mWFDChannel = this.mWFDManager.initialize(this.mOwnerActivity, Looper.getMainLooper
- (), null);
- if (this.mWFDChannel == null) {
- Logger.ERR(kTag, "Failed to initialize Wi-fi Direct Manager");
- }
- }
-
- // Attributes
- private Activity mOwnerActivity;
-
- // P2P Info Attributes
- private boolean mIsInfoSet;
- private final Object mInfoSetTrigger;
- private String mTargetMacAddress;
- private String mWpsPin;
-
- // Components
- private WifiP2pManager mWFDManager;
- private WifiP2pManager.Channel mWFDChannel;
-}
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/testapp/CommInitializer.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/testapp/CommInitializer.java
deleted file mode 100644
index 87aa7cf1..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/testapp/CommInitializer.java
+++ /dev/null
@@ -1,197 +0,0 @@
-package com.redcarrottt.testapp;
-
-import android.bluetooth.BluetoothAdapter;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.net.wifi.WifiManager;
-
-/* Copyright (c) 2018, contributors. All rights reserved.
- *
- * Contributor: Gyeonghwan Hong
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-public class CommInitializer {
- private static final String kTag = "CommInit";
-
- public void start() {
- new Thread() {
- @Override
- public void run() {
- turnOffBt();
- }
- }.start();
- }
-
- private void turnOffBt() {
- BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
- if (adapter.isEnabled()) {
- // Register bluetooth device on event receiver
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
- Context context = this.mMainActivity.getApplicationContext();
- context.registerReceiver(this.TurnOffBtResult, intentFilter);
-
- // turn on adapter command
- Logger.DEBUG(kTag, "Turn off BT Start");
- adapter.disable();
- } else {
- Logger.DEBUG(kTag, "BT already turned off");
- this.turnOnBt();
- }
- }
-
- private BroadcastReceiver TurnOffBtResult = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String action = intent.getAction();
- if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
- final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
- BluetoothAdapter.ERROR);
- if (state == BluetoothAdapter.STATE_OFF) {
- Logger.DEBUG(kTag, "Turn off BT Success");
- context.unregisterReceiver(TurnOffBtResult);
- turnOnBt();
- }
- }
- }
- };
-
- private void turnOnBt() {
- BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
- if (!adapter.isEnabled()) {
- // Register bluetooth device on event receiver
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
- Context context = this.mMainActivity.getApplicationContext();
- context.registerReceiver(this.TurnOnBtResult, intentFilter);
-
- // turn on adapter command
- Logger.DEBUG(kTag, "Turn on BT Start");
- adapter.enable();
- } else {
- Logger.WARN(kTag, "BT not turned on");
- this.mOnResult.onCommInitializerResult(false);
- }
- }
-
- private BroadcastReceiver TurnOnBtResult = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String action = intent.getAction();
- if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
- final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
- BluetoothAdapter.ERROR);
- if (state == BluetoothAdapter.STATE_ON) {
- Logger.DEBUG(kTag, "Turn on BT Success");
- context.unregisterReceiver(TurnOnBtResult);
- turnOffWifi();
- }
- }
- }
- };
-
- private void turnOffWifi() {
- // Register wi-fi device off event receiver
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
- Context context = this.mMainActivity.getApplicationContext();
- context.registerReceiver(this.TurnOffWifiResult, intentFilter);
-
- // turn off wi-fi command
- WifiManager wifiManager = (WifiManager) this.mMainActivity.getApplicationContext()
- .getSystemService(Context.WIFI_SERVICE);
- if (wifiManager == null) {
- Logger.ERR(kTag, "Failed to get Wi-fi Manager");
- return;
- }
-
- if (wifiManager.isWifiEnabled()) {
- Logger.DEBUG(kTag, "Turn off WIFI Start");
- wifiManager.setWifiEnabled(false);
- } else {
- Logger.DEBUG(kTag, "WIFI already turned off");
- this.turnOnWifi();
- }
- }
-
- private BroadcastReceiver TurnOffWifiResult = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String action = intent.getAction();
- if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
- final int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager
- .WIFI_STATE_UNKNOWN);
- if (state == WifiManager.WIFI_STATE_DISABLED) {
- Logger.DEBUG(kTag, "Turn off WFD success");
- context.unregisterReceiver(TurnOffWifiResult);
- turnOnWifi();
- }
- }
- }
- };
-
- private void turnOnWifi() {
- // Register wi-fi device off event receiver
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
- Context context = this.mMainActivity.getApplicationContext();
- context.registerReceiver(this.TurnOnWifiResult, intentFilter);
-
- // turn off wi-fi command
- WifiManager wifiManager = (WifiManager) this.mMainActivity.getApplicationContext()
- .getSystemService(Context.WIFI_SERVICE);
- if (wifiManager == null) {
- Logger.ERR(kTag, "Failed to get Wi-fi Manager");
- return;
- }
-
- if (!wifiManager.isWifiEnabled()) {
- Logger.DEBUG(kTag, "Turn on WIFI Start");
- wifiManager.setWifiEnabled(true);
- } else {
- Logger.DEBUG(kTag, "WIFI already turned on");
- this.mOnResult.onCommInitializerResult(true);
- }
- }
-
- private BroadcastReceiver TurnOnWifiResult = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String action = intent.getAction();
- if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
- final int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager
- .WIFI_STATE_UNKNOWN);
- if (state == WifiManager.WIFI_STATE_ENABLED) {
- Logger.DEBUG(kTag, "Turn on WFD success");
- context.unregisterReceiver(TurnOnWifiResult);
- mOnResult.onCommInitializerResult(true);
- }
- }
- }
- };
-
- public CommInitializer(MainActivity mainActivity, CommInitializerResult onResult) {
- this.mMainActivity = mainActivity;
- this.mOnResult = onResult;
- }
-
- private MainActivity mMainActivity;
- private CommInitializerResult mOnResult;
-}
-
-interface CommInitializerResult {
- public void onCommInitializerResult(boolean isSuccess);
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/testapp/Logger.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/testapp/Logger.java
deleted file mode 100644
index e1e79755..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/testapp/Logger.java
+++ /dev/null
@@ -1,126 +0,0 @@
-package com.redcarrottt.testapp;
-
-/* Copyright (c) 2018, contributors. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import android.annotation.SuppressLint;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-class LogLevel {
- public static final int ERR = 1;
- public static final int WARN = 2;
- public static final int VERB = 3;
- public static final int DEBUG = 4;
-}
-
-class LogReceiver extends BroadcastReceiver {
- public static final String kAction = "LogBroadcast";
- public static final String kKeyLogLevel = "LogLevel";
- public static final String kKeyLogTag = "LogTag";
- public static final String kKeyLogMessage = "LogMessage";
-
- private Callback mCallback;
-
- public LogReceiver(Callback callback) {
- this.mCallback = callback;
- }
-
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- assert action != null;
- if (action.equals(kAction)) {
- String logTag = intent.getStringExtra(kKeyLogTag);
- String logMessage = intent.getStringExtra(kKeyLogMessage);
- int logLevel = intent.getIntExtra(kKeyLogLevel, LogLevel.DEBUG);
- this.mCallback.onLogMessage(logLevel, logTag, logMessage);
- }
- }
-
- interface Callback {
- void onLogMessage(final int logLevel, String logTag, String logMessage);
- }
-}
-
-public class Logger {
- private static void print(Context context, int logLevel, String logTag, String logMessage) {
- Intent broadcastIntent = new Intent();
- broadcastIntent.setAction(LogReceiver.kAction);
- broadcastIntent.putExtra(LogReceiver.kKeyLogLevel, logLevel);
- broadcastIntent.putExtra(LogReceiver.kKeyLogTag, logTag);
- broadcastIntent.putExtra(LogReceiver.kKeyLogMessage, logMessage);
- context.sendBroadcast(broadcastIntent);
- }
-
- private static void print(String tag, int logLevel, String logMessage) {
- print(defaultContext, logLevel, tag, logMessage);
- }
-
- public static void ERR(String tag, String logMessage) {
- print(tag, LogLevel.ERR, logMessage);
- }
-
- public static void WARN(String tag, String logMessage) {
- print(tag, LogLevel.WARN, logMessage);
- }
-
- public static void VERB(String tag, String logMessage) {
- print(tag, LogLevel.VERB, logMessage);
- }
-
- public static void DEBUG(String tag, String logMessage) {
- print(tag, LogLevel.DEBUG, logMessage);
- }
-
- public static void THREAD_LAUNCH(String threadName) {
- VERB(threadName, "Thread(" + threadName + "/" + Thread.currentThread().getId() + ") " +
- "Launch");
- }
-
- public static void THREAD_ADAPTER_LAUNCH(String adapterName, String threadName) {
- VERB(threadName, "Thread(" + adapterName + "-" + threadName + "/" + Thread.currentThread
- ().getId() + ") Launch");
- }
-
- public static void THREAD_FINISH(String threadName) {
- VERB(threadName, "Thread(" + threadName + "/" + Thread.currentThread().getId() + ") " +
- "Finish");
- }
-
- public static void THREAD_ADAPTER_FINISH(String adapterName, String threadName) {
- VERB(threadName, "Thread(" + adapterName + "-" + threadName + "/" + Thread.currentThread
- ().getId() + ") Finish");
- }
-
- public static void THREAD_FAIL(String threadName) {
- ERR(threadName, "Thread(" + threadName + "/" + Thread.currentThread().getId() + ") " +
- "Fail");
- }
-
- public static void THREAD_ADAPTER_FAIL(String adapterName, String threadName) {
- ERR(threadName, "Thread(" + adapterName + "-" + threadName + "/" + Thread.currentThread
- ().getId() + ") Fail");
- }
-
- public static void setDefaultContext(Context context) {
- Logger.defaultContext = context;
- }
-
- @SuppressLint("StaticFieldLeak")
- private static Context defaultContext;
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/java/com/redcarrottt/testapp/MainActivity.java b/subprojects/sc/android/app/src/main/java/com/redcarrottt/testapp/MainActivity.java
deleted file mode 100755
index 1814068e..00000000
--- a/subprojects/sc/android/app/src/main/java/com/redcarrottt/testapp/MainActivity.java
+++ /dev/null
@@ -1,461 +0,0 @@
-package com.redcarrottt.testapp;
-
-/* Copyright (c) 2017-2018. All rights reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import android.Manifest;
-import android.annotation.SuppressLint;
-import android.content.Context;
-import android.content.IntentFilter;
-import android.content.pm.PackageManager;
-import android.graphics.Color;
-import android.os.Bundle;
-import android.support.v4.app.ActivityCompat;
-import android.support.v4.content.ContextCompat;
-import android.support.v7.app.AppCompatActivity;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.BaseAdapter;
-import android.widget.Button;
-import android.widget.ListView;
-import android.widget.TextView;
-
-import com.redcarrottt.sc.api.API;
-import com.redcarrottt.sc.api.OnStartSCResult;
-import com.redcarrottt.sc.api.OnStopSCResult;
-import com.redcarrottt.sc.internal.ClientAdapter;
-import com.redcarrottt.sc.internal.ClientAdapterStateListener;
-import com.redcarrottt.sc.internal.bt.BtClientAdapter;
-import com.redcarrottt.sc.internal.wfd.WfdClientAdapter;
-
-import java.text.NumberFormat;
-import java.util.ArrayList;
-import java.util.Date;
-
-import static com.redcarrottt.sc.internal.ExpConfig.VERBOSE_BANDWIDTH_UPDATE;
-
-public class MainActivity extends AppCompatActivity implements LogReceiver.Callback,
- CommInitializerResult {
- private static final String kTag = "MainActivity";
-
- // Components
- private ArrayList mLogListViewData = new ArrayList<>();
- private LogListViewAdapter mLogListViewAdapter;
- private SpeedWatcherThread mSpeedWatcherThread;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- // Initialize SwitchProfileButton
- Button switchProfileButton = (Button) findViewById(R.id.switchProfileButton);
- switchProfileButton.setOnClickListener(onClickSwitchProfileButton);
- this.updateSwitchProfileButton();
-
- // Initialize StartButton
- Button startButton = (Button) findViewById(R.id.startButton);
- startButton.setOnClickListener(onClickStartButton);
-
- // Initialize SpeedWatcherThread for BandwidthTextView
- this.mSpeedWatcherThread = new SpeedWatcherThread();
- this.mSpeedWatcherThread.start();
-
- // Initialize LogListView
- this.mLogListViewAdapter = new LogListViewAdapter(this, this.mLogListViewData);
- ListView logListView = (ListView) findViewById(R.id.logListView);
- logListView.setAdapter(this.mLogListViewAdapter);
-
- // Initialize Log Receiver
- Logger.setDefaultContext(this);
- LogReceiver logReceiver = new LogReceiver(this);
- IntentFilter broadcastIntentFilter = new IntentFilter();
- broadcastIntentFilter.addAction(LogReceiver.kAction);
- this.registerReceiver(logReceiver, broadcastIntentFilter);
-
- // Require permissions for SC
- this.requestPermissions();
-
- // Initialize Communication Interfaces
- Logger.VERB(kTag, "Initializing network interfaces...");
- mCommInitializer = new CommInitializer(this, this);
- mCommInitializer.start();
- }
-
-
- private CommInitializer mCommInitializer;
-
- @Override
- public void onCommInitializerResult(boolean isSuccess) {
- if (isSuccess) {
- Logger.VERB(kTag, "All network Interfaces ready");
- Button startButton = (Button) findViewById(R.id.startButton);
- startButton.setEnabled(true);
- } else {
- Logger.ERR(kTag, "Initialization failed");
- }
- }
-
- private View.OnClickListener onClickStartButton = new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- // Initialize SC
- initializeCommunication();
- }
- };
-
- private String[] mProfiles = {"Lab", "Home"};
- private int mPresentProfile = 0;
- private View.OnClickListener onClickSwitchProfileButton = new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- final int kMaxProfiles = mProfiles.length;
- mPresentProfile = (mPresentProfile + 1) % kMaxProfiles;
- updateSwitchProfileButton();
- }
- };
-
- private void updateSwitchProfileButton() {
- Button switchProfileButton = (Button) findViewById(R.id.switchProfileButton);
- switchProfileButton.setText(this.mProfiles[this.mPresentProfile] + " Profile");
- }
-
- private void requestPermissions() {
- if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.INTERNET) !=
- PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission
- .INTERNET, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission
- .ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE, Manifest
- .permission.CHANGE_NETWORK_STATE, Manifest.permission
- .ACCESS_COARSE_LOCATION}, 0);
- }
- }
-
- private void initializeCommunication() {
- String btAddress = "";
- switch (this.mPresentProfile) {
- case 0:
- btAddress = "B8:27:EB:D9:FA:85";
- break;
- case 1:
- btAddress = "B8:27:EB:77:C3:4A";
- break;
- }
-
- if (btAddress == "") {
- Logger.ERR(kTag, "No bluetooth address is defined!");
- return;
- } else {
- Logger.VERB(kTag, "BT Address: " + btAddress);
- }
-
-
- // Setting adapters
- this.mBtClientAdapter = BtClientAdapter.singleton(1, "BT", btAddress,
- "150e8400-1234-41d4-a716-446655440000", this);
- this.mBtClientAdapter.listenState(this.mClientAdapterStateListener);
- API.registerAdapter(this.mBtClientAdapter);
-
- this.mWfdClientAdapter = WfdClientAdapter.singleton(2, "WFD", 3455, this);
- this.mWfdClientAdapter.listenState(this.mClientAdapterStateListener);
- API.registerAdapter(this.mWfdClientAdapter);
-
- // Start the selective connection
- API.startSC(onStartSCResult);
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- API.stopSC(onStopSCResult);
- }
-
- // ClientAdapters
- private BtClientAdapter mBtClientAdapter;
- private WfdClientAdapter mWfdClientAdapter;
-
- private int mBtClientAdapterState;
- private int mWfdClientAdapterState;
-
- private ClientAdapterStateListener mClientAdapterStateListener = new
- ClientAdapterStateListener() {
-
- @Override
- public void onUpdateClientAdapterState(ClientAdapter adapter, int oldState, int newState) {
- // Update local state variable
- if (adapter == mBtClientAdapter) {
- mBtClientAdapterState = newState;
- } else if (adapter == mWfdClientAdapter) {
- mWfdClientAdapterState = newState;
- }
-
- // Update state text
- final String btClientAdapterState = ClientAdapter.stateToString(mBtClientAdapterState);
- final String wfdClientAdapterState = ClientAdapter.stateToString
- (mWfdClientAdapterState);
- final String stateString = "BT: " + btClientAdapterState + " / WFD: " +
- wfdClientAdapterState;
-
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- // Update UI
- TextView adapterStateTextView = (TextView) findViewById(R.id
- .adapterStateTextView);
- adapterStateTextView.setText(stateString);
-
- // Add Log
- Logger.VERB("Adapters", stateString);
- }
- });
- }
- };
-
- private OnStartSCResult onStartSCResult = new OnStartSCResult() {
- private int mRetries = 0;
- private static final int kMaxRetries = 5;
-
- @Override
- public void onDoneStartSC(boolean isSuccess) {
- if (isSuccess) {
- // Starting Selective Connection is done
- ReceivingThread receivingThread = new ReceivingThread();
- receivingThread.start();
- } else {
- // Retry to start SC
- if (mRetries++ < kMaxRetries) {
- Logger.VERB(kTag, "Failed to start SC... Retry to start.");
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- API.startSC(onStartSCResult);
- }
- }
- }
- };
-
- private OnStopSCResult onStopSCResult = new OnStopSCResult() {
- @Override
- public void onDoneStopSC(boolean isSuccess) {
- if (!isSuccess) {
- Log.e(kTag, "Stopping Selective Connection failed");
- }
- }
- };
-
- private class SpeedWatcherThread extends Thread {
- private Date mLastAccessedTS;
- private int mPrevValue;
- private int mTotalDataSize; // Bytes
- private final int kSleepMS = 1000;
-
- public void arrive(int dataSize) {
- this.mTotalDataSize += dataSize;
- }
-
- private int getSpeed() {
- int speed;
-
- Date startTS = this.mLastAccessedTS;
- Date endTS = new Date();
- int prevValue = this.mPrevValue;
- int presentValue = this.mTotalDataSize;
-
- speed = (int) ((float) (presentValue - prevValue) / ((float) (endTS.getTime() -
- startTS.getTime()) / 1000));
-
- this.mLastAccessedTS = endTS;
- this.mPrevValue = presentValue;
-
- return speed;
- }
-
- @SuppressLint("SetTextI18n")
- @SuppressWarnings("InfiniteLoopStatement")
- @Override
- public void run() {
- this.setName("SpeedWatcher");
- this.mPrevValue = 0;
- this.mTotalDataSize = 0;
- this.mLastAccessedTS = new Date();
- while (true) {
- final int speed = this.getSpeed();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- TextView bandwidthTextView = (TextView) findViewById(R.id
- .bandwidthTextView);
- NumberFormat format = NumberFormat.getNumberInstance();
- if (VERBOSE_BANDWIDTH_UPDATE) {
- Log.d(kTag, "Bandwidth update: " + format.format(speed) + "B/s");
- }
- bandwidthTextView.setText("Bandwidth: " + format.format(speed) + "B/s");
- }
- });
- try {
- Thread.sleep(kSleepMS);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- private class ReceivingThread extends Thread {
- private static final String kTag = "Recv";
- private boolean mIsAlive;
- private final boolean kVerboseReceivingThread = false;
-
- ReceivingThread() {
- this.mIsAlive = false;
- }
-
- @Override
- public void run() {
- this.setName("AppReceiving");
- this.mIsAlive = true;
- byte[] buf = new byte[100 * 1024 * 1024];
- String sending_buf = "ACK"; /* Ack Message */
-
- while (this.mIsAlive) {
- int receivedLength = API.receive(buf);
- mSpeedWatcherThread.arrive(receivedLength);
- if (kVerboseReceivingThread) {
- Logger.DEBUG(kTag, "Received: Size=" + receivedLength);
- }
- }
- }
-
- public void terminate() {
- this.mIsAlive = false;
- }
- }
-
- @Override
- public void onLogMessage(final int logLevel, final String logTag, final String logMessage) {
- final int kPrintThreshold = LogLevel.VERB;
- final String kTag = "LOG";
- this.runOnUiThread(new Runnable() {
- @SuppressLint("SetTextI18n")
- @Override
- public void run() {
- String printLevel = "";
- int color = Color.BLACK;
- switch (logLevel) {
- case LogLevel.ERR:
- Log.e(logTag, logMessage);
- printLevel = "E";
- color = Color.RED;
- break;
- case LogLevel.WARN:
- Log.w(logTag, logMessage);
- printLevel = "W";
- color = Color.parseColor("#FF8000");
- break;
- case LogLevel.VERB:
- Log.i(logTag, logMessage);
- printLevel = "V";
- color = Color.parseColor("#0072C1");
- break;
- case LogLevel.DEBUG:
- Log.d(logTag, logMessage);
- printLevel = "D";
- color = Color.parseColor("#5C676F");
- break;
- }
- String printMessage = "[" + printLevel + "/" + logTag + "] " + logMessage;
-
- if (logLevel <= kPrintThreshold) {
- mLogListViewData.add(0, new LogListViewItem(printMessage, color));
- mLogListViewAdapter.notifyDataSetChanged();
- }
- }
- });
- }
-}
-
-class LogListViewItem {
- private String mText;
- private int mColor;
-
- public String getText() {
- return this.mText;
- }
-
- public int getColor() {
- return this.mColor;
- }
-
- LogListViewItem(String text, int color) {
- this.mText = text;
- this.mColor = color;
- }
-}
-
-class LogListViewAdapter extends BaseAdapter {
- private LayoutInflater mInflater;
- private int mLayout;
- private ArrayList mData;
-
- LogListViewAdapter(Context context, ArrayList data) {
- this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- this.mLayout = R.layout.item;
- this.mData = data;
- }
-
- @Override
- public int getCount() {
- return this.mData.size();
- }
-
- @Override
- public String getItem(int position) {
- return this.mData.get(position).getText();
- }
-
- @Override
- public long getItemId(int position) {
- return position;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- if (convertView == null) {
- convertView = mInflater.inflate(this.mLayout, parent, false);
- }
-
- LogListViewItem item = this.mData.get(position);
- TextView contentsTextView = (TextView) convertView.findViewById(R.id.contentsTextView);
- contentsTextView.setText(item.getText());
- contentsTextView.setTextColor(item.getColor());
- return contentsTextView;
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/res/layout/activity_main.xml b/subprojects/sc/android/app/src/main/res/layout/activity_main.xml
deleted file mode 100755
index 5aaada2f..00000000
--- a/subprojects/sc/android/app/src/main/res/layout/activity_main.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/subprojects/sc/android/app/src/main/res/layout/item.xml b/subprojects/sc/android/app/src/main/res/layout/item.xml
deleted file mode 100644
index 9a8ab52b..00000000
--- a/subprojects/sc/android/app/src/main/res/layout/item.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/subprojects/sc/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/subprojects/sc/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
deleted file mode 100755
index 754f18fd..00000000
Binary files a/subprojects/sc/android/app/src/main/res/mipmap-hdpi/ic_launcher.png and /dev/null differ
diff --git a/subprojects/sc/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/subprojects/sc/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
deleted file mode 100755
index 467d135f..00000000
Binary files a/subprojects/sc/android/app/src/main/res/mipmap-mdpi/ic_launcher.png and /dev/null differ
diff --git a/subprojects/sc/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/subprojects/sc/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
deleted file mode 100755
index feeb748b..00000000
Binary files a/subprojects/sc/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png and /dev/null differ
diff --git a/subprojects/sc/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/subprojects/sc/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
deleted file mode 100755
index fa081ed8..00000000
Binary files a/subprojects/sc/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differ
diff --git a/subprojects/sc/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/subprojects/sc/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
deleted file mode 100755
index 86c09a9a..00000000
Binary files a/subprojects/sc/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and /dev/null differ
diff --git a/subprojects/sc/android/app/src/main/res/values-w820dp/dimens.xml b/subprojects/sc/android/app/src/main/res/values-w820dp/dimens.xml
deleted file mode 100755
index 62df1875..00000000
--- a/subprojects/sc/android/app/src/main/res/values-w820dp/dimens.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
- 64dp
-
diff --git a/subprojects/sc/android/app/src/main/res/values/colors.xml b/subprojects/sc/android/app/src/main/res/values/colors.xml
deleted file mode 100755
index 2a12c47c..00000000
--- a/subprojects/sc/android/app/src/main/res/values/colors.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
- #3F51B5
- #303F9F
- #FF4081
-
diff --git a/subprojects/sc/android/app/src/main/res/values/dimens.xml b/subprojects/sc/android/app/src/main/res/values/dimens.xml
deleted file mode 100755
index 295b5a9d..00000000
--- a/subprojects/sc/android/app/src/main/res/values/dimens.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
- 16dp
- 16dp
-
diff --git a/subprojects/sc/android/app/src/main/res/values/strings.xml b/subprojects/sc/android/app/src/main/res/values/strings.xml
deleted file mode 100755
index 30d5b383..00000000
--- a/subprojects/sc/android/app/src/main/res/values/strings.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-
- SCPeer
-
diff --git a/subprojects/sc/android/app/src/main/res/values/styles.xml b/subprojects/sc/android/app/src/main/res/values/styles.xml
deleted file mode 100755
index 6f19b475..00000000
--- a/subprojects/sc/android/app/src/main/res/values/styles.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
diff --git a/subprojects/sc/android/app/src/test/java/com/redcarrottt/testapp/ExampleUnitTest.java b/subprojects/sc/android/app/src/test/java/com/redcarrottt/testapp/ExampleUnitTest.java
deleted file mode 100755
index bfb0ad92..00000000
--- a/subprojects/sc/android/app/src/test/java/com/redcarrottt/testapp/ExampleUnitTest.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.redcarrottt.testapp;
-
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-/**
- * Example local unit test, which will execute on the development machine (host).
- *
- * @see Testing documentation
- */
-public class ExampleUnitTest {
- @Test
- public void addition_isCorrect() throws Exception {
- assertEquals(4, 2 + 2);
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/android/build.gradle b/subprojects/sc/android/build.gradle
deleted file mode 100755
index 4af6c976..00000000
--- a/subprojects/sc/android/build.gradle
+++ /dev/null
@@ -1,24 +0,0 @@
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- google()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:3.1.4'
-
- // Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- jcenter()
- }
-}
-
-task clean(type: Delete) {
- delete rootProject.buildDir
-}
diff --git a/subprojects/sc/android/gradle.properties b/subprojects/sc/android/gradle.properties
deleted file mode 100755
index 3530b010..00000000
--- a/subprojects/sc/android/gradle.properties
+++ /dev/null
@@ -1,17 +0,0 @@
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Gradle settings configured through the IDE *will override*
-# any settings specified in this file.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-org.gradle.jvmargs=-Xmx1536m
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
diff --git a/subprojects/sc/android/gradle/wrapper/gradle-wrapper.jar b/subprojects/sc/android/gradle/wrapper/gradle-wrapper.jar
deleted file mode 100755
index 13372aef..00000000
Binary files a/subprojects/sc/android/gradle/wrapper/gradle-wrapper.jar and /dev/null differ
diff --git a/subprojects/sc/android/gradle/wrapper/gradle-wrapper.properties b/subprojects/sc/android/gradle/wrapper/gradle-wrapper.properties
deleted file mode 100755
index dee7704c..00000000
--- a/subprojects/sc/android/gradle/wrapper/gradle-wrapper.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-#Mon Jul 16 02:00:24 KST 2018
-distributionBase=GRADLE_USER_HOME
-distributionPath=wrapper/dists
-zipStoreBase=GRADLE_USER_HOME
-zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
diff --git a/subprojects/sc/android/gradlew b/subprojects/sc/android/gradlew
deleted file mode 100755
index 9d82f789..00000000
--- a/subprojects/sc/android/gradlew
+++ /dev/null
@@ -1,160 +0,0 @@
-#!/usr/bin/env bash
-
-##############################################################################
-##
-## Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
- echo "$*"
-}
-
-die ( ) {
- echo
- echo "$*"
- echo
- exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
- CYGWIN* )
- cygwin=true
- ;;
- Darwin* )
- darwin=true
- ;;
- MINGW* )
- msys=true
- ;;
-esac
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >/dev/null
-APP_HOME="`pwd -P`"
-cd "$SAVED" >/dev/null
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- if [ ! -x "$JAVACMD" ] ; then
- die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-else
- JAVACMD="java"
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
- MAX_FD_LIMIT=`ulimit -H -n`
- if [ $? -eq 0 ] ; then
- if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
- MAX_FD="$MAX_FD_LIMIT"
- fi
- ulimit -n $MAX_FD
- if [ $? -ne 0 ] ; then
- warn "Could not set maximum file descriptor limit: $MAX_FD"
- fi
- else
- warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
- fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
- GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
- APP_HOME=`cygpath --path --mixed "$APP_HOME"`
- CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
- JAVACMD=`cygpath --unix "$JAVACMD"`
-
- # We build the pattern for arguments to be converted via cygpath
- ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
- SEP=""
- for dir in $ROOTDIRSRAW ; do
- ROOTDIRS="$ROOTDIRS$SEP$dir"
- SEP="|"
- done
- OURCYGPATTERN="(^($ROOTDIRS))"
- # Add a user-defined pattern to the cygpath arguments
- if [ "$GRADLE_CYGPATTERN" != "" ] ; then
- OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
- fi
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- i=0
- for arg in "$@" ; do
- CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
- CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
-
- if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
- eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
- else
- eval `echo args$i`="\"$arg\""
- fi
- i=$((i+1))
- done
- case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
- esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
- JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/subprojects/sc/android/gradlew.bat b/subprojects/sc/android/gradlew.bat
deleted file mode 100755
index aec99730..00000000
--- a/subprojects/sc/android/gradlew.bat
+++ /dev/null
@@ -1,90 +0,0 @@
-@if "%DEBUG%" == "" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
-set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto init
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:init
-@rem Get command-line arguments, handling Windowz variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
diff --git a/subprojects/sc/android/settings.gradle b/subprojects/sc/android/settings.gradle
deleted file mode 100755
index d3db1092..00000000
--- a/subprojects/sc/android/settings.gradle
+++ /dev/null
@@ -1 +0,0 @@
-include ':app'
diff --git a/subprojects/sc/linux/LICENSE b/subprojects/sc/linux/LICENSE
deleted file mode 100644
index ac66cd6b..00000000
--- a/subprojects/sc/linux/LICENSE
+++ /dev/null
@@ -1,126 +0,0 @@
- Copyright 2017-2018 Gyeonghwan Hong (redcarrottt@gmail.com), Eunsoo Park (esevan.park@gmail.com), Injung Hwang (sinban04@gmail.com) All rights reserved
-
- Contact: Gyeonghwan Hong (redcarrottt@gmail.com)
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
-
diff --git a/subprojects/sc/linux/bin/.git_empty_file b/subprojects/sc/linux/bin/.git_empty_file
deleted file mode 100644
index e69de29b..00000000
diff --git a/subprojects/sc/linux/common/inc/ArrivalTimeCounter.h b/subprojects/sc/linux/common/inc/ArrivalTimeCounter.h
deleted file mode 100644
index 318906d1..00000000
--- a/subprojects/sc/linux/common/inc/ArrivalTimeCounter.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __ARRIVAL_TIME_COUNTER_H__
-#define __ARRIVAL_TIME_COUNTER_H__
-
-#include "Counter.h"
-
-#include
-
-#include
-#include
-
-namespace sc {
-class ArrivalTimeCounter : public Counter {
-public:
- ArrivalTimeCounter(void) : Counter() {
- this->mLastAccessedTS.tv_sec = 0;
- this->mLastAccessedTS.tv_usec = 0;
- }
-
- void arrive(void) {
- std::unique_lock lock(this->mArriveLock);
- struct timeval startTS, endTS;
- startTS = this->mLastAccessedTS;
- gettimeofday(&endTS, NULL);
-
- // Get and store interval
- if (startTS.tv_sec != 0 || startTS.tv_usec != 0) {
- uint64_t endUS = (uint64_t)endTS.tv_sec * 1000 * 1000 + endTS.tv_usec;
- uint64_t startUS =
- (uint64_t)startTS.tv_sec * 1000 * 1000 + startTS.tv_usec;
- int intervalUS = (int)(endUS - startUS);
- this->set_value(intervalUS);
- }
-
- // Store last accessed timestamp
- this->mLastAccessedTS = endTS;
- }
-
-private:
- std::mutex mArriveLock;
-
- struct timeval mLastAccessedTS;
-}; /* class ArrivalTimeCounter */
-} /* namespace sc */
-
-#endif /* !defined(__ARRIVAL_TIME_COUNTER_H__) */
diff --git a/subprojects/sc/linux/common/inc/ChildProcess.h b/subprojects/sc/linux/common/inc/ChildProcess.h
deleted file mode 100644
index dfbf369e..00000000
--- a/subprojects/sc/linux/common/inc/ChildProcess.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __UTIL_H__
-#define __UTIL_H__
-
-#include "../../configs/PathConfig.h"
-
-#include
-
-namespace sc {
-class ChildProcess {
-public:
- static int run(const char *path, char *const params[], char *res_buf,
- size_t len, bool is_wait_child);
- static int run(const char *path, char *const params[], bool is_wait_child);
-}; /* class ChildProcess */
-
-} /* namespace sc */
-
-#endif /* !defined(__UTIL_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/common/inc/Counter.h b/subprojects/sc/linux/common/inc/Counter.h
deleted file mode 100644
index f38c4f20..00000000
--- a/subprojects/sc/linux/common/inc/Counter.h
+++ /dev/null
@@ -1,181 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __COUNTER_H__
-#define __COUNTER_H__
-
-#include "DebugLog.h"
-
-#include
-#include
-#include
-
-namespace sc {
-class Counter {
-public:
-#define DEFAULT_SIMPLE_MOVING_AVERAGE_LENGTH 10
-#define DEFAULT_EXPONENTIAL_MOVING_AVERAGE_WEIGHT 0.9f
-
- Counter() {
- int simple_moving_average_length = DEFAULT_SIMPLE_MOVING_AVERAGE_LENGTH;
- float exponential_moving_average_weight =
- DEFAULT_EXPONENTIAL_MOVING_AVERAGE_WEIGHT;
-
- this->mValue = 0;
- this->mPrevValue = 0;
- this->mLastAccessedTS.tv_sec = 0;
- this->mLastAccessedTS.tv_usec = 0;
-
- /* Simple moving average */
- assert(simple_moving_average_length > 0);
- this->mSmaLength = simple_moving_average_length;
- this->mSimpleHistoryValues = new int[this->mSmaLength];
- for (int i = 0; i < this->mSmaLength; i++) {
- this->mSimpleHistoryValues[i] = 0;
- }
- this->mSimpleHistoryCursor = 0;
-
- /* Exponential moving average */
- this->mEma = 0.0f;
- this->mEmaWeight = exponential_moving_average_weight;
- assert(exponential_moving_average_weight >= 0 &&
- exponential_moving_average_weight <= 1);
- }
-
- ~Counter() { delete this->mSimpleHistoryValues; }
-
- void add(int diff) {
- std::unique_lock lock(this->mValueLock);
- this->set_value_locked(this->get_value_locked() + diff);
- }
-
- void sub(int diff) {
- std::unique_lock lock(this->mValueLock);
- this->set_value_locked(this->get_value_locked() - diff);
- }
-
- void increase(void) {
- std::unique_lock lock(this->mValueLock);
- this->set_value_locked(this->get_value_locked() + 1);
- }
-
- void decrease(void) {
- std::unique_lock lock(this->mValueLock);
- this->set_value_locked(this->get_value_locked() - 1);
- }
-
- void set_value(int new_value) {
- std::unique_lock lock(this->mValueLock);
- this->set_value_locked(new_value);
- }
-
- int get_value() {
- std::unique_lock lock(this->mValueLock);
- return this->get_value_locked();
- }
-
- int get_speed() {
- std::unique_lock lock(this->mValueLock);
- return this->get_speed_locked();
- };
-
- int get_sm_average(void) {
- std::unique_lock lock(this->mValueLock);
- return this->get_sm_average_locked();
- }
-
- float get_em_average(void) {
- std::unique_lock lock(this->mValueLock);
- return this->get_em_average_locked();
- }
-
-private:
- void set_value_locked(int new_value) {
- /* Update new value */
- this->mValue = new_value;
-
- /* Update history for simple moving average */
- this->mSimpleHistoryValues[this->mSimpleHistoryCursor] = new_value;
- this->mSimpleHistoryCursor =
- (this->mSimpleHistoryCursor + 1) % this->mSmaLength;
-
- /* Update exponential moving average */
- this->mEma = ((float)this->mEma * (1.0f - this->mEmaWeight)) +
- ((float)this->mValue * this->mEmaWeight);
- }
-
- int get_value_locked() { return this->mValue; }
-
- int get_speed_locked() {
- int speed;
- struct timeval startTS, endTS;
- startTS = this->mLastAccessedTS;
- gettimeofday(&endTS, NULL);
-
- if (startTS.tv_sec == 0 && startTS.tv_usec == 0) {
- speed = 0;
- } else {
- uint64_t end = (uint64_t)endTS.tv_sec * 1000 * 1000 + endTS.tv_usec;
- uint64_t start = (uint64_t)startTS.tv_sec * 1000 * 1000 + startTS.tv_usec;
- uint64_t interval = end - start;
-
- if (start != 0 && interval != 0) {
- speed = (int)((float)(this->mValue - this->mPrevValue) /
- ((float)interval / (1000 * 1000)));
- } else {
- speed = 0;
- }
- }
- this->mPrevValue = this->mValue;
- this->mLastAccessedTS = endTS;
- return speed;
- }
-
- int get_sm_average_locked(void) {
- int simple_mavg = 0;
- for (int i = 0; i < this->mSmaLength; i++) {
- simple_mavg += this->mSimpleHistoryValues[i];
- }
- simple_mavg /= this->mSmaLength;
- return simple_mavg;
- }
-
- float get_em_average_locked(void) { return this->mEma; }
-
-private:
- /* Value */
- std::mutex mValueLock;
- int mValue;
-
- /* Speed */
- int mPrevValue;
- struct timeval mLastAccessedTS;
-
- /* Simple moving average (SMA) */
- int *mSimpleHistoryValues; /* History values for simple moving average */
- int mSimpleHistoryCursor; /* Cursor on history values */
- int mSmaLength; /* Length for simple moving average */
-
- /* Exponential moving average (EMA) */
- float mEma; /* Exponential moving average */
- float mEmaWeight; /* Weight for Exponential moving average */
-}; /* class Counter */
-} /* namespace sc */
-
-#endif /* !defined(__COUNTER_H__) */
diff --git a/subprojects/sc/linux/common/inc/DebugLog.h b/subprojects/sc/linux/common/inc/DebugLog.h
deleted file mode 100644
index 4c2e362d..00000000
--- a/subprojects/sc/linux/common/inc/DebugLog.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __DEBUG_LOG_H__
-#define __DEBUG_LOG_H__
-
-#include "../../configs/ExpConfig.h"
-
-#include
-#include
-#include
-#include
-#include
-
-#ifndef likely
-#define likely(x) __builtin_expect(!!(x), 1)
-#define unlikely(x) __builtin_expect(!!(x), 0)
-#endif /* likely(x) */
-
-#ifndef LOG_LEVEL
-#define LOG_LEVEL 0
-#endif
-
-#define _log(format, color, args...) \
- do { \
- __log(format, __FILE__, __func__, color, __LINE__, ##args); \
- } while (0)
-#define _func(format, args...) \
- do { \
- __func(format, __FILE__, __func__, __LINE__, ##args); \
- } while (0)
-
-#if LOG_LEVEL < 1
-#define LOG_DEBUG(fmt, args...) \
- do { \
- _log(fmt, 9, ##args); \
- } while (0)
-#else /* LOG_LEVEL >= 1 */
-#define LOG_DEBUG(fmt, args...)
-#endif /* LOG_LEVEL < 1 */
-
-#if LOG_LEVEL < 2
-#define LOG_VERB(fmt, args...) \
- do { \
- _log(fmt, 94, ##args); \
- } while (0)
-#else /* LOG_LEVEL >= 2 */
-#define LOG_VERB(fmt, args...)
-#endif /* LOG_LEVEL < 2 */
-
-#if LOG_LEVEL < 3
-#define LOG_WARN(fmt, args...) \
- do { \
- _log(fmt, 91, ##args); \
- } while (0)
-#else /* LOG_LEVEL >= 3 */
-#define LOG_WARN(fmt, args...)
-#endif /* LOG_LEVEL < 3 */
-
-#if LOG_LEVEL < 4
-#define LOG_ERR(fmt, args...) \
- do { \
- _log(fmt, 101, ##args); \
- } while (0)
-#else /* LOG_LEVEL >= 4 */
-#define LOG_ERR(fmt, args...)
-#endif /* LOG_LEVEL < 4 */
-
-#define __FUNCTION_ENTER__ \
- do { \
- _func("ENTER"); \
- } while (0)
-#define __FUNCTION_EXIT__ \
- do { \
- _func("EXIT"); \
- } while (0)
-
-void __log(const char *format, const char *fileName, const char *funcName,
- int color, int lineNo, ...);
-
-void __func(const char *format, const char *fileName, const char *funcName,
- int lineNo, ...);
-
-#define LOG_THREAD_LAUNCH(thread_name) \
- do { \
- LOG_VERB("Thread(%s; %d) Launch", thread_name, getpid()); \
- } while (0)
-
-#define LOG_ADAPTER_THREAD_LAUNCH(adapter_name, thread_name) \
- do { \
- LOG_VERB("Thread(%s-%s; %d) Launch", adapter_name, thread_name, getpid()); \
- } while (0)
-
-#define LOG_THREAD_FINISH(thread_name) \
- do { \
- LOG_VERB("Thread(%s; %d) Finish", thread_name, getpid()); \
- } while (0)
-
-#define LOG_ADAPTER_THREAD_FINISH(adapter_name, thread_name) \
- do { \
- LOG_VERB("Thread(%s-%s; %d) Finish", adapter_name, thread_name, getpid()); \
- } while (0)
-
-#define LOG_THREAD_FAIL(thread_name) \
- do { \
- LOG_ERR("Thread(%s; %d) Failed", thread_name, getpid()); \
- } while (0)
-
-#define LOG_ADAPTER_THREAD_FAIL(adapter_name, thread_name) \
- do { \
- LOG_ERR("Thread(%s-%s; %d) Failed", adapter_name, thread_name, getpid()); \
- } while (0)
-
-#endif /* !defined(__DEBUG_LOG_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/common/inc/RefCount.h b/subprojects/sc/linux/common/inc/RefCount.h
deleted file mode 100644
index 05354469..00000000
--- a/subprojects/sc/linux/common/inc/RefCount.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __REF_COUNT_H__
-#define __REF_COUNT_H__
-
-#include
-
-namespace sc {
-
-class RefCount {
-public:
- int get_value(void) {
- std::unique_lock lck(this->mLock);
- return this->mCount;
- }
- int increase(void) {
- std::unique_lock lck(this->mLock);
- this->mCount++;
- return this->mCount;
- }
- int decrease(void) {
- std::unique_lock lck(this->mLock);
- this->mCount--;
- return this->mCount;
- }
-
- RefCount(void) {
- this->mCount = 0;
- }
-protected:
- int mCount;
- std::mutex mLock;
-}; /* class RefCount */
-} /* namespace sc */
-#endif /* !defined(__REF_COUNT_H__) */
diff --git a/subprojects/sc/linux/common/src/ChildProcess.cpp b/subprojects/sc/linux/common/src/ChildProcess.cpp
deleted file mode 100644
index 8703a22b..00000000
--- a/subprojects/sc/linux/common/src/ChildProcess.cpp
+++ /dev/null
@@ -1,154 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "../inc/ChildProcess.h"
-
-#include "../../common/inc/DebugLog.h"
-
-#include "../../configs/ExpConfig.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#ifdef VERBOSE_CHILD_PROCESS_RUN
-#include
-#endif
-
-using namespace sc;
-
-int ChildProcess::run(const char *path, char *const params[], char *res_buf,
- size_t len, bool is_wait_child) {
- int internal_pipe[2];
- int pid, bk, res;
-
-#ifdef VERBOSE_CHILD_PROCESS_RUN
- std::string command_string("");
- int i = 0;
- while (params[i] != NULL) {
- command_string.append(params[i]);
- if (params[i + 1] != NULL) {
- command_string.append(" ");
- }
- i++;
- }
- LOG_DEBUG("RUN: %s", command_string.c_str());
-#endif
-
- res = pipe(internal_pipe);
- if (res < 0) {
- LOG_ERR("pipe open error");
- return errno;
- }
-
- dup2(1, bk);
-
- pid = fork();
- if (pid < 0) {
- LOG_ERR("Fork error");
- return errno;
- } else if (pid > 0) { // LOG_VERB("Forked PID : %d", pid);
- /* Parent process */
- close(internal_pipe[1]);
-
- char buf[1024];
- const int kMaxTries = 5;
- int read_bytes;
- for (int tries = 0; tries < kMaxTries; tries++) {
- read_bytes = read(internal_pipe[0], buf, 1024);
-
- if (read_bytes < 0) {
- LOG_DEBUG("%s(pid %d): read error(%s) / retry %d", path, pid,
- strerror(errno), tries);
- } else {
- break;
- }
- }
- if (read_bytes < 0) {
- return errno;
- }
-
- if (is_wait_child) {
- int status;
- waitpid(pid, &status, 0);
-#ifdef VERBOSE_CHILD_PROCESS_RUN
- LOG_DEBUG("DONE: %s - %d", command_string.c_str(), status);
-#endif
- } else {
-#ifdef VERBOSE_CHILD_PROCESS_RUN
- LOG_DEBUG("DAEMON: %s", command_string.c_str());
-#endif
- }
-
- memcpy(res_buf, buf, read_bytes < len ? read_bytes : len);
- dup2(bk, 1);
-
- close(internal_pipe[0]);
-
- return pid;
- } else {
- /* Child process */
- close(internal_pipe[0]);
- dup2(internal_pipe[1], 1);
-
- execv(path, params);
- return 0;
- }
-}
-
-int ChildProcess::run(const char *path, char *const params[],
- bool is_wait_child) {
- int pid;
-
-#ifdef VERBOSE_CHILD_PROCESS_RUN
- std::string command_string("");
- int i = 0;
- while (params[i] != NULL) {
- command_string.append(params[i]);
- command_string.append(" ");
- i++;
- }
- LOG_VERB("Run command: %s", command_string.c_str());
-#endif
-
- if ((pid = fork()) < 0) {
- LOG_ERR("fork error");
- return errno;
- } else if (pid > 0) { // LOG_VERB("Forked PID : %d", pid);
- /* Parent process */
- if (is_wait_child) {
- int status;
- waitpid(pid, &status, 0);
-#ifdef VERBOSE_CHILD_PROCESS_RUN
- LOG_VERB("DONE: %s - %d", command_string.c_str(), status);
-#endif
- } else {
-#ifdef VERBOSE_CHILD_PROCESS_RUN
- LOG_VERB("DAEMON: %s", command_string.c_str());
-#endif
- }
- return pid;
- } else {
- execv(path, params);
- return 0;
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/common/src/DebugLog.cpp b/subprojects/sc/linux/common/src/DebugLog.cpp
deleted file mode 100644
index abc470ab..00000000
--- a/subprojects/sc/linux/common/src/DebugLog.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/DebugLog.h"
-
-#include "../../configs/ExpConfig.h"
-
-#include
-#include
-#include
-#include
-#include
-
-void __log(const char *format, const char *fileName, const char *funcName,
- int color, int lineNo, ...) {
- va_list ap;
- #if defined(LOG_FILE_NAME) && defined(LOG_FUNC_NAME)
- printf("\033[%dm%s:%d (%s()) ", color, fileName, lineNo, funcName);
- #elif defined(LOG_FILE_NAME)
- printf("\033[%dm%s:%d ", color, fileName, lineNo);
- #elif defined(LOG_FUNC_NAME)
- printf("\033[%dm(%s()) ", color, funcName);
- #else
- printf("\033[%dm", color);
- #endif
- va_start(ap, lineNo);
- vprintf(format, ap);
- va_end(ap);
- printf("\033[0m\n");
-}
-
-void __func(const char *format, const char *fileName, const char *funcName,
- int lineNo, ...) {
- va_list ap;
- #if defined(LOG_FILE_NAME) && defined(LOG_FUNC_NAME)
- printf("\033[%dm%s:%d (%s()) ", 2, fileName, lineNo, funcName);
- #elif defined(LOG_FILE_NAME)
- printf("\033[%dm%s:%d ", 2, fileName, lineNo);
- #elif defined(LOG_FUNC_NAME)
- printf("\033[%dm(%s()) ", 2, funcName);
- #else
- printf("\033[%dm", 2);
- #endif
- va_start(ap, lineNo);
- vprintf(format, ap);
- va_end(ap);
- printf("]\033[0m\n");
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/configs/ExpConfig.h b/subprojects/sc/linux/configs/ExpConfig.h
deleted file mode 100644
index a66f4bff..00000000
--- a/subprojects/sc/linux/configs/ExpConfig.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __EXP_CONFIG_H__
-#define __EXP_CONFIG_H__
-
-/* Printing */
-// #define LOG_FILE_NAME
-#define LOG_FUNC_NAME
-#define PRINT_NETWORK_MONITOR_STATISTICS
-//#define EXP_MEASURE_INTERVAL_SENDER
-//#define VERBOSE_SERVER_ADAPTER_RECEIVING
-//#define VERBOSE_SEGMENT_QUEUE_WAITING
-#define VERBOSE_DEQUEUE_SEND_CONTROL
-//#define VERBOSE_DEQUEUE_SEND_DATA
-//#define VERBOSE_ENQUEUE_SEND
-#define VERBOSE_ENQUEUE_RECV
-#define VERBOSE_CHILD_PROCESS_RUN
-//#define EXP_DONT_SEND_CONNECT_CONTROL_MESSAGE
-//#define EXP_DONT_SEND_PRIV_CONTROL_MESSAGE
-//#define EXP_RECONNECT_ADAPTER_ENABLED
-#define VERBOSE_CONTROL_RAW_MESSAGE
-
-#define LOG_LEVEL 1
-
-#endif /* !defined(__EXP_CONFIG_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/configs/NetworkSwitcherConfig.h b/subprojects/sc/linux/configs/NetworkSwitcherConfig.h
deleted file mode 100644
index 8a0b0a02..00000000
--- a/subprojects/sc/linux/configs/NetworkSwitcherConfig.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NETWORK_SWITCHER_CONFIG_H__
-#define __NETWORK_SWITCHER_CONFIG_H__
-
-#define NETWORK_MONITOR_SLEEP_USECS (250 * 1000)
-
-/* Energy constants (mJ) */
-#define BT_TX_ENERGY_1KB_BASIS 5.0342202f
-#define BT_TX_ENERGY_PER_1B 0.000882425f
-#define WFD_TX_ENERGY_1KB_BASIS 2.055363f
-#define WFD_TX_ENERGY_PER_1B 0.000200986f
-#define WFD_INIT_ENERGY 3157.8248f
-#define WFD_IDLE_ENERGY_PER_1SEC 156.13f
-
-/* Latency constants (us) */
-#define BT_TX_LATENCY_1KB_BASIS 26970.0f
-#define BT_TX_LATENCY_PER_1B 11.21951941f
-#define WFD_TX_LATENCY_1KB_BASIS 10110.0f
-#define WFD_TX_LATENCY_PER_1B 0.248092696f
-#define WFD_INIT_LATENCY 6740000.0f
-
-/* CoolSpots */
-#define AVERAGE_WFD_ON_LATENCY_SEC 8.04f /* 8.04 sec */
-#define MAX_BANDWIDTH 90000 /* 90000B/s */
-
-#endif /* !defined(__NETWORK_SWITCHER_CONFIG_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/configs/PathConfig.h b/subprojects/sc/linux/configs/PathConfig.h
deleted file mode 100644
index 56a04666..00000000
--- a/subprojects/sc/linux/configs/PathConfig.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __PATH_CONFIG_H__
-#define __PATH_CONFIG_H__
-
-#define HCICONFIG_PATH "/bin/hciconfig"
-#define WPA_CLI_PATH "/sbin/wpa_cli"
-#define IFCONFIG_PATH "/sbin/ifconfig"
-#define UDHCPD_PATH "/usr/sbin/udhcpd"
-#define IFUP_PATH "/sbin/ifup"
-#define IFDOWN_PATH "/sbin/ifdown"
-
-#endif /* !defined(__PATH_CONFIG_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/configs/WfdConfig.h b/subprojects/sc/linux/configs/WfdConfig.h
deleted file mode 100644
index 00a11418..00000000
--- a/subprojects/sc/linux/configs/WfdConfig.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __WFD_CONFIG_H__
-#define __WFD_CONFIG_H__
-
-/* WLAN device configuration */
-#define DEFAULT_WFD_DEVICE_NAME "wlan0"
-
-/* Server IP configuration */
-#define DEFAULT_WFD_IP_ADDRESS "192.168.49.1"
-
-/* DHCPD configuration */
-#define WFD_DHCPD_LEASES_START_ADDRESS "192.168.49.20"
-#define WFD_DHCPD_LEASES_END_ADDRESS "192.168.49.40"
-#define WFD_DHCPD_MAX_LEASES 20
-#define WFD_DHCPD_LEASE 864000
-#define WFD_DHCPD_SUBNET_MASK "255.255.255.0"
-#define WFD_DHCPD_BROADCAST_ADDRESS "192.168.49.255"
-#define UDHCPD_CONFIG_PATH "dhcpd.conf"
-
-#endif /* defined(__WFD_CONFIG_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/API.h b/subprojects/sc/linux/core/inc/API.h
deleted file mode 100644
index bcb986a7..00000000
--- a/subprojects/sc/linux/core/inc/API.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __SC_API_H__
-#define __SC_API_H__
-
-#include "Core.h"
-#include "ServerAdapter.h"
-
-namespace sc {
-typedef void (*StartCallback)(bool is_success);
-void start_sc(StartCallback startCallback);
-
-typedef void (*StopCallback)(bool is_success);
-void stop_sc(StopCallback stopCallback);
-
-inline void register_adapter(ServerAdapter *adapter) {
- Core::singleton()->register_adapter(adapter);
-}
-
-inline int send(const void *dataBuffer, uint32_t dataLength) {
- Core::singleton()->send(dataBuffer, dataLength, false);
-}
-
-inline int receive(void **dataBuffer) {
- Core::singleton()->receive(dataBuffer, false);
-}
-} /* namespace sc */
-
-#endif /* !defined(__SC_API_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/APIInternal.h b/subprojects/sc/linux/core/inc/APIInternal.h
deleted file mode 100644
index 0699953e..00000000
--- a/subprojects/sc/linux/core/inc/APIInternal.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __API_INTERNAL_H__
-#define __API_INTERNAL_H__
-
-namespace sc {
-void start_sc_done(bool is_success);
-void stop_sc_done(bool is_success);
-} /* namespace sc */
-
-#endif /* !defined(__API_INTERNAL_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/ControlMessageProtocol.h b/subprojects/sc/linux/core/inc/ControlMessageProtocol.h
deleted file mode 100644
index e3b52826..00000000
--- a/subprojects/sc/linux/core/inc/ControlMessageProtocol.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __CONTROL_MESSAGE_PROTOCOL_H__
-#define __CONTROL_MESSAGE_PROTOCOL_H__
-
-namespace sc {
-/**
- *
- * Line 1: Control Message Code
- * Line 2: Target Adapter ID (Normal Type)
- * Priv Message Type (Priv Type)
- * Line 3+: Priv Message Contents (Priv Type)
- */
-
-/**
- * Control Message Code
- * It is used to classify "control request message" that is transferred to the
- * peer.
- * - Commands: "Connect", "Sleep", "WakeUp", "Disconnect"
- * - Acks: "Disconnect"
- * - Private Data: "Priv"
- */
-typedef enum {
- kCMCodeConnect = 1,
- kCMCodeSleep = 2,
- kCMCodeWakeUp = 3,
- kCMCodeDisconnect = 4,
- kCMCodePriv = 10,
- kCMCodeDisconnectAck = 24
-} CMCode; /* enum CMCode */
-
-/**
- * Control Priv Message Type
- * - WFDInfo: Wi-fi Direct Information
- */
-typedef enum {
- kPrivTypeWFDInfo = 1,
- kPrivTypeUnknown = 999
-} PrivType; /* enum PrivType */
-
-} /* namespace sc */
-
-#endif /* !defined(__CONTROL_MESSAGE_PROTOCOL_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/ControlMessageReceiver.h b/subprojects/sc/linux/core/inc/ControlMessageReceiver.h
deleted file mode 100644
index 1605247c..00000000
--- a/subprojects/sc/linux/core/inc/ControlMessageReceiver.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __CONTROL_MESSAGE_RECEIVER_H__
-#define __CONTROL_MESSAGE_RECEIVER_H__
-
-#include "../inc/ControlMessageProtocol.h"
-
-#include
-#include
-#include
-
-namespace sc {
-
-class ControlPrivMessageListener {
-public:
- virtual void on_receive_control_priv_message(int priv_type,
- std::string priv_message) = 0;
-}; /* class ControlPrivMessageListener */
-
-class ControlMessageReceiver {
-public:
- void start_receiving_thread(void);
- void stop_receiving_thread(void);
-
- /* Handling control message (private data) listener */
- void add_control_message_listener(ControlPrivMessageListener *listener) {
- this->mPrivMessageListeners.push_back(listener);
- }
-
-protected:
- /* Receiving Thread */
- void receiving_thread_loop(void);
- bool receiving_thread_loop_internal(void);
- void on_receive_normal_message(int control_message_code, int adapter_id);
- void on_receive_disconnect_message(int adapter_id,
- uint32_t final_seq_no_control,
- uint32_t final_seq_no_data);
- void on_receive_priv_message(std::string contents);
- std::thread *mReceivingThread = NULL;
- bool mReceivingThreadOn = false;
-
- /* Control Message Listeners */
- std::vector mPrivMessageListeners;
-}; /* class ControlMessageReceiver */
-} /* namespace sc */
-
-#endif /* !defined(__CONTROL_MESSAGE_RECEIVER_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/ControlMessageSender.h b/subprojects/sc/linux/core/inc/ControlMessageSender.h
deleted file mode 100644
index b9f4a81e..00000000
--- a/subprojects/sc/linux/core/inc/ControlMessageSender.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __CONTROL_MESSAGE_SENDER_H__
-#define __CONTROL_MESSAGE_SENDER_H__
-
-#include "ControlMessageProtocol.h"
-
-#include
-#include
-
-namespace sc {
-class ControlMessageSender {
-public:
- /* Control message handling (External) */
- void send_request_connect(int adapter_id);
- void send_request_disconnect(int adapter_id, uint32_t last_seq_no_control,
- uint32_t last_seq_no_data);
- void send_request_disconnect_ack(int adapter_id);
- void send_request_sleep(int adapter_id);
- void send_request_wake_up(int adapter_id);
- void send_noti_private_data(PrivType priv_type, char *priv_data_buffer,
- uint32_t priv_data_length);
-
-private:
- /* Control message handling (Internal) */
- void send_control_message(std::string &message);
- void send_request(CMCode request_code, int adapter_id);
-}; /* class ControlMessageSender */
-} /* namespace sc */
-
-#endif /* !defined(__CONTROL_MESSAGE_SENDER_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/Core.h b/subprojects/sc/linux/core/inc/Core.h
deleted file mode 100644
index b0a369d4..00000000
--- a/subprojects/sc/linux/core/inc/Core.h
+++ /dev/null
@@ -1,237 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __SC_CORE_H__
-#define __SC_CORE_H__
-
-#include "APIInternal.h"
-#include "SegmentManager.h"
-#include "ServerAdapter.h"
-#include "ControlMessageReceiver.h"
-#include "ControlMessageSender.h"
-
-#include "../../common/inc/ArrivalTimeCounter.h"
-
-#include
-#include
-#include
-
-namespace sc {
-
-class Core;
-/*
- * Auxiliary Classes (Transactions)
- * Series of asynchronous callbacks, especially used for
- * connection/disconnection callbacks.
- */
-class StartCoreTransaction {
-public:
- static bool run(Core *caller);
- void start();
- static void connect_first_adapter_callback(ServerAdapter* adapter, bool is_success);
-
-private:
- void done(bool is_success);
-
- StartCoreTransaction(Core *caller) { this->mCaller = caller; }
- static StartCoreTransaction *sOngoing;
-
- Core *mCaller;
-}; /* class StartCoreTransaction */
-
-class StopCoreTransaction {
-public:
- static bool run(Core *caller);
- void start();
- static void disconnect_adapter_callback(ServerAdapter* adapter, bool is_success);
-
-private:
- void done(bool is_success);
-
- StopCoreTransaction(Core *caller) { this->mCaller = caller; }
- static StopCoreTransaction *sOngoing;
-
- Core *mCaller;
-
- int mAdaptersCount;
- std::mutex mAdaptersCountLock;
-}; /* class StopCoreTransaction */
-
-/* Core State */
-typedef enum {
- kCoreStateIdle = 0,
- kCoreStateStarting = 1,
- kCoreStateReady = 2,
- kCoreStateStopping = 3
-} CoreState; /* enum CoreState */
-
-class ServerAdapter;
-
-/*
- * Core
- */
-class Core {
-public:
- /*
- * APIs
- */
- void start();
- void done_start(bool is_success);
- void stop();
- void done_stop(bool is_success);
-
- void register_adapter(ServerAdapter *adapter);
-
- int send(const void *dataBuffer, uint32_t dataLength, bool is_control);
- int receive(void **pDataBuffer, bool is_control);
-
-public:
- /* Control Message Receiver/Sender Getter */
- ControlMessageSender* get_control_sender(void) {
- return this->mControlMessageSender;
- }
- ControlMessageReceiver* get_control_receiver(void) {
- return this->mControlMessageReceiver;
- }
-
-private:
-/* Control Message Receiver/Sender */
- ControlMessageSender* mControlMessageSender;
- ControlMessageReceiver* mControlMessageReceiver;
-
-public:
- /* Get statistics */
- int get_total_bandwidth(void) {
- int num_adapters = 0;
- int now_total_bandwidth = 0;
- /* Statistics from adapters */
- int adapter_count = this->get_adapter_count();
- for (int i = 0; i < adapter_count; i++) {
- ServerAdapter *adapter = this->get_adapter(i);
- if (adapter == NULL)
- continue;
- int bandwidth_up = adapter->get_bandwidth_up();
- int bandwidth_down = adapter->get_bandwidth_down();
- now_total_bandwidth += (bandwidth_up + bandwidth_down);
- num_adapters++;
- }
- return now_total_bandwidth;
- }
- float get_ema_send_request_size() {
- return this->mSendRequestSize.get_em_average();
- }
- float get_ema_send_arrival_time() {
- return this->mSendArrivalTime.get_em_average();
- }
-
-public:
- /* State getter */
- CoreState get_state(void) {
- std::unique_lock lck(this->mStateLock);
- return this->mState;
- }
-
-private:
- /* State setter */
- void set_state(CoreState new_state) {
- std::unique_lock lck(this->mStateLock);
- this->mState = new_state;
- }
-
- /* State */
- CoreState mState;
- std::mutex mStateLock;
-
-public:
- /* Adapter list handling */
- ServerAdapter *find_adapter_by_id(int adapter_id) {
- std::unique_lock lck(this->mAdaptersLock);
- for (std::vector::iterator it = this->mAdapters.begin();
- it != this->mAdapters.end(); it++) {
- ServerAdapter *adapter = *it;
- if (adapter->get_id() == adapter_id) {
- return adapter;
- }
- }
- return NULL;
- }
-
- ServerAdapter *get_adapter(int index) {
- std::unique_lock lck(this->mAdaptersLock);
- assert(index < this->mAdapters.size());
- return this->mAdapters.at(index);
- }
-
- ServerAdapter *get_active_adapter() {
- return this->get_adapter(this->get_active_adapter_index());
- }
-
- int get_adapter_count(void) {
- std::unique_lock lck(this->mAdaptersLock);
- return this->mAdapters.size();
- }
-
- /* Handling adapter index */
- int get_active_adapter_index(void) { return this->mActiveAdapterIndex; }
- void set_active_adapter_index(int active_control_adapter_index) {
- this->mActiveAdapterIndex = active_control_adapter_index;
- }
-
-private:
- /* Adapter list */
- std::vector mAdapters;
- std::mutex mAdaptersLock;
- int mActiveAdapterIndex;
-
-private:
- /* Statistics */
- Counter mSendRequestSize;
- ArrivalTimeCounter mSendArrivalTime;
-
-public:
- /* Singleton */
- static Core *singleton(void) {
- if (sSingleton == NULL) {
- sSingleton = new Core();
- }
- return sSingleton;
- }
-
- ~Core() { SegmentManager::singleton()->free_segment_all(); }
-
-private:
- /* Singleton */
- static Core *sSingleton;
- Core(void) {
- SegmentManager *sm = SegmentManager::singleton();
- this->mState = kCoreStateIdle;
- this->mActiveAdapterIndex = 0;
- this->mControlMessageReceiver = new ControlMessageReceiver();
- this->mControlMessageSender = new ControlMessageSender();
- }
-
-public:
- /* Its private members can be accessed by auxiliary classes */
- friend StartCoreTransaction;
- friend StopCoreTransaction;
-}; /* class Core */
-} /* namespace sc */
-#endif /* !defined(__SC_CORE_H__) */
diff --git a/subprojects/sc/linux/core/inc/Device.h b/subprojects/sc/linux/core/inc/Device.h
deleted file mode 100644
index 78bbfe53..00000000
--- a/subprojects/sc/linux/core/inc/Device.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __DEVICE_H__
-#define __DEVICE_H__
-
-#include
-#include
-
-#include
-
-namespace sc {
-
-typedef enum {
- kOff = 0,
- kTurningOn = 1,
- kOn = 2,
- kTurningOff = 3
-} DeviceState;
-
-class ServerAdapter;
-class Device {
-public:
- bool turn_on(void);
- bool turn_off(void);
-
- virtual bool turn_on_impl(void) = 0;
- virtual bool turn_off_impl(void) = 0;
-
- DeviceState get_state(void) {
- return this->mState;
- }
-
- Device(const char* name) {
- this->mState = DeviceState::kOff;
- snprintf(this->mName, sizeof(this->mName), name);
- }
-
- ~Device() {
- }
-
-protected:
- void set_state(DeviceState new_state) {
- this->mState = new_state;
- }
-
- char* get_name() {
- return this->mName;
- }
-
-private:
- DeviceState mState;
- char mName[256];
-}; /* class Device */
-} /* namespace sc */
-
-#endif /* !defined(__DEVICE_H__) */
diff --git a/subprojects/sc/linux/core/inc/NetworkMonitor.h b/subprojects/sc/linux/core/inc/NetworkMonitor.h
deleted file mode 100644
index a7c2f0a5..00000000
--- a/subprojects/sc/linux/core/inc/NetworkMonitor.h
+++ /dev/null
@@ -1,131 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NETWORK_MONITOR_H__
-#define __NETWORK_MONITOR_H__
-
-#include "NetworkSwitcher.h"
-
-namespace sc {
-typedef enum {
- kNSModeEnergyAware = 0, /* WearDrive-like */
- kNSModeLatencyAware = 1, /* Selective Connection Unique */
- kNSModeCapDynamic = 2 /* CoolSpots */
-} NSMode;
-
-class Stats {
-public:
- /* Statistics used to print present status */
- float ema_queue_arrival_speed = 0;
-
- /* Statistics used in CoolSpots Policy */
- int now_total_bandwidth = 0;
-
- /* Statistics used in Energy-aware & Latency-aware Policy */
- float ema_send_request_size = 0;
- float ema_arrival_time_us = 0;
- int now_queue_data_size = 0;
-};
-
-class NetworkSwitcher;
-class NetworkMonitor {
-public:
- /* Control netwowrk monitor thread */
- void start(void);
- void stop(void);
-
-private:
- /* Network switcher thread */
- void switcher_thread(void);
- std::thread *mThread;
- bool mSwitcherThreadOn;
-
- /* Checking statistics and decide switching */
- void get_stats(Stats &stats);
- void print_stats(Stats &stats);
- void check_and_decide_switching(Stats &stats);
-
-private:
- /* Check policy-driven condition of increase/decrease */
- bool check_increase_adapter(const Stats &stats);
- bool check_decrease_adapter(const Stats &stats);
-
- /* Check condition of increase/decrease */
- bool is_increaseable(void);
- bool is_decreaseable(void);
-
- /* Get payoff points */
- int get_init_energy_payoff_point(void);
- int get_idle_energy_payoff_point(int avg_arrival_time_us);
- int get_init_latency_payoff_point(void);
-
- /* Increase/decrease adapter */
- bool increase_adapter(void);
- bool decrease_adapter(void);
-
- /* Policy-related */
- /* CoolSpots Policy */
- int mBandwidthWhenIncreasing;
- int mDecreasingCheckCount;
-
- /* Auxiliary member variable for statistics */
- Counter mQueueArrivalSpeed; /* to achieve the ema of queue arrival speed */
-
-public:
- /* Mode getter */
- NSMode get_mode(void) {
- std::unique_lock lck(this->mModeLock);
- NSMode mode = this->mMode;
- return mode;
- }
-
- /* Mode setter */
- void set_mode(NSMode new_mode) {
- std::unique_lock lck(this->mModeLock);
- this->mMode = new_mode;
- }
-
-private:
- /* Mode */
- NSMode mMode;
- std::mutex mModeLock;
-
-public:
- /* Singleton */
- static NetworkMonitor *singleton(void) {
- if (NetworkMonitor::sSingleton == NULL) {
- NetworkMonitor::sSingleton = new NetworkMonitor();
- }
- return NetworkMonitor::sSingleton;
- }
-
-private:
- /* Singleton */
- static NetworkMonitor *sSingleton;
- NetworkMonitor(void) {
- this->mSwitcherThreadOn = false;
- this->mThread = NULL;
- this->mBandwidthWhenIncreasing = 0;
- this->mDecreasingCheckCount = 0;
- this->set_mode(NSMode::kNSModeEnergyAware);
- }
-}; /* class NetworkMonitor */
-} /* namespace sc */
-
-#endif /* !defined(__NETWORK_MONITOR_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/NetworkSwitcher.h b/subprojects/sc/linux/core/inc/NetworkSwitcher.h
deleted file mode 100644
index b350c110..00000000
--- a/subprojects/sc/linux/core/inc/NetworkSwitcher.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NETWORK_SWITCHER_H__
-#define __NETWORK_SWITCHER_H__
-
-#include "Core.h"
-#include "ServerAdapter.h"
-
-#include "../../common/inc/DebugLog.h"
-
-#include "../../configs/ExpConfig.h"
-
-#include
-#include
-#include
-
-#include
-
-namespace sc {
-class Core;
-class NetworkSwitcher;
-
-/* Transctions in NetworkSwitcher */
-class SwitchAdapterTransaction {
- /*
- * Switch Adapter Transaction: Order
- * 0. Entry
- * - NetworkSwitcher.switch_adapters()
- * - SwitchAdapterTransaction.start()
- * 1-a. Connect/WakeUp Next Adapter
- * - next_adapter.connect_or_wake_up()
- * 1-b. Callback (for connect request)
- * - SwitchAdapterTransaction.connect_next_adapter_callback()
- * 2-a. Sleep Prev Adapter
- * - prev_adapter.sleep()
- * 2-b. Callback (for sleep request)
- * - SwitchAdapterTransaction.sleep_prev_adapter_callback()
- * 3-a. Disconnect Prev Adapter
- * - prev_adapter.disconnect()
- * 3-b. Callback (for disconnect request)
- * - SwitchAdapterTransaction.disconnect_prev_adapter_callback()
- * 4. SwitchAdapterTransaction.done()
- * NetworkSwitcher.done_switch()
- */
-public:
- static bool run(int prev_index, int next_index);
- void start(void);
- static void connect_next_adapter_callback(ServerAdapter* adapter, bool is_success);
- static void sleep_prev_adapter_callback(ServerAdapter* adapter, bool is_success);
- static void disconnect_prev_adapter_callback(ServerAdapter* adapter, bool is_success);
-
-protected:
- void done(bool is_success);
-
- SwitchAdapterTransaction(int prev_index, int next_index) {
- this->mPrevIndex = prev_index;
- this->mNextIndex = next_index;
- }
- static SwitchAdapterTransaction *sOngoing;
-
- int mPrevIndex;
- int mNextIndex;
-}; /* class SwitchAdapterTransaction */
-
-class ConnectRequestTransaction {
-public:
- static bool run(int adapter_id);
- bool start(void);
- static void connect_callback(ServerAdapter* adapter, bool is_success);
-
-protected:
- void done();
-
- ConnectRequestTransaction(int adapter_id) { this->mAdapterId = adapter_id; }
- static ConnectRequestTransaction *sOngoing;
-
- int mAdapterId;
-}; /* class ConnectRequestTransaction */
-
-class ReconnectAdapterTransaction {
-public:
- static bool run(ServerAdapter *targetAdapter);
- bool start();
- static void disconnect_callback(ServerAdapter* adapter, bool is_success);
- static void connect_callback(ServerAdapter* adapter, bool is_success);
-
-protected:
- void done(bool require_restart);
-
- ReconnectAdapterTransaction(ServerAdapter *targetAdapter) {
- this->mTargetAdapter = targetAdapter;
- }
- static ReconnectAdapterTransaction *sOngoing;
-
- ServerAdapter *mTargetAdapter;
-}; /* class ReconnectAdapterTransaction */
-
-/* Netweork Switcher State */
-typedef enum {
- kNSStateReady = 0,
- kNSStateSwitching = 1,
-} NSState;
-
-/* Network Switcher */
-class NetworkSwitcher {
-public:
- /* APIs called by peer through Core */
- void connect_adapter_by_peer(int adapter_id);
- void disconnect_adapter_by_peer(int adapter_id, uint32_t last_seq_no_control,
- uint32_t last_seq_no_data);
- void sleep_adapter_by_peer(int adapter_id);
- void wake_up_adapter_by_peer(int adapter_id);
-
- /* APIs called by receiver/sender loop */
- void reconnect_adapter(ServerAdapter *adapter,
- bool retry_if_already_switching);
-
- /* APIs called by NetworkMonitor */
- bool switch_adapters(int prev_index, int next_index);
-
-private:
- /* Notification of switch done event */
- void done_switch();
-
-public:
- /* State getter */
- NSState get_state(void) {
- std::unique_lock lck(this->mStateLock);
- return this->mState;
- }
-
-private:
- /* State setter */
- void set_state(NSState new_state) {
- std::unique_lock lck(this->mStateLock);
- this->mState = new_state;
- }
-
- /* State */
- NSState mState;
- std::mutex mStateLock;
-
-public:
- /* Singleton */
- static NetworkSwitcher *singleton(void) {
- if (NetworkSwitcher::sSingleton == NULL) {
- NetworkSwitcher::sSingleton = new NetworkSwitcher();
- }
- return NetworkSwitcher::sSingleton;
- }
-
-private:
- /* Singleton */
- static NetworkSwitcher *sSingleton;
- NetworkSwitcher() { this->set_state(NSState::kNSStateReady); }
-
-public:
- /* Its private members can be accessed by auxiliary classes */
- friend SwitchAdapterTransaction;
- friend ConnectRequestTransaction;
- friend ReconnectAdapterTransaction;
-}; /* class NetworkSwitcher */
-} /* namespace sc */
-
-#endif /* !defined(__NETWORK_SWITCHER_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/P2PServer.h b/subprojects/sc/linux/core/inc/P2PServer.h
deleted file mode 100644
index d9418bb3..00000000
--- a/subprojects/sc/linux/core/inc/P2PServer.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __P2P_SERVER_H__
-#define __P2P_SERVER_H__
-
-#include "../../common/inc/RefCount.h"
-
-#include
-#include
-
-#include
-
-namespace sc {
-typedef enum {
- kDisallowed = 0,
- kAllowed = 1
-} P2PServerState;
-
-class P2PServer {
-public:
- bool allow_discover(void);
- bool disallow_discover(void);
-
- virtual bool allow_discover_impl(void) = 0;
- virtual bool disallow_discover_impl(void) = 0;
-
- P2PServerState get_state(void) {
- return this->mState;
- }
-
- P2PServer(const char* name) {
- this->mState = P2PServerState::kDisallowed;
- snprintf(this->mName, sizeof(this->mName), name);
- }
- ~P2PServer(void) {
- }
-
-protected:
- void set_state(P2PServerState new_state) {
- this->mState = new_state;
- }
-
- char* get_name() {
- return this->mName;
- }
-
-private:
- P2PServerState mState;
- char mName[256];
-}; /* class P2PServer */
-} /* namespace sc */
-
-#endif /* !defined(__P2P_SERVER_H__) */
diff --git a/subprojects/sc/linux/core/inc/ProtocolManager.h b/subprojects/sc/linux/core/inc/ProtocolManager.h
deleted file mode 100644
index 52e04769..00000000
--- a/subprojects/sc/linux/core/inc/ProtocolManager.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __PROTOCOL_MANAGER_H__
-#define __PROTOCOL_MANAGER_H__
-
-#include
-
-namespace sc {
-/**
- * This is determined by the structure ProtocolData.
- * In the ProtocolData, the size except the data pointer is the kProHeaderSize.
- */
-#define kProtHeaderSize 6
-
-/**
- * Do not use architecture dependent sized types in this file
- * e.g. such as size_t
- */
-typedef struct {
- uint16_t id;
- uint32_t len;
- const uint8_t *data;
-} ProtocolData;
-
-class ProtocolManager {
-public:
- static void data_to_protocol_data(const uint8_t *data, uint32_t len,
- ProtocolData *ret_pd);
- static uint32_t serialize(ProtocolData *pd, const uint8_t *buf,
- uint32_t offset, uint32_t payload_size,
- uint8_t **ret_vector);
- static int send_packet(uint8_t *serialized, uint32_t packet_size, bool is_control);
-
- static uint32_t recv_packet(uint8_t **seralized, bool is_control);
-
- static uint32_t parse_header(uint8_t *serialized, ProtocolData *ret_pd);
-
-private:
- static uint16_t sPacketId;
- static void serialize_header(ProtocolData *pd, uint8_t *vec_ptr);
- static void serialize_data(const uint8_t *dat_buf, uint32_t len,
- uint8_t *vec_ptr);
-};
-} /* namespace sc */
-
-#endif /* !defined(__PROTOCOL_MANAGER_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/ReceiverThread.h b/subprojects/sc/linux/core/inc/ReceiverThread.h
deleted file mode 100644
index c74f0afa..00000000
--- a/subprojects/sc/linux/core/inc/ReceiverThread.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __RECEIVER_THREAD_H__
-#define __RECEIVER_THREAD_H__
-
-#include "ServerAdapter.h"
-
-#include
-#include
-#include
-
-namespace sc {
-class ServerAdapter;
-
-class ReceiverThread {
-public:
- void launch_thread(void) {
- if (this->mThread == NULL) {
- this->mThread = new std::thread(std::bind(&ReceiverThread::run, this));
- this->mThread->detach();
- }
- }
-
- void finish_thread(void) { this->set_is_thread_running(false); }
-
- void enable_loop(void) { this->set_is_loop_enabled(true); }
-
- void disable_loop(void) { this->set_is_loop_enabled(false); }
-
- void wait_until_disable_loop_done(void) { this->wait_until_loop_ends(); }
-
-private:
- /* Main routine and thread loop */
- void run(void);
-
- /* Receiver loop */
- void receiver_loop(void);
-
-private:
- /* Thread running */
- void set_is_thread_running(bool _is_thread_running) {
- std::unique_lock lck(this->mIsThreadRunningMutex);
- this->mIsThreadRunning = _is_thread_running;
- }
- bool is_thread_running(void) {
- std::unique_lock lck(this->mIsThreadRunningMutex);
- return this->mIsThreadRunning;
- }
-
- bool mIsThreadRunning;
- std::mutex mIsThreadRunningMutex;
-
-private:
- /* Receiver loop end condition */
- void wait_until_loop_ends(void) {
- std::unique_lock lck(this->mIsLoopEndsMutex);
- if (!this->mIsLoopEnds) {
- this->mLoopEndsCond.wait(lck);
- }
- }
- void set_is_loop_ends(bool is_loop_ends) {
- std::unique_lock lck(this->mIsLoopEndsMutex);
- this->mIsLoopEnds = is_loop_ends;
- if (this->mIsLoopEnds) {
- this->mLoopEndsCond.notify_all();
- }
- }
- bool mIsLoopEnds;
- std::mutex mIsLoopEndsMutex;
- std::condition_variable mLoopEndsCond;
-
-private:
- /* Receiver loop enable/disable */
- void set_is_loop_enabled(bool _is_loop_enabled) {
- std::unique_lock lck(this->mIsLoopEnabledMutex);
- this->mIsLoopEnabled = _is_loop_enabled;
- if (this->mIsLoopEnabled) {
- this->mEnableLoopCond.notify_all();
- }
- }
- bool is_loop_enabled(void) {
- std::unique_lock lck(this->mIsLoopEnabledMutex);
- return this->mIsLoopEnabled;
- }
- void wait_until_enable_loop(void) {
- std::unique_lock lck(this->mIsLoopEnabledMutex);
- if(!this->mIsLoopEnabled) {
- this->mEnableLoopCond.wait(lck);
- }
- }
-
- bool mIsLoopEnabled;
- std::mutex mIsLoopEnabledMutex;
- std::condition_variable mEnableLoopCond;
-
-public:
- /* Constructor */
- ReceiverThread(ServerAdapter *motherAdapter) {
- this->mThread = NULL;
- this->mIsLoopEnabled = false;
-
- this->mAdapter = motherAdapter;
- }
-
-private:
- /* Mother adapter */
- ServerAdapter *mAdapter = NULL;
-
- /* Components */
- std::thread *mThread;
-
-}; /* class ReceiverThread */
-} /* namespace sc */
-
-#endif /* !defined(__RECEIVER_THREAD_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/Segment.h b/subprojects/sc/linux/core/inc/Segment.h
deleted file mode 100644
index fba7b47a..00000000
--- a/subprojects/sc/linux/core/inc/Segment.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __SEGMENT_H__
-#define __SEGMENT_H__
-
-#include
-
-#define kSegSize 512
-#define kSegHeaderSize 12
-
-/**
- * < Data Structure of Segment > - Handled by Segment Manager
- * Segment is the minimum unit of sending data through the network.
- * The partial of the segment cannot be sent.
- *
- * (*c.f.) Segment Header (seq_no + flag_len) is delicate to memroy alignment.
- * You need to be careful with the segment header.
- */
-#define SEGMENT_DATA_SIZE (kSegSize + kSegHeaderSize)
-typedef struct
-{
- uint32_t seq_no;
- uint32_t len; // To present the size of the segment(consider the flag)
- uint32_t flag;
- uint8_t data[SEGMENT_DATA_SIZE];
-} Segment; /* struct Segment */
-
-#endif /* !defined(__SEGMENT_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/SegmentManager.h b/subprojects/sc/linux/core/inc/SegmentManager.h
deleted file mode 100644
index bafaad4a..00000000
--- a/subprojects/sc/linux/core/inc/SegmentManager.h
+++ /dev/null
@@ -1,215 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __SEGMENT_MANAGER_H__
-#define __SEGMENT_MANAGER_H__
-
-#include "Segment.h"
-#include "SegmentQueue.h"
-
-#include "../../common/inc/Counter.h"
-
-#include "../../configs/ExpConfig.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-namespace sc {
-
-#define kSegFreeThreshold 256
-
-/**
- * Queue Type
- */
-typedef enum {
- kSQSendData = 0,
- kSQRecvData = 1,
- kSQSendControl = 2,
- kSQRecvControl = 3,
- kNumSQ = 4,
- kSQUnknown = 999
-} SegQueueType; /* enum SegQueueType */
-
-/**
- * Dequeue Type
- */
-typedef enum {
- kDeqSendControlData = 0,
- kDeqRecvData = 1,
- kDeqRecvControl = 2,
- kNumDeq = 3,
- kDeqUnknown = 999
-} SegDequeueType; /* enum SegDequeueType */
-
-/**
- * Types of Flag
- */
-typedef enum {
- kSegFlagMF = 1,
- kSegFlagControl = 2
-} SegFlagVal; /* enum SegFlagVal */
-
-/**
- * Types of Sequence Number
- */
-typedef enum {
- kSNData = 0,
- kSNControl = 1,
- kNumSN = 2
-} SegSeqNumType; /* enum SegSeqNumType */
-
-class SegmentManager {
-public:
- /* Used in protocol manager */
- int send_to_segment_manager(uint8_t *data, size_t len, bool is_control);
- uint8_t *recv_from_segment_manager(void *proc_data_handle, bool is_control);
-
- void failed_sending(Segment *seg);
- Segment *get_failed_sending(void);
- void enqueue(SegQueueType queue_type, Segment *seg);
- Segment *dequeue(SegDequeueType dequeue_type);
- Segment *get_free_segment(void);
- void free_segment(Segment *seg);
- void free_segment_all(void);
-
- void wake_up_dequeue_waiting(SegDequeueType dequeue_type) {
- this->mDequeueCond[dequeue_type].notify_all();
- }
-
- int get_queue_length(int type) {
- return this->mSegmentQueues[type].get_queue_length();
- }
-
- int get_queue_data_size(int type) {
- return this->mSegmentQueues[type].get_queue_length() * SEGMENT_DATA_SIZE;
- }
-
- int get_failed_sending_queue_data_size() {
- return this->mFailedSendingQueueLength.get_value() * SEGMENT_DATA_SIZE;
- }
-
- int get_send_request_per_sec() { return this->mSendRequest.get_speed(); }
-
- /* Singleton */
- static SegmentManager *singleton(void) {
- if (sSingleton == NULL)
- sSingleton = new SegmentManager();
- return sSingleton;
- }
-
-private:
- SegDequeueType queue_type_to_dequeue_type(SegQueueType queue_type);
- SegQueueType get_target_queue_type(SegDequeueType dequeue_type);
-
- void wait_for_dequeue_locked(SegDequeueType dequeue_type,
- std::unique_lock &dequeue_lock);
-
-private:
- /* Singleton */
- static SegmentManager *sSingleton;
- SegmentManager(void) {
- for (int i = 0; i < kNumSN; i++) {
- this->mNextSeqNo[i] = 0;
- }
- this->mFreeSegmentListSize = 0;
-
- is_start = 0;
- is_finish = 0;
- }
-
- // for experiment
- int is_start, is_finish;
- struct timeval start, end;
- FILE *fp2;
-
- /* When access to queue, lock should be acquired */
- std::mutex mDequeueLock[kNumDeq];
- std::mutex mSendFailQueueLock;
- std::condition_variable mDequeueCond[kNumDeq];
-
- std::mutex mNextSeqNoLock[kNumSN];
- uint32_t mNextSeqNo[kNumSN];
- uint32_t get_next_seq_no(SegSeqNumType seq_num_type, uint32_t num_segments);
-
- SegmentQueue mSegmentQueues[kNumSQ];
- std::list mSendFailQueue;
-
- /* Statistics */
- Counter mSendRequest;
- Counter mFailedSendingQueueLength;
-
- /* Reserved free segment list */
- std::mutex mFreeSegmentListLock;
- std::list mFreeList;
- uint32_t mFreeSegmentListSize;
-
- /* Wait data before disconnection */
-public:
- void wait_receiving(uint32_t wait_seq_no_control, uint32_t wait_seq_no_data) {
- std::unique_lock lck(this->mWaitReceivingMutex);
- this->mIsWaitReceiving = true;
- this->mWaitSeqNoControl = wait_seq_no_control;
- this->mWaitSeqNoData = wait_seq_no_data;
- this->mWaitReceivingCond.wait(lck);
- }
-
-private:
- void check_receiving_done() {
- bool is_wakeup = false;
- {
- std::unique_lock lck(this->mWaitReceivingMutex);
- uint32_t expected_seq_no_control =
- this->mSegmentQueues[kSQRecvControl].get_expected_seq_no();
- uint32_t expected_seq_no_data =
- this->mSegmentQueues[kSQRecvData].get_expected_seq_no();
- if (this->mIsWaitReceiving &&
- expected_seq_no_control >= this->mWaitSeqNoControl &&
- expected_seq_no_data >= this->mWaitSeqNoData) {
- is_wakeup = true;
- }
- }
- if (is_wakeup) {
- this->mWaitReceivingCond.notify_all();
- this->mIsWaitReceiving = false;
- }
- }
-
- bool mIsWaitReceiving = false;
- uint32_t mWaitSeqNoControl = 0;
- uint32_t mWaitSeqNoData = 0;
- std::mutex mWaitReceivingMutex;
- std::condition_variable mWaitReceivingCond;
-
-private:
- void serialize_segment_header(Segment *seg);
-
- void release_segment_from_free_list(uint32_t threshold);
-
- void reset_send_queue(void);
- void reset_recv_queue(void);
-}; /* class SegmentManager */
-} /* namespace sc */
-
-#endif // !defined(__SEGMENT_MANAGER_H__)
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/SegmentQueue.h b/subprojects/sc/linux/core/inc/SegmentQueue.h
deleted file mode 100644
index 41898db6..00000000
--- a/subprojects/sc/linux/core/inc/SegmentQueue.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __SEGMENT_QUEUE_H__
-#define __SEGMENT_QUEUE_H__
-
-#include "Segment.h"
-
-#include "../../common/inc/Counter.h"
-#include "../../common/inc/DebugLog.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-namespace sc {
-class SegmentQueue {
-public:
- bool enqueue(Segment *seg) {
- bool continuous_segment_enqueued = false;
- if (seg->seq_no == this->mExpectedSeqNo) {
- /*
- * If the sequence number is the right next one,
- * it executes enqueuing logic normally.
- */
- this->mExpectedSeqNo++;
- this->mMainQueue.push_back(seg);
- this->mQueueLength.increase();
- continuous_segment_enqueued = true;
- } else {
- /*
- * If the sequence number is not the next expected one,
- * it enqueues its segments to the pending queue, not normal queue.
- */
- if (seg->seq_no <= this->mExpectedSeqNo) {
- LOG_ERR("Sequence # Error!: %d > %d", seg->seq_no,
- this->mExpectedSeqNo);
- }
- assert(seg->seq_no > this->mExpectedSeqNo);
-
- std::list::iterator curr_it = this->mPendingQueue.begin();
-
- /*
- * If we received a unsequential segment, put it into pending queue.
- * Pending queue should retain segments in order of sequence number.
- */
- while (curr_it != this->mPendingQueue.end()) {
- Segment *walker = *curr_it;
- assert(walker->seq_no != seg->seq_no);
- if (walker->seq_no > seg->seq_no)
- break;
- curr_it++;
- }
- this->mPendingQueue.insert(curr_it, seg);
- }
-
- /*
- * Finally, we put all the consequent segments into type queue.
- * If no segment in the pending queue matches to the next seq_no,
- * Then this process is just skipped.
- */
- std::list::iterator curr_it = this->mPendingQueue.begin();
- while (curr_it != this->mPendingQueue.end() &&
- (*curr_it)->seq_no == this->mExpectedSeqNo) {
- this->mExpectedSeqNo++;
- this->mMainQueue.push_back(*curr_it);
- this->mQueueLength.increase();
- continuous_segment_enqueued = true;
-
- std::list::iterator to_erase = curr_it++;
- this->mPendingQueue.erase(to_erase);
- }
-
- return continuous_segment_enqueued;
- }
-
- Segment *dequeue(void) {
- // Check the main queue
- Segment *segment_dequeued = this->mMainQueue.front();
- if (segment_dequeued == NULL) {
- return NULL;
- } else {
- // Update main queue
- this->mMainQueue.pop_front();
- this->mQueueLength.decrease();
- return segment_dequeued;
- }
- }
-
- int get_queue_length(void) { return this->mQueueLength.get_value(); }
-
- uint32_t get_expected_seq_no(void) { return this->mExpectedSeqNo; }
-
- SegmentQueue(void) { this->mExpectedSeqNo = 0; }
-
-private:
- std::list mMainQueue; /* In-order & Continuous */
- std::list mPendingQueue; /* In-order & Noncontinuous */
-
- Counter mQueueLength;
-
- uint32_t mExpectedSeqNo;
-}; /* class SegmentQueue */
-} /* namespace sc */
-
-#endif /* !defined(__SEGMENT_QUEUE_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/SenderThread.h b/subprojects/sc/linux/core/inc/SenderThread.h
deleted file mode 100644
index 372b79ef..00000000
--- a/subprojects/sc/linux/core/inc/SenderThread.h
+++ /dev/null
@@ -1,186 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __SENDER_THREAD_H__
-#define __SENDER_THREAD_H__
-
-#include "ServerAdapter.h"
-
-#include
-#include
-#include
-
-namespace sc {
-class ServerAdapter;
-
-class SenderThread {
-public:
- void launch_thread(void) {
- if (this->mThread == NULL) {
- this->mThread = new std::thread(std::bind(&SenderThread::run, this));
- this->mThread->detach();
- }
- }
-
- void finish_thread(void) { this->set_is_thread_running(false); }
-
- void enable_loop(void) { this->set_is_loop_enabled(true); }
-
- void disable_loop(void) { this->set_is_loop_enabled(false); }
-
- void wait_until_disable_loop_done(void) { this->wait_until_loop_ends(); }
-
- void resume_loop(void) { this->set_is_loop_paused(false); }
-
- void pause_loop(void) { this->set_is_loop_paused(true); }
-
-private:
- /* Main routine and thread loop */
- void run(void);
-
- /* Sender loop */
- void sender_loop(void);
-
-private:
- /* Thread running */
- void set_is_thread_running(bool _is_thread_running) {
- std::unique_lock lck(this->mIsThreadRunningMutex);
- this->mIsThreadRunning = _is_thread_running;
- }
- bool is_thread_running(void) {
- std::unique_lock lck(this->mIsThreadRunningMutex);
- return this->mIsThreadRunning;
- }
-
- bool mIsThreadRunning;
- std::mutex mIsThreadRunningMutex;
-
-private:
- /* Sender loop end condition */
- void wait_until_loop_ends(void) {
- std::unique_lock lck(this->mIsLoopEndsMutex);
- if (!this->mIsLoopEnds) {
- this->mLoopEndsCond.wait(lck);
- }
- }
- void set_is_loop_ends(bool is_loop_ends) {
- std::unique_lock lck(this->mIsLoopEndsMutex);
- this->mIsLoopEnds = is_loop_ends;
- if (this->mIsLoopEnds) {
- this->mLoopEndsCond.notify_all();
- }
- }
- bool mIsLoopEnds;
- std::mutex mIsLoopEndsMutex;
- std::condition_variable mLoopEndsCond;
-
-private:
- /* Sender loop enable/disable */
- void set_is_loop_enabled(bool _is_loop_enabled) {
- std::unique_lock lck(this->mIsLoopEnabledMutex);
- this->mIsLoopEnabled = _is_loop_enabled;
- if (this->mIsLoopEnabled) {
- this->mEnableLoopCond.notify_all();
- }
- }
- bool is_loop_enabled(void) {
- std::unique_lock lck(this->mIsLoopEnabledMutex);
- return this->mIsLoopEnabled;
- }
- void wait_until_enable_loop(void) {
- std::unique_lock lck(this->mIsLoopEnabledMutex);
- if (!this->mIsLoopEnabled) {
- this->mEnableLoopCond.wait(lck);
- }
- }
-
- bool mIsLoopEnabled;
- std::mutex mIsLoopEnabledMutex;
- std::condition_variable mEnableLoopCond;
-
-public:
- /* Sender loop pause/resume */
- bool is_loop_paused(void) {
- std::unique_lock lck(this->mIsLoopPausedMutex);
- return this->mIsLoopPaused;
- }
-
-private:
- /* Sender loop pause/resume */
- void set_is_loop_paused(bool _is_loop_paused) {
- std::unique_lock lck(this->mIsLoopPausedMutex);
- this->mIsLoopPaused = _is_loop_paused;
- if (!this->mIsLoopPaused) {
- this->mResumeLoopCond.notify_all();
- }
- }
- void wait_until_resume_loop(void) {
- std::unique_lock lck(this->mIsLoopPausedMutex);
- if (this->mIsLoopPaused) {
- this->mResumeLoopCond.wait(lck);
- }
- }
-
- bool mIsLoopPaused = false;
- std::mutex mIsLoopPausedMutex;
- std::condition_variable mResumeLoopCond;
-
-public:
- /* Sender loop last sequence number */
- uint32_t get_last_seq_no_control() {
- return this->mLastSeqNoControl;
- }
- uint32_t get_last_seq_no_data() {
- return this->mLastSeqNoData;
- }
-
-private:
- /* Sender loop last sequence number */
- void set_last_seq_no_control(uint32_t last_seq_no_control) {
- this->mLastSeqNoControl = last_seq_no_control;
- }
-
- void set_last_seq_no_data(uint32_t last_seq_no_data) {
- this->mLastSeqNoData = last_seq_no_data;
- }
-
- uint32_t mLastSeqNoControl;
- uint32_t mLastSeqNoData;
-
-public:
- /* Constructor */
- SenderThread(ServerAdapter *motherAdapter) {
- this->mThread = NULL;
- this->mIsLoopEnabled = false;
- this->mIsLoopPaused = false;
-
- this->mAdapter = motherAdapter;
- }
-
-private:
- /* Mother adapter */
- ServerAdapter *mAdapter = NULL;
-
- /* Components */
- std::thread *mThread;
-
-}; /* class SenderThread */
-} /* namespace sc */
-
-#endif /* !defined(__SENDER_THREAD_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/ServerAdapter.h b/subprojects/sc/linux/core/inc/ServerAdapter.h
deleted file mode 100644
index 02869bac..00000000
--- a/subprojects/sc/linux/core/inc/ServerAdapter.h
+++ /dev/null
@@ -1,245 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __SERVER_ADAPTER_H__
-#define __SERVER_ADAPTER_H__
-
-#include "Device.h"
-#include "P2PServer.h"
-#include "ReceiverThread.h"
-#include "SenderThread.h"
-#include "ServerAdapterState.h"
-#include "ServerSocket.h"
-
-#include "../../common/inc/Counter.h"
-
-#include "../../configs/ExpConfig.h"
-
-#include
-#include
-#include
-
-#include
-#include
-
-namespace sc {
-
-typedef void (*ConnectCallback)(ServerAdapter *adapter, bool is_success);
-typedef void (*DisconnectCallback)(ServerAdapter *adapter, bool is_success);
-
-class ServerAdapterStateListener;
-class ReceiverThread;
-class SenderThread;
-
-class ServerAdapter {
-public:
- /* Basic APIs
- * - launch/finish sender/receiver threads
- * - connect, disconnect, sleep, wake up
- * - send, receive
- */
- /* Basic APIs related to launching/finishing sender/receiver threads */
- void launch_threads(void);
- void finish_thread(void);
-
- /* Basic APIs related to connection/sleeping */
- void connect(ConnectCallback callback, bool is_send_request);
- void disconnect_on_command(DisconnectCallback callback);
- void disconnect_on_peer_command(DisconnectCallback callback,
- uint32_t peer_last_seq_no_control,
- uint32_t peer_last_seq_no_data);
- void disconnect_on_failure(DisconnectCallback callback);
- void sleep(DisconnectCallback callback, bool is_send_request);
- void wake_up(ConnectCallback callback, bool is_send_request);
- void connect_or_wake_up(ConnectCallback callback, bool is_send_request);
-
- /* Basic APIs related to data transmission */
- int send(const void *buf, size_t len);
- int receive(void *buf, size_t len);
-
-private:
- /* Connect */
- void connect_internal(ConnectCallback callback);
- bool __connect_internal(void);
- ConnectCallback mConnectCallback = NULL;
-
- /* Disconnect */
- void disconnect_internal(DisconnectCallback callback);
- bool __disconnect_internal(ServerAdapterState oldState);
- DisconnectCallback mDisconnectCallback = NULL;
-
- /* Wake up */
- void wake_up_internal(void);
-
-private:
- /* Sender Thread */
- SenderThread *mSenderThread = NULL;
- friend SenderThread;
-
- /* Receiver Thread */
- ReceiverThread *mReceiverThread = NULL;
-
-public:
- /* Statistics getters */
- int get_bandwidth_up(void) { this->mSendDataSize.get_speed(); }
- int get_bandwidth_down(void) { this->mReceiveDataSize.get_speed(); }
-
-private:
- /* Statistics */
- Counter mSendDataSize;
- Counter mReceiveDataSize;
-
-public:
- /* Attribute getters */
- char *get_name(void) { return this->mName; }
- int get_id(void) { return this->mId; }
- bool is_disconnecting_on_purpose(void) {
- return this->mIsDisconnectingOnPurpose;
- }
- bool is_disconnecting_on_purpose_peer(void) {
- return this->mIsDisconnectingOnPurposePeer;
- }
-
- /* Component getters */
- Device *get_device(void) { return this->mDevice; }
- P2PServer *get_p2p_server(void) { return this->mP2PServer; }
- ServerSocket *get_server_socket(void) { return this->mServerSocket; }
-
- /* Attribute setters */
- void start_disconnecting_on_purpose() {
- this->mIsDisconnectingOnPurpose = true;
- }
-
- void wait_for_disconnecting_on_purpose_peer(void) {
- std::unique_lock lck(this->mWaitForDisconnectAckLock);
- this->mWaitForDisconnectAckCond.wait(lck);
- }
-
- void peer_knows_disconnecting_on_purpose() {
- this->mIsDisconnectingOnPurposePeer = true;
- this->mWaitForDisconnectAckCond.notify_all();
- }
-
-private:
- /* Attribute setters */
- void finish_disconnecting_on_purpose() {
- this->mIsDisconnectingOnPurpose = false;
- this->mIsDisconnectingOnPurposePeer = false;
- }
-
-private:
- /* Attributes */
- char mName[256];
-
- /*
- * TODO: ID is now defined by user. However, the ID should be maintained by
- * system finally.
- */
- int mId;
- bool mIsDisconnectingOnPurpose; /* Disconnecting on purpose by a device */
- bool mIsDisconnectingOnPurposePeer; /* Peer knows disconnecting on purpose */
- std::mutex mWaitForDisconnectAckLock;
- std::condition_variable mWaitForDisconnectAckCond;
-
- /* Components */
- Device *mDevice = NULL;
- P2PServer *mP2PServer = NULL;
- ServerSocket *mServerSocket = NULL;
-
- /* State Listeners */
- std::vector mStateListeners;
-
-private:
- /* EXP: Measure sender thread loop's time interval */
-#ifdef EXP_MEASURE_INTERVAL_SENDER
-private:
- int mSendCount = 0;
- /* Milliseconds */
- int mIntervals[4] = {
- 0,
- };
-#endif
-
-public:
- /* State getter */
- ServerAdapterState get_state(void) {
- std::unique_lock lck(this->mStateLock);
- return this->mState;
- }
-
- /* Add state listener */
- void listen_state(ServerAdapterStateListener *listener) {
- std::unique_lock lck(this->mStateLock);
-
- if (listener == NULL)
- return;
- this->mStateListeners.push_back(listener);
- }
-
- static std::string server_adapter_state_to_string(ServerAdapterState state) {
- char *const state_string[] = {"Disconnected", "Connecting", "Active",
- "Disconnecting", "GoingSleeping", "Sleeping",
- "WakingUp"};
- int state_index = (int)state;
- if (state_index >= ServerAdapterState::kASNum || state_index < 0) {
- return std::string("");
- } else {
- return std::string(state_string[state_index]);
- }
- }
-
-private:
- /* State setter */
- void set_state(ServerAdapterState new_state);
-
- /* State */
- ServerAdapterState mState;
- std::mutex mStateLock;
-
-public:
- /* Constructor */
- ServerAdapter(int id, const char *name) {
- this->mState = ServerAdapterState::kDisconnected;
- snprintf(this->mName, sizeof(this->mName), "%s", name);
- this->mId = id;
- this->mIsDisconnectingOnPurpose = false;
- this->mIsDisconnectingOnPurposePeer = false;
- }
-
- ~ServerAdapter() {
- if (this->mP2PServer != NULL) {
- delete this->mP2PServer;
- }
- if (this->mServerSocket != NULL) {
- delete this->mServerSocket;
- }
- }
-
-protected:
- /* Initializer called by child classes */
- void initialize(Device *device, P2PServer *p2pServer,
- ServerSocket *serverSocket) {
- this->mDevice = device;
- this->mP2PServer = p2pServer;
- this->mServerSocket = serverSocket;
- }
-}; /* class ServerAdapter */
-} /* namespace sc */
-
-#endif /* !defined(__SERVER_ADAPTER_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/ServerAdapterState.h b/subprojects/sc/linux/core/inc/ServerAdapterState.h
deleted file mode 100644
index f0d0f10b..00000000
--- a/subprojects/sc/linux/core/inc/ServerAdapterState.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __SERVER_ADAPTER_STATE_H__
-#define __SERVER_ADAPTER_STATE_H__
-
-namespace sc {
-
-typedef enum {
- kDisconnected = 0,
- kConnecting = 1,
- kActive = 2,
- kDisconnecting = 3,
- kGoingSleeping = 4,
- kSleeping = 5,
- kWakingUp = 6,
- kASNum = 7
-} ServerAdapterState; /* enum ServerAdapterState */
-
-} /* namespace sc */
-
-#endif /* !defined(__SERVER_ADAPTER_STATE_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/ServerAdapterStateListener.h b/subprojects/sc/linux/core/inc/ServerAdapterStateListener.h
deleted file mode 100644
index 91443272..00000000
--- a/subprojects/sc/linux/core/inc/ServerAdapterStateListener.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __SERVER_ADAPTER_STATE_LISTENER_H__
-#define __SERVER_ADAPTER_STATE_LISTENER_H__
-
-#include "ServerAdapter.h"
-#include "ServerAdapterState.h"
-
-namespace sc {
-class ServerAdapter;
-class ServerAdapterStateListener {
-public:
- virtual void onUpdateServerAdapterState(ServerAdapter *adapter,
- ServerAdapterState old_state,
- ServerAdapterState new_state) = 0;
-}; /* class ServerAdapterStateListener */
-} /* namespace sc */
-
-#endif /* !defined(__SERVER_ADAPTER_STATE_LISTENER_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/inc/ServerSocket.h b/subprojects/sc/linux/core/inc/ServerSocket.h
deleted file mode 100644
index 3cfe7ceb..00000000
--- a/subprojects/sc/linux/core/inc/ServerSocket.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __SERVER_SOCKET_H__
-#define __SERVER_SOCKET_H__
-
-#include
-#include
-
-#include
-
-namespace sc {
-typedef enum {
- kClosed = 0,
- kOpening = 1,
- kOpened = 2,
- kClosing = 3
-} ServerSocketState; /* enum ServerSocketState */
-
-class ServerSocket {
-public:
- bool open(void);
- bool close(void);
- int send(const void *data_buffer, size_t data_length);
- int receive(void *data_buffer, size_t data_length);
-
- virtual bool open_impl(void) = 0;
- virtual bool close_impl(void) = 0;
- virtual int send_impl(const void *data_buffer, size_t data_length) = 0;
- virtual int receive_impl(void *data_buffer, size_t data_length) = 0;
-
- ServerSocketState get_state(void) { return this->mState; }
-
- ServerSocket(const char *name) {
- this->mState = ServerSocketState::kClosed;
- snprintf(this->mName, sizeof(this->mName), name);
- }
-
- ~ServerSocket(void) {}
-
-protected:
- void set_state(ServerSocketState new_state) { this->mState = new_state; }
-
- char *get_name() { return this->mName; }
-
-private:
- ServerSocketState mState;
- char mName[256];
-}; /* class ServerSocket */
-} /* namespace sc */
-
-#endif /* !defined(__SERVER_SOCKET_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/API.cpp b/subprojects/sc/linux/core/src/API.cpp
deleted file mode 100644
index b8e29411..00000000
--- a/subprojects/sc/linux/core/src/API.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/API.h"
-
-#include "../inc/APIInternal.h"
-#include "../inc/NetworkMonitor.h"
-
-#include
-#include
-
-using namespace sc;
-
-std::mutex g_wait_lock_start_sc;
-std::condition_variable g_wait_cond_start_sc;
-bool g_is_start_sc_done;
-bool g_start_sc_success;
-
-std::mutex g_wait_lock_stop_sc;
-std::condition_variable g_wait_cond_stop_sc;
-bool g_is_stop_sc_done;
-bool g_stop_sc_success;
-
-// TODO: make it into synchronous call
-void sc::start_sc(StartCallback startCallback) {
- // Core start procedure
- g_is_start_sc_done = false;
- Core::singleton()->start();
- NetworkMonitor::singleton()->start();
-
- // Wait until core start thread ends
- if(!g_is_start_sc_done) {
- std::unique_lock lck(g_wait_lock_start_sc);
- g_wait_cond_start_sc.wait(lck);
- }
-
- // Execute callback
- if(startCallback != NULL) {
- startCallback(g_start_sc_success);
- }
-}
-
-void sc::start_sc_done(bool is_success) {
- g_is_start_sc_done = true;
- g_start_sc_success = is_success;
- g_wait_cond_start_sc.notify_all();
-}
-
-// TODO: make it into synchronous call
-void sc::stop_sc(StopCallback stopCallback) {
- // Core stop procedure
- g_is_stop_sc_done = false;
- NetworkMonitor::singleton()->stop();
- Core::singleton()->stop();
-
- // Wait until core stop thread ends
- if(!g_is_stop_sc_done) {
- std::unique_lock lck(g_wait_lock_stop_sc);
- g_wait_cond_stop_sc.wait(lck);
- }
-
- // Execute callback
- if(stopCallback != NULL) {
- stopCallback(g_stop_sc_success);
- }
-}
-
-void sc::stop_sc_done(bool is_success) {
- g_is_stop_sc_done = true;
- g_stop_sc_success = is_success;
- g_wait_cond_stop_sc.notify_all();
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/ControlMessageReceiver.cpp b/subprojects/sc/linux/core/src/ControlMessageReceiver.cpp
deleted file mode 100644
index 0345ff29..00000000
--- a/subprojects/sc/linux/core/src/ControlMessageReceiver.cpp
+++ /dev/null
@@ -1,187 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/ControlMessageReceiver.h"
-
-#include "../inc/Core.h"
-#include "../inc/NetworkSwitcher.h"
-
-#include "../../common/inc/DebugLog.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-#define THREAD_NAME "Control Message Receiving"
-
-using namespace sc;
-
-void ControlMessageReceiver::start_receiving_thread(void) {
- this->mReceivingThread = new std::thread(
- std::bind(&ControlMessageReceiver::receiving_thread_loop, this));
- this->mReceivingThread->detach();
-}
-
-void ControlMessageReceiver::stop_receiving_thread(void) {
- this->mReceivingThreadOn = false;
-}
-
-void ControlMessageReceiver::receiving_thread_loop(void) {
- this->mReceivingThreadOn = true;
- LOG_THREAD_LAUNCH(THREAD_NAME);
-
- while (this->mReceivingThreadOn) {
- this->receiving_thread_loop_internal();
- }
-
- LOG_THREAD_FINISH(THREAD_NAME);
- this->mReceivingThreadOn = false;
-}
-
-bool ControlMessageReceiver::receiving_thread_loop_internal(void) {
- void *message_buffer = NULL;
- Core::singleton()->receive(&message_buffer, true);
- if (message_buffer == NULL) {
- return false;
- }
-
- std::string message((char *)message_buffer);
-
- // Find separator location (between first line and other lines)
- std::size_t separator_pos = message.find('\n');
-
- // Divide the message into first line & other lines
- std::string first_line(message.substr(0, separator_pos));
- std::string other_lines(message.substr(separator_pos));
-
- int control_message_code = std::stoi(first_line);
-
- switch (control_message_code) {
- case CMCode::kCMCodeConnect:
- case CMCode::kCMCodeSleep:
- case CMCode::kCMCodeWakeUp:
- case CMCode::kCMCodeDisconnectAck: {
- // Normal type
- int adapter_id = std::stoi(other_lines);
- this->on_receive_normal_message(control_message_code, adapter_id);
- break;
- }
- case CMCode::kCMCodeDisconnect: {
- // Disconnect type
- // Divide the message into second line, third line, fourth line
- separator_pos = other_lines.find('\n');
- std::string second_line(other_lines.substr(0, separator_pos));
- std::string third_fourth_line(other_lines.substr(separator_pos));
- separator_pos = third_fourth_line.find('\n');
- std::string third_line(third_fourth_line.substr(0, separator_pos));
- std::string fourth_line(third_fourth_line.substr(separator_pos));
-
- int adapter_id = std::stoi(second_line);
- uint32_t final_seq_no_control = std::stoul(third_line);
- uint32_t final_seq_no_data = std::stoul(fourth_line);
-
- this->on_receive_disconnect_message(adapter_id, final_seq_no_control,
- final_seq_no_data);
- }
- case CMCode::kCMCodePriv: {
- // Priv type
- this->on_receive_priv_message(other_lines);
- break;
- }
- default: {
- LOG_ERR("Unknown Control Message Code(%d)!\n%s", control_message_code,
- message.c_str());
- break;
- }
- }
-
- free(message_buffer);
- return true;
-}
-
-void ControlMessageReceiver::on_receive_normal_message(int control_message_code,
- int adapter_id) {
- NetworkSwitcher *ns = NetworkSwitcher::singleton();
- switch (control_message_code) {
- case CMCode::kCMCodeConnect: {
- LOG_VERB("Receive(Control Msg): Request(Connect %d)", adapter_id);
- ns->connect_adapter_by_peer(adapter_id);
- break;
- }
- case CMCode::kCMCodeSleep: {
- LOG_VERB("Receive(Control Msg): Request(Sleep %d)", adapter_id);
- ns->sleep_adapter_by_peer(adapter_id);
- break;
- }
- case CMCode::kCMCodeWakeUp: {
- LOG_VERB("Receive(Control Msg): Request(WakeUp %d)", adapter_id);
- ns->wake_up_adapter_by_peer(adapter_id);
- break;
- }
- case CMCode::kCMCodeDisconnectAck: {
- LOG_VERB("Receive(Control Msg): Request(DisconnectAck %d)", adapter_id);
- ServerAdapter *disconnect_adapter =
- Core::singleton()->find_adapter_by_id((int)adapter_id);
- if (disconnect_adapter == NULL) {
- LOG_WARN("Cannot find adapter %d", (int)adapter_id);
- } else {
- disconnect_adapter->peer_knows_disconnecting_on_purpose();
- }
- break;
- }
- default: {
- // Never reach here
- break;
- }
- }
-}
-
-void ControlMessageReceiver::on_receive_disconnect_message(
- int adapter_id, uint32_t final_seq_no_control, uint32_t final_seq_no_data) {
- LOG_VERB("Receive(Control Msg): Request(Disconnect %d / "
- "final_seq_no_control=%lu / final_seq_no_data=%lu)",
- adapter_id, final_seq_no_control, final_seq_no_data);
- NetworkSwitcher *ns = NetworkSwitcher::singleton();
- ns->disconnect_adapter_by_peer(adapter_id, final_seq_no_control,
- final_seq_no_data);
-}
-
-void ControlMessageReceiver::on_receive_priv_message(std::string contents) {
- // Find separator location (between second line and other lines)
- std::size_t separator_pos = contents.find('\n');
-
- // Divide the message into second line & other lines
- std::string second_line(contents.substr(0, separator_pos));
- std::string priv_message(contents.substr(separator_pos));
-
- int priv_type = std::stoi(second_line);
-
- // Notify the priv message
- for (std::vector::iterator it =
- this->mPrivMessageListeners.begin();
- it != this->mPrivMessageListeners.end(); it++) {
- ControlPrivMessageListener *listener = *it;
- if (listener != NULL) {
- listener->on_receive_control_priv_message(priv_type, priv_message);
- }
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/ControlMessageSender.cpp b/subprojects/sc/linux/core/src/ControlMessageSender.cpp
deleted file mode 100644
index 6d29652a..00000000
--- a/subprojects/sc/linux/core/src/ControlMessageSender.cpp
+++ /dev/null
@@ -1,124 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/ControlMessageSender.h"
-
-#include "../inc/API.h"
-
-#include "../../configs/ExpConfig.h"
-
-#include
-#include
-#include
-
-using namespace sc;
-
-void ControlMessageSender::send_control_message(std::string &message) {
- int message_buffer_size = message.size() + 1;
- char *message_buffer = new char[message_buffer_size];
- strncpy(message_buffer, message.c_str(), message_buffer_size);
- message_buffer[message_buffer_size - 1] = '\0';
-#ifdef VERBOSE_CONTROL_RAW_MESSAGE
- LOG_DEBUG("Send(Control Msg) RAW (len=%d)::\n%s", message_buffer_size,
- message_buffer);
-#endif
- int res = Core::singleton()->send(message_buffer, message_buffer_size, true);
-}
-
-void ControlMessageSender::send_request(CMCode request_code, int adapter_id) {
- std::string message("");
-
- // Write first line (request code)
- message.append(std::to_string(request_code));
- message.append("\n");
-
- // Write second line (adapter ID)
- message.append(std::to_string(adapter_id));
-
- // Send the message
- this->send_control_message(message);
-}
-
-void ControlMessageSender::send_request_connect(int adapter_id) {
- this->send_request(CMCode::kCMCodeConnect, adapter_id);
- LOG_VERB("Send(Control Msg): Request(Connect %d)", adapter_id);
-}
-
-void ControlMessageSender::send_request_disconnect(
- int adapter_id, uint32_t final_seq_no_control, uint32_t final_seq_no_data) {
- std::string message("");
-
- // Write first line (request code)
- message.append(std::to_string(CMCode::kCMCodeDisconnect));
- message.append("\n");
-
- // Write second line (adapter ID)
- message.append(std::to_string(adapter_id));
- message.append("\n");
-
- // Write third line (final seq_no of control segments)
- message.append(std::to_string(final_seq_no_control));
- message.append("\n");
-
- // Write fourth line (final seq_no of data segments)
- message.append(std::to_string(final_seq_no_data));
-
- // Send the message
- this->send_control_message(message);
- LOG_VERB("Send(Control Msg): Request(Disconnect %d; "
- "final_seq_no_control=%lu; final_seq_no_data=%lu)",
- adapter_id, final_seq_no_control, final_seq_no_data);
-}
-
-void ControlMessageSender::send_request_disconnect_ack(int adapter_id) {
- this->send_request(CMCode::kCMCodeDisconnectAck, adapter_id);
- LOG_VERB("Send(Control Msg): Request(DisconnectAck %d)", adapter_id);
-}
-
-void ControlMessageSender::send_request_sleep(int adapter_id) {
- this->send_request(CMCode::kCMCodeSleep, adapter_id);
- LOG_VERB("Send(Control Msg): Request(Sleep %d)", adapter_id);
-}
-
-void ControlMessageSender::send_request_wake_up(int adapter_id) {
- this->send_request(CMCode::kCMCodeWakeUp, adapter_id);
- LOG_VERB("Send(Control Msg): Request(WakeUp %d)", adapter_id);
-}
-
-void ControlMessageSender::send_noti_private_data(PrivType priv_type,
- char *priv_data_buffer,
- uint32_t priv_data_length) {
- std::string message("");
-
- // Write first line (request code)
- message.append(std::to_string(CMCode::kCMCodePriv));
- message.append("\n");
-
- // Write second line (priv type)
- message.append(std::to_string(priv_type));
- message.append("\n");
-
- // Write third+ line (priv data)
- message.append(priv_data_buffer, priv_data_length);
-
- // Send the message
- this->send_control_message(message);
- LOG_VERB("Send(Control Msg): Request(Priv %d)\n%s", priv_type,
- priv_data_buffer);
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/Core.cpp b/subprojects/sc/linux/core/src/Core.cpp
deleted file mode 100644
index 48afc40f..00000000
--- a/subprojects/sc/linux/core/src/Core.cpp
+++ /dev/null
@@ -1,315 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/Core.h"
-
-#include "../inc/NetworkSwitcher.h"
-#include "../inc/ProtocolManager.h"
-#include "../inc/SegmentManager.h"
-
-#include "../../common/inc/DebugLog.h"
-
-#include "../../configs/ExpConfig.h"
-
-#include
-#include
-#include
-#include
-#include
-
-/**
- * < When to Free Buffer >
- * [*] Sending
- * When ProtocolManager::serialize() method is invoked, memory will be
- * allocated. ProtocolManager is in charge of allocating this memory.
- * SegmentManager is in charge of freeing this memory.
- * [*] Receiving
- * SegmentManager invokes ProtocolManager::parse() with allocated serialized
- * vector. SegmentManager is in charge of allocating this memory. After copying
- * to application memory, serialized vector should be freed. ProtocolManager is
- * in charge of freeing this memory.
- */
-using namespace sc;
-
-Core *Core::sSingleton = NULL;
-
-StartCoreTransaction *StartCoreTransaction::sOngoing = NULL;
-StopCoreTransaction *StopCoreTransaction::sOngoing = NULL;
-
-// Start core: connect initial adapter
-void Core::start() {
- setlocale(LC_ALL, "");
-
- CoreState state = this->get_state();
- if (state != CoreState::kCoreStateIdle) {
- LOG_ERR("start(Core): FAILED - state (%d)", state);
- this->done_start(false);
- return;
- } else if (this->mAdapters.empty()) {
- LOG_ERR("start(Core): FAILED - no adapters");
- this->done_start(false);
- return;
- }
-
- // Connect first adapter
- this->set_state(CoreState::kCoreStateStarting);
- StartCoreTransaction::run(this);
-}
-
-void Core::done_start(bool is_success) {
- if (is_success) {
- LOG_VERB("start(Core): SUCCESS");
- this->set_state(CoreState::kCoreStateReady);
-
- // Launch control message receiving thread
- this->mControlMessageReceiver->start_receiving_thread();
- } else {
- LOG_ERR("start(Core): FAILED - error");
- this->set_state(CoreState::kCoreStateIdle);
- return;
- }
-
- // Execute callback
- start_sc_done(is_success);
-}
-
-// Stop core: disconnect all the adapters
-void Core::stop() {
- CoreState state = this->get_state();
- if (state == CoreState::kCoreStateStarting ||
- state == CoreState::kCoreStateStopping ||
- state == CoreState::kCoreStateIdle) {
- LOG_ERR("done(Core): FAIL - state (%d)", state);
- this->done_stop(false);
- return;
- } else if (this->mAdapters.empty()) {
- LOG_ERR("done(Core): FAIL - no adapters");
- this->done_stop(false);
- return;
- }
-
- // Disconnect all the adapters
- this->set_state(CoreState::kCoreStateStopping);
- StopCoreTransaction::run(this);
-}
-
-void Core::done_stop(bool is_success) {
- if (is_success) {
- LOG_VERB("done(Core): SUCCESS");
- this->set_state(CoreState::kCoreStateIdle);
-
- // Finish control message receiving thread
- this->mControlMessageReceiver->stop_receiving_thread();
- } else {
- LOG_ERR("done(Core): FAIL - error");
- this->set_state(CoreState::kCoreStateReady);
- }
-
- stop_sc_done(is_success);
-}
-
-// Register adapter
-void Core::register_adapter(ServerAdapter *adapter) {
- if (this->get_state() != CoreState::kCoreStateIdle) {
- LOG_ERR("You can register adapter on only idle state!");
- return;
- }
- std::unique_lock lck(this->mAdaptersLock);
- this->mAdapters.push_back(adapter);
-
- adapter->launch_threads();
-}
-
-int Core::send(const void *dataBuffer, uint32_t dataLength, bool is_control) {
- CoreState state = this->get_state();
- if (state != CoreState::kCoreStateReady) {
- LOG_ERR("Core is not started yet, so you cannot send the data");
- return -1;
- }
- uint32_t curr_offset = 0;
- int sent_bytes;
- ProtocolData pd;
- uint8_t *serialized_vector;
- uint32_t packet_size;
-
- /* Update statistics */
- this->mSendRequestSize.set_value(dataLength);
- this->mSendArrivalTime.arrive();
-
- /* Attach the protocol header to the payload */
- ProtocolManager::data_to_protocol_data((const uint8_t *)dataBuffer,
- dataLength, &pd);
-
- /* The serialized_vector buffer is allocated in here */
- packet_size =
- ProtocolManager::serialize(&pd, (const uint8_t *)dataBuffer, curr_offset,
- dataLength, &serialized_vector);
- assert(serialized_vector != NULL && packet_size > 0);
-
- /* Hand over the data to the Protocol Manager */
- sent_bytes =
- ProtocolManager::send_packet(serialized_vector, packet_size, is_control);
- if (unlikely(sent_bytes < 0)) {
- LOG_ERR("Sending stopped(%u/%u) by %d", curr_offset, dataLength,
- sent_bytes);
- }
- return sent_bytes;
-}
-
-int Core::receive(void **pDataBuffer, bool is_control) {
- CoreState state = this->get_state();
- if (state != CoreState::kCoreStateReady) {
- LOG_ERR("Core is not started yet, so you cannot receive data");
- return -1;
- }
- int ret;
- uint32_t packet_size;
- uint8_t *packet;
-
- packet_size = ProtocolManager::recv_packet(&packet, is_control);
- *pDataBuffer = packet;
-
- return packet_size;
-}
-
-// Transactions
-// ----------------------------------------------------------------------------------
-
-// Start Core
-bool StartCoreTransaction::run(Core *caller) {
- if (sOngoing == NULL) {
- sOngoing = new StartCoreTransaction(caller);
- sOngoing->start();
- return true;
- } else {
- LOG_WARN("Already starting core");
- caller->done_start(false);
- return false;
- }
-}
-void StartCoreTransaction::start() {
- // Connect first adapter
- std::unique_lock lck(this->mCaller->mAdaptersLock);
-
- if (this->mCaller->mAdapters.empty()) {
- LOG_ERR("Connecting adapter is failed");
- this->done(false);
- return;
- }
-
- this->mCaller->mAdapters.front()->connect(
- StartCoreTransaction::connect_first_adapter_callback, false);
-}
-
-void StartCoreTransaction::connect_first_adapter_callback(
- ServerAdapter *adapter, bool is_success) {
- if (is_success) {
- // Done transaction
- sOngoing->done(true);
- } else {
- LOG_ERR("Connecting first adapter is failed");
- sOngoing->done(false);
- }
-}
-
-void StartCoreTransaction::done(bool is_success) {
- // Execute StartCore callback
- this->mCaller->done_start(is_success);
-
- // Execute callback
- sOngoing = NULL;
-}
-
-// Stop Core
-bool StopCoreTransaction::run(Core *caller) {
- if (sOngoing == NULL) {
- sOngoing = new StopCoreTransaction(caller);
- sOngoing->start();
- return true;
- } else {
- LOG_WARN("Already stopping core");
- caller->done_stop(false);
- return false;
- }
-}
-void StopCoreTransaction::start() {
- /* Disconnect all adapters */
- std::unique_lock lck(this->mCaller->mAdaptersLock);
-
- /* Get active adapter count */
- this->mAdaptersCount = 0;
- for (std::vector::iterator it =
- this->mCaller->mAdapters.begin();
- it != this->mCaller->mAdapters.end(); it++) {
- ServerAdapter *adapter = *it;
- ServerAdapterState state = adapter->get_state();
- if (state != ServerAdapterState::kDisconnected &&
- state != ServerAdapterState::kDisconnecting) {
- this->mAdaptersCount++;
- }
- }
-
- /* Disconnect only active adapters */
- for (std::vector::iterator it =
- this->mCaller->mAdapters.begin();
- it != this->mCaller->mAdapters.end(); it++) {
- ServerAdapter *adapter = *it;
- ServerAdapterState state = adapter->get_state();
- if (state != ServerAdapterState::kDisconnected &&
- state != ServerAdapterState::kDisconnecting) {
- adapter->disconnect_on_command(
- StopCoreTransaction::disconnect_adapter_callback);
- }
- }
-}
-
-void StopCoreTransaction::disconnect_adapter_callback(ServerAdapter *adapter,
- bool is_success) {
- if (!is_success) {
- if (sOngoing != NULL) {
- LOG_ERR("Disconnecting adapter is failed 2");
- sOngoing->done(false);
- }
- return;
- }
-
- adapter->finish_thread();
-
- /* check if all the adapters are disconnected */
- bool done_disconnect_all = false;
- {
- std::unique_lock lck(sOngoing->mAdaptersCountLock);
- sOngoing->mAdaptersCount--;
- if (sOngoing->mAdaptersCount == 0) {
- done_disconnect_all = true;
- }
- }
-
- /* Done transaction */
- if (done_disconnect_all) {
- sOngoing->done(true);
- }
-}
-
-void StopCoreTransaction::done(bool is_success) {
- this->mCaller->done_stop(is_success);
- sOngoing = NULL;
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/Device.cpp b/subprojects/sc/linux/core/src/Device.cpp
deleted file mode 100644
index 5efd3128..00000000
--- a/subprojects/sc/linux/core/src/Device.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/Device.h"
-
-#include "../inc/ServerAdapter.h"
-
-using namespace sc;
-
-bool Device::turn_on(void) {
- // Check previous state
- DeviceState state = this->get_state();
- if (state == DeviceState::kOn || state == DeviceState::kTurningOn) {
- LOG_WARN("turn_on(%s): FAILED - already on (%d)", this->get_name(), state);
- return false;
- }
-
- // State change
- this->set_state(DeviceState::kTurningOn);
-
- // Turn on the device
- bool res = this->turn_on_impl();
-
- // Result check
- if (!res) {
- LOG_ERR("turn_on(%s): FAILED - impl error", this->get_name());
- this->set_state(DeviceState::kOff);
- } else {
- LOG_DEBUG("turn_on(%s): SUCCESS", this->get_name());
- this->set_state(DeviceState::kOn);
- }
-
- return res;
-}
-
-bool Device::turn_off(void) {
- // Check previous state
- DeviceState state = this->get_state();
- if (state == DeviceState::kOff || state == DeviceState::kTurningOff) {
- LOG_WARN("turn_off(%s): FAILED - already off (%d)", this->get_name(), state);
- return false;
- }
-
- // State change
- this->set_state(DeviceState::kTurningOff);
-
- // Turn off the device
- bool res = this->turn_off_impl();
-
- // Result check
- if (!res) {
- LOG_ERR("turn_off(%s): FAILED - impl error", this->get_name());
- this->set_state(DeviceState::kOn);
- } else {
- LOG_DEBUG("turn_off(%s): SUCCESS", this->get_name());
- this->set_state(DeviceState::kOff);
- }
-
- return res;
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/NetworkMonitor.cpp b/subprojects/sc/linux/core/src/NetworkMonitor.cpp
deleted file mode 100644
index 02899a14..00000000
--- a/subprojects/sc/linux/core/src/NetworkMonitor.cpp
+++ /dev/null
@@ -1,336 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/NetworkMonitor.h"
-
-#include "../inc/NetworkSwitcher.h"
-
-#include "../../configs/ExpConfig.h"
-#include "../../configs/NetworkSwitcherConfig.h"
-
-#include
-
-using namespace sc;
-
-NetworkMonitor *NetworkMonitor::sSingleton = NULL;
-
-void NetworkMonitor::start(void) {
- this->mSwitcherThreadOn = true;
- this->mThread =
- new std::thread(std::bind(&NetworkMonitor::switcher_thread, this));
- this->mThread->detach();
-}
-
-void NetworkMonitor::stop(void) { this->mSwitcherThreadOn = false; }
-
-void NetworkMonitor::switcher_thread(void) {
- int count = 0;
- while (this->mSwitcherThreadOn) {
- // Get statistics
- Stats stats;
- this->get_stats(stats);
-
- // Print statistics
- this->print_stats(stats);
-
- // Check and switch
- // If the switcher is already switching,
- NSState switcher_state = NetworkSwitcher::singleton()->get_state();
- if (switcher_state == NSState::kNSStateReady) {
- this->check_and_decide_switching(stats);
- }
-
- usleep(NETWORK_MONITOR_SLEEP_USECS);
- }
-}
-
-void NetworkMonitor::print_stats(Stats &stats) {
-#ifndef PRINT_NETWORK_MONITOR_STATISTICS
- return;
-#else
- if (Core::singleton()->get_state() != CoreState::kCoreStateReady) {
- return;
- }
-
- const int k_mode_str_length = 20;
- char mode_str[k_mode_str_length];
- switch (this->get_mode()) {
- case NSMode::kNSModeEnergyAware:
- strncpy(mode_str, "Energy", k_mode_str_length);
- break;
- case NSMode::kNSModeLatencyAware:
- strncpy(mode_str, "Latency", k_mode_str_length);
- break;
- case NSMode::kNSModeCapDynamic:
- strncpy(mode_str, "Capacity", k_mode_str_length);
- break;
- default:
- strncpy(mode_str, "Unknown", k_mode_str_length);
- break;
- }
-
- /* Print statistics
- * - EMA(Send Request Size (B))
- * - EMA(Queue Arrival Speed (B/s))
- *
- * - Queue Data Size
- *
- * - Total Bandwidth
- * - EMA(Arrival Time (sec))
- */
- printf("R: %dB (IAT: %3.3fms) => [Q: %dB ] => %dB/s // ON:%dB "
- "OFF: %dB (%d)\n",
- (int)stats.ema_send_request_size, (stats.ema_arrival_time_us / 1000),
- stats.now_queue_data_size, stats.now_total_bandwidth,
- this->get_init_energy_payoff_point(),
- this->get_idle_energy_payoff_point(stats.ema_arrival_time_us),
- this->mDecreasingCheckCount);
-#endif
-}
-
-void NetworkMonitor::get_stats(Stats &stats) {
- // TODO: consider peer's request_speed, now_queue_data_size
- Core *core = Core::singleton();
- SegmentManager *sm = SegmentManager::singleton();
-
- /* Statistics used to print present status */
- this->mQueueArrivalSpeed.set_value(sm->get_send_request_per_sec());
- stats.ema_queue_arrival_speed = this->mQueueArrivalSpeed.get_em_average();
-
- /* Statistics used in CoolSpots Policy */
- stats.now_total_bandwidth = core->get_total_bandwidth();
-
- /* Statistics used in Energy-aware & Latency-aware Policy */
- stats.ema_send_request_size = core->get_ema_send_request_size();
- stats.ema_arrival_time_us = core->get_ema_send_arrival_time();
- stats.now_queue_data_size = sm->get_queue_data_size(kSQSendData) +
- sm->get_queue_data_size(kSQSendControl) +
- sm->get_failed_sending_queue_data_size();
-}
-
-void NetworkMonitor::check_and_decide_switching(Stats &stats) {
- /* Determine Increasing/Decreasing adapter */
- if (this->check_increase_adapter(stats)) {
- /* CoolSpots: Maintain bandwidth when increasing */
- this->mBandwidthWhenIncreasing = stats.now_total_bandwidth;
-
- /* Increase Adapter */
- this->increase_adapter();
- } else if (this->check_decrease_adapter(stats)) {
- /* Decrease Adapter */
- this->decrease_adapter();
- }
-}
-
-int NetworkMonitor::get_init_energy_payoff_point(void) {
- /* 4634053B (4525KB) */
- return (int)((WFD_INIT_ENERGY) /
- (BT_TX_ENERGY_PER_1B - WFD_TX_ENERGY_PER_1B));
-}
-int NetworkMonitor::get_idle_energy_payoff_point(int ema_arrival_time_us) {
- /*
- * 229118B(224KB) at 1sec
- * 6873542B(6712KB) at 30sec
- */
- return (int)((WFD_IDLE_ENERGY_PER_1SEC * ema_arrival_time_us / 1000000) /
- (BT_TX_ENERGY_PER_1B - WFD_TX_ENERGY_PER_1B));
-}
-
-int NetworkMonitor::get_init_latency_payoff_point(void) {
- /* 612787B (598KB) */
- return (int)((WFD_INIT_LATENCY + WFD_TX_LATENCY_1KB_BASIS -
- BT_TX_LATENCY_1KB_BASIS) /
- (BT_TX_LATENCY_PER_1B - WFD_TX_LATENCY_PER_1B));
-}
-
-bool NetworkMonitor::check_increase_adapter(const Stats &stats) {
- /* Check the condition of adapter increase based on switching policy */
- if (!this->is_increaseable()) {
- return false;
- } else if (Core::singleton()->get_state() != kCoreStateReady) {
- return false;
- } else {
- switch (this->get_mode()) {
- case NSMode::kNSModeEnergyAware: {
- /*
- * Energy-aware Policy:
- * - queue data size + EMA(send_request_size) > init energy payoff point
- */
- if (stats.ema_send_request_size + stats.now_queue_data_size >
- this->get_init_energy_payoff_point()) {
- return true;
- } else {
- return false;
- }
- break;
- } /* case NSMode::kNSModeEnergyAware */
- case NSMode::kNSModeLatencyAware: {
- /*
- * Latency-aware Policy:
- * - queue data size + EMA(send_request_size) > init latency payoff point
- */
- if (stats.ema_send_request_size + stats.now_queue_data_size >
- this->get_init_latency_payoff_point()) {
- return true;
- } else {
- return false;
- }
- break;
- } /* case NSMode::kNSModeLatencyAware */
- case NSMode::kNSModeCapDynamic: {
- /*
- * Cap-dynamic Policy:
- */
- LOG_ERR("Unsupported mode!: %d", this->get_mode());
- return false;
- break;
- } /* case NSMode::kNSModeCapDynamic */
- default: {
- LOG_ERR("Unsupported mode!: %d", this->get_mode());
- return false;
- break;
- } /* default */
- } /* switch(this->get_mode()) */
- }
-}
-
-#define CHECK_DECREASING_OK_COUNT 10
-bool NetworkMonitor::check_decrease_adapter(const Stats &stats) {
- /* Check the condition of adapter decrease based on switching policy */
- if (!this->is_decreaseable()) {
- return false;
- } else if (Core::singleton()->get_state() != kCoreStateReady) {
- return false;
- } else {
- switch (this->get_mode()) {
- case NSMode::kNSModeEnergyAware: {
- /*
- * Energy-aware Policy:
- * - if(wfd_idle_energy < wfd_init_energy) EMA(send_request_size)
- * > idle energy payoff point
- * - if(wfd_idle_energy > wfd_init_energy) always false
- */
- bool wfd_off;
- int wfd_idle_energy =
- WFD_IDLE_ENERGY_PER_1SEC * stats.ema_arrival_time_us / 1000000;
- if (WFD_INIT_ENERGY < wfd_idle_energy) {
- wfd_off = true;
- } else {
- int next_request_size = stats.ema_send_request_size;
- int idle_energy_payoff_point =
- get_idle_energy_payoff_point(stats.ema_arrival_time_us);
- if (next_request_size < idle_energy_payoff_point) {
- wfd_off = true;
- } else {
- wfd_off = false;
- }
- }
-
- if (wfd_off) {
- if (stats.ema_send_request_size <
- this->get_idle_energy_payoff_point(stats.ema_arrival_time_us)) {
- this->mDecreasingCheckCount++;
- if (this->mDecreasingCheckCount >= CHECK_DECREASING_OK_COUNT) {
- this->mDecreasingCheckCount = 0;
- return true;
- } else {
- return false;
- }
- } else {
- this->mDecreasingCheckCount = 0;
- return false;
- }
- } else {
- this->mDecreasingCheckCount = 0;
- return false;
- }
- break;
- } /* case NSMode::kNSModeEnergyAware */
- case NSMode::kNSModeLatencyAware: {
- /*
- * Latency-aware Policy:
- * - always false
- */
- return false;
- break;
- } /* case NSMode::kNSModeLatencyAware */
- case NSMode::kNSModeCapDynamic: {
- /*
- * Cap-dynamic Policy:
- */
- LOG_ERR("Unsupported mode!: %d", this->get_mode());
- break;
- } /* case NSMode::kNSModeCapDynamic */
- default: {
- LOG_ERR("Unsupported mode!: %d", this->get_mode());
- return false;
- break;
- }
- } /* switch(this->get_mode()) */
- }
-}
-
-bool NetworkMonitor::is_increaseable(void) {
- /* Check the minimum condition of adapter increase such as adapters' count
- */
- Core *core = Core::singleton();
- int adapter_count = core->get_adapter_count();
- int active_adapter_index = core->get_active_adapter_index();
- return ((adapter_count > 1) && (active_adapter_index < (adapter_count - 1)));
-}
-bool NetworkMonitor::is_decreaseable(void) {
- /* Check the minimum condition of adapter decrease such as adapters' count
- */
- Core *core = Core::singleton();
- int adapter_count = core->get_adapter_count();
- int active_adapter_index = core->get_active_adapter_index();
- return ((adapter_count > 1) && (active_adapter_index > 0));
-}
-
-bool NetworkMonitor::increase_adapter(void) {
- Core *core = Core::singleton();
- if (core->get_adapter_count() == 0) {
- LOG_ERR("No adapter is registered!");
- return false;
- } else if (!this->is_increaseable()) {
- LOG_WARN("Cannot increase adapter!");
- return false;
- }
-
- int prev_index = core->get_active_adapter_index();
- int next_index = prev_index + 1;
-
- return NetworkSwitcher::singleton()->switch_adapters(prev_index, next_index);
-}
-
-bool NetworkMonitor::decrease_adapter(void) {
- Core *core = Core::singleton();
- if (core->get_adapter_count() == 0) {
- LOG_ERR("No adapter is registered!");
- return false;
- } else if (!this->is_decreaseable()) {
- LOG_WARN("Cannot deccrease adapter!");
- return false;
- }
-
- int prev_index = core->get_active_adapter_index();
- int next_index = prev_index - 1;
-
- return NetworkSwitcher::singleton()->switch_adapters(prev_index, next_index);
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/NetworkSwitcher.cpp b/subprojects/sc/linux/core/src/NetworkSwitcher.cpp
deleted file mode 100644
index fcb1ee21..00000000
--- a/subprojects/sc/linux/core/src/NetworkSwitcher.cpp
+++ /dev/null
@@ -1,431 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/NetworkSwitcher.h"
-
-#include "../inc/Core.h"
-#include "../inc/SegmentManager.h"
-#include "../inc/ServerAdapter.h"
-
-#include "../../common/inc/DebugLog.h"
-
-#include "../../configs/ExpConfig.h"
-#include "../../configs/NetworkSwitcherConfig.h"
-
-#include
-#include
-#include
-
-using namespace sc;
-
-NetworkSwitcher *NetworkSwitcher::sSingleton = NULL;
-
-SwitchAdapterTransaction *SwitchAdapterTransaction::sOngoing = NULL;
-ConnectRequestTransaction *ConnectRequestTransaction::sOngoing = NULL;
-ReconnectAdapterTransaction *ReconnectAdapterTransaction::sOngoing = NULL;
-
-void NetworkSwitcher::connect_adapter_by_peer(int adapter_id) {
- NSState state = this->get_state();
- if (state == NSState::kNSStateSwitching) {
- LOG_WARN("connect(adapter %d): FAILED - already switching", adapter_id);
- return;
- }
-
- this->set_state(NSState::kNSStateSwitching);
- ConnectRequestTransaction::run(adapter_id);
-}
-
-void NetworkSwitcher::disconnect_adapter_by_peer(int adapter_id,
- uint32_t last_seq_no_control,
- uint32_t last_seq_no_data) {
- NSState state = this->get_state();
- if (state == NSState::kNSStateSwitching) {
- LOG_WARN("disconnect(adapter %d): FAILED - already switching", adapter_id);
- return;
- }
-
- Core *core = Core::singleton();
- ServerAdapter *adapter = core->find_adapter_by_id(adapter_id);
- if (adapter == NULL) {
- LOG_WARN("Cannot find adapter %d", (int)adapter_id);
- return;
- }
-
- this->set_state(NSState::kNSStateSwitching);
-
- adapter->disconnect_on_peer_command(NULL, last_seq_no_control,
- last_seq_no_data);
-}
-
-void NetworkSwitcher::sleep_adapter_by_peer(int adapter_id) {
- NSState state = this->get_state();
- if (state == NSState::kNSStateSwitching) {
- LOG_VERB("It's now switching. Cannot connect to adapter %d.", adapter_id);
- return;
- }
-
- ServerAdapter *adapter = Core::singleton()->get_adapter(adapter_id);
- if (adapter != NULL) {
- this->set_state(NSState::kNSStateSwitching);
- adapter->sleep(NULL, false);
- this->set_state(NSState::kNSStateReady);
- }
-}
-
-void NetworkSwitcher::wake_up_adapter_by_peer(int adapter_id) {
- NSState state = this->get_state();
- if (state == NSState::kNSStateSwitching) {
- LOG_VERB("It's now switching. Cannot connect to adapter %d.", adapter_id);
- return;
- }
-
- ServerAdapter *adapter = Core::singleton()->get_adapter(adapter_id);
- if (adapter != NULL) {
- this->set_state(NSState::kNSStateSwitching);
- adapter->wake_up(NULL, false);
- this->set_state(NSState::kNSStateReady);
- }
-}
-
-void NetworkSwitcher::reconnect_adapter(ServerAdapter *adapter,
- bool retry_if_already_switching) {
- /* Wait until other adapter is disconnected */
- NSState state = this->get_state();
- if (retry_if_already_switching && state == NSState::kNSStateSwitching) {
- LOG_VERB("It's now switching. Cannot reconnect adapter %s",
- adapter->get_name());
- sleep(1);
- this->reconnect_adapter(adapter, retry_if_already_switching);
- return;
- }
-
- /* Start to reconnect the adapter */
- this->set_state(NSState::kNSStateSwitching);
- ReconnectAdapterTransaction::run(adapter);
-}
-
-bool NetworkSwitcher::switch_adapters(int prev_index, int next_index) {
- // Switch Step 0
- this->set_state(NSState::kNSStateSwitching);
- return SwitchAdapterTransaction::run(prev_index, next_index);
-}
-
-void NetworkSwitcher::done_switch() {
- LOG_VERB("Switch adapter end!");
- NSState state = this->get_state();
- switch (state) {
- case NSState::kNSStateSwitching:
- this->set_state(NSState::kNSStateReady);
- break;
- case NSState::kNSStateReady:
- break;
- }
-}
-
-bool SwitchAdapterTransaction::run(int prev_index, int next_index) {
- if (sOngoing == NULL) {
- sOngoing = new SwitchAdapterTransaction(prev_index, next_index);
- LOG_VERB("Switch (%d->%d): START", prev_index, next_index);
- sOngoing->start();
- return true;
- } else {
- LOG_WARN("Already starting core");
- NetworkSwitcher *switcher = NetworkSwitcher::singleton();
- switcher->done_switch();
- return false;
- }
-}
-
-void SwitchAdapterTransaction::done(bool is_success) {
- if (is_success) {
- LOG_VERB("Switch (%d->%d): SUCCESS", sOngoing->mPrevIndex,
- sOngoing->mNextIndex);
- Core::singleton()->set_active_adapter_index(sOngoing->mNextIndex);
- } else {
- LOG_ERR("Switch (%d->%d): FAILED", sOngoing->mPrevIndex,
- sOngoing->mNextIndex);
- }
- NetworkSwitcher::singleton()->done_switch();
- sOngoing = NULL;
-}
-
-void SwitchAdapterTransaction::start(void) {
- // Switch Step 0, 1-a
- Core *core = Core::singleton();
-
- ServerAdapter *next_adapter = core->get_adapter(this->mNextIndex);
- if (next_adapter == NULL) {
- LOG_ERR("Connecting next adapter is failed");
- this->done(false);
- return;
- }
-
- ServerAdapterState adapter_state = next_adapter->get_state();
- if (adapter_state == ServerAdapterState::kActive) {
- LOG_WARN("Next adapter is already active");
- SwitchAdapterTransaction::connect_next_adapter_callback(NULL, true);
- return;
- } else if (adapter_state == ServerAdapterState::kConnecting ||
- adapter_state == ServerAdapterState::kDisconnecting ||
- adapter_state == ServerAdapterState::kGoingSleeping ||
- adapter_state == ServerAdapterState::kWakingUp) {
- LOG_ERR("Switching is already in progress");
- this->done(false);
- return;
- }
-
- LOG_VERB("Switch (%d->%d): STEP 1. %s Adapter ON",
- sOngoing->mPrevIndex, sOngoing->mNextIndex,
- next_adapter->get_name());
-
-// Connect or wake up the next adapter
-#ifdef EXP_DONT_SEND_CONNECT_CONTROL_MESSAGE
- // For debugging
- next_adapter->connect_or_wake_up(
- SwitchAdapterTransaction::connect_next_adapter_callback, false);
-#else
- next_adapter->connect_or_wake_up(
- SwitchAdapterTransaction::connect_next_adapter_callback, true);
-#endif
-}
-
-void SwitchAdapterTransaction::connect_next_adapter_callback(
- ServerAdapter *adapter, bool is_success) {
- // Switch Step 1-b, 2-a
- Core *core = Core::singleton();
- NetworkSwitcher *switcher = NetworkSwitcher::singleton();
-
- // Check if the connection result is successful
- if (!is_success) {
- LOG_ERR("Connecting next adapter is failed");
- sOngoing->done(false);
- return;
- }
-
- // Get previous adapter
- ServerAdapter *prev_adapter = core->get_adapter(sOngoing->mPrevIndex);
- if (prev_adapter == NULL) {
- LOG_ERR("Disconnecting previous adapter is failed");
- sOngoing->done(false);
- return;
- }
-
- // Check previous adapter's state
- ServerAdapterState adapter_state = prev_adapter->get_state();
- if (adapter_state == ServerAdapterState::kDisconnected) {
- LOG_WARN("Prev adapter is already disconnected");
- // Proceed to Step 4
- sOngoing->done(true);
- return;
- } else if (adapter_state == ServerAdapterState::kSleeping ||
- adapter_state == ServerAdapterState::kGoingSleeping) {
- LOG_WARN("Prev adapter is already sleeping or going to sleeping");
- // Proceed to Step 3-a
- sOngoing->sleep_prev_adapter_callback(NULL, true);
- } else if (adapter_state == ServerAdapterState::kConnecting ||
- adapter_state == ServerAdapterState::kDisconnecting ||
- adapter_state == ServerAdapterState::kWakingUp) {
- // Failure
- LOG_ERR("Switching is already in progress");
- sOngoing->done(false);
- return;
- }
-
- LOG_VERB("Switch (%d->%d): STEP 2. %s Adapter SLEEP",
- sOngoing->mPrevIndex, sOngoing->mNextIndex,
- prev_adapter->get_name());
-
- // Disconnect or sleep previous adapter
- // TODO: Actually, it needs sleep request. For now, since sleep does not
- // support ACK message, sleep request message makes out-of-order of sleep()
- // and disconnect().
- prev_adapter->sleep(SwitchAdapterTransaction::sleep_prev_adapter_callback,
- false);
-}
-
-void SwitchAdapterTransaction::sleep_prev_adapter_callback(
- ServerAdapter *adapter, bool is_success) {
- // Switch Step 2-b, 3-a
- Core *core = Core::singleton();
- NetworkSwitcher *switcher = NetworkSwitcher::singleton();
- if (!is_success) {
- LOG_ERR("Sleeping next adapter is failed");
- sOngoing->done(false);
- return;
- }
-
- ServerAdapter *prev_adapter = core->get_adapter(sOngoing->mPrevIndex);
- if (prev_adapter == NULL) {
- LOG_ERR("Sleeping previous adapter is failed");
- sOngoing->done(false);
- return;
- }
-
- ServerAdapterState adapter_state = prev_adapter->get_state();
- if (adapter_state == ServerAdapterState::kDisconnected) {
- // Proceed to Step 4
- LOG_WARN("Prev adapter is already disconnected");
- sOngoing->done(true);
- return;
- } else if (adapter_state == ServerAdapterState::kGoingSleeping) {
- // Wait until the adapter become sleeping state
- LOG_VERB("Wait for going to sleeping");
- do {
- adapter_state = prev_adapter->get_state();
- ::sleep(1);
- } while (adapter_state != ServerAdapterState::kSleeping);
- } else if (adapter_state == ServerAdapterState::kConnecting ||
- adapter_state == ServerAdapterState::kDisconnecting ||
- adapter_state == ServerAdapterState::kWakingUp) {
- // Failure
- LOG_ERR("Switching is already in progress");
- sOngoing->done(false);
- return;
- }
-
- LOG_VERB("Switch (%d->%d): STEP 3. %s Adapter OFF",
- sOngoing->mPrevIndex, sOngoing->mNextIndex,
- prev_adapter->get_name());
-
- prev_adapter->disconnect_on_command(
- SwitchAdapterTransaction::disconnect_prev_adapter_callback);
-}
-
-void SwitchAdapterTransaction::disconnect_prev_adapter_callback(
- ServerAdapter *adapter, bool is_success) {
- // Switch Step 3-b, 4
- if (!is_success) {
- LOG_ERR("Disconnecting prev adapter is failed");
- sOngoing->done(false);
- return;
- }
-
- // Switching adapter is successfully done!
- sOngoing->done(true);
-}
-
-bool ConnectRequestTransaction::run(int adapter_id) {
- if (sOngoing == NULL) {
- sOngoing = new ConnectRequestTransaction(adapter_id);
- sOngoing->start();
- return true;
- } else {
- LOG_WARN("Already starting core");
- NetworkSwitcher *switcher = NetworkSwitcher::singleton();
- switcher->done_switch();
- return false;
- }
-}
-
-void ConnectRequestTransaction::done() {
- NetworkSwitcher *switcher = NetworkSwitcher::singleton();
- switcher->done_switch();
- sOngoing = NULL;
-}
-
-// Connect Request
-bool ConnectRequestTransaction::start() {
- // Connect requested adapter
- ServerAdapter *adapter =
- Core::singleton()->find_adapter_by_id(this->mAdapterId);
- if (adapter == NULL) {
- LOG_ERR("Connecting requested adapter is failed");
- this->done();
- return false;
- }
- adapter->connect(ConnectRequestTransaction::connect_callback, false);
- return true;
-}
-
-void ConnectRequestTransaction::connect_callback(ServerAdapter *adapter,
- bool is_success) {
- if (!is_success) {
- LOG_ERR("Connecting requested adapter is failed");
- sOngoing->done();
- return;
- }
- LOG_VERB("Connecting requested adapter is done");
- sOngoing->done();
-}
-
-bool ReconnectAdapterTransaction::run(ServerAdapter *targetAdapter) {
- if (sOngoing == NULL) {
- sOngoing = new ReconnectAdapterTransaction(targetAdapter);
- sOngoing->start();
- return true;
- } else {
- LOG_WARN("Already starting core");
- NetworkSwitcher *switcher = NetworkSwitcher::singleton();
- switcher->done_switch();
- return false;
- }
-}
-
-void ReconnectAdapterTransaction::done(bool require_restart) {
- sOngoing = NULL;
- if (require_restart) {
- ReconnectAdapterTransaction::start();
- } else {
- sleep(1);
-
- NetworkSwitcher *switcher = NetworkSwitcher::singleton();
- switcher->done_switch();
- }
-}
-
-// Reconnect Adapter
-bool ReconnectAdapterTransaction::start() {
- // disconnect adapter
- if (this->mTargetAdapter == NULL) {
- LOG_ERR("Reconnecting adapter is failed: retry");
- this->done(true);
- return false;
- }
- this->mTargetAdapter->disconnect_on_failure(
- ReconnectAdapterTransaction::disconnect_callback);
- return true;
-}
-
-void ReconnectAdapterTransaction::disconnect_callback(ServerAdapter *adapter,
- bool is_success) {
- if (!is_success) {
- LOG_ERR("Reconnecting adapter is failed: retry");
- sOngoing->done(true);
- return;
- }
- // connect adapter
- if (sOngoing->mTargetAdapter == NULL) {
- LOG_ERR("Reconnecting adapter is failed: retry");
- sOngoing->done(true);
- return;
- }
- sOngoing->mTargetAdapter->connect(
- ReconnectAdapterTransaction::disconnect_callback, false);
-}
-
-void ReconnectAdapterTransaction::connect_callback(ServerAdapter *adapter,
- bool is_success) {
- if (!is_success) {
- LOG_ERR("Reconnecting adapter is failed 6: retry");
- sOngoing->done(true);
- return;
- }
- LOG_VERB("Reconnecting adapter is done");
- NetworkSwitcher::singleton()->done_switch();
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/P2PServer.cpp b/subprojects/sc/linux/core/src/P2PServer.cpp
deleted file mode 100644
index 009d972b..00000000
--- a/subprojects/sc/linux/core/src/P2PServer.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/P2PServer.h"
-
-#include "../../common/inc/DebugLog.h"
-
-using namespace sc;
-
-bool P2PServer::allow_discover(void) {
- // Check previous state
- P2PServerState state = this->get_state();
- if (state == P2PServerState::kAllowed) {
- LOG_WARN("allow_discover(%s): FAILED - already allowed (%d)", this->get_name(), state);
- return false;
- }
-
- // Allow discover
- bool res = this->allow_discover_impl();
-
- // Check result and change state
- if (!res) {
- LOG_ERR("allow_discover(%s): FAILED - impl error", this->get_name());
- this->set_state(P2PServerState::kDisallowed);
- } else {
- LOG_DEBUG("allow_discover(%s): SUCCESS", this->get_name());
- this->set_state(P2PServerState::kAllowed);
- }
- return res;
-}
-
-bool P2PServer::disallow_discover(void) {
- // Check previous state
- P2PServerState state = this->get_state();
- if (state == P2PServerState::kDisallowed) {
- LOG_WARN("disallow_discover(%s): FAILED - already disallowed(%d)", this->get_name(), state);
- return false;
- }
-
- // Disallow discover
- bool res = this->disallow_discover_impl();
-
- // Check result and change state
- if (!res) {
- LOG_ERR("disallow_discover(%s): FAILED - impl error", this->get_name());
- this->set_state(P2PServerState::kAllowed);
- } else {
- LOG_DEBUG("disallow_discover(%s): SUCCESS", this->get_name());
- this->set_state(P2PServerState::kDisallowed);
- }
- return res;
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/ProtocolManager.cpp b/subprojects/sc/linux/core/src/ProtocolManager.cpp
deleted file mode 100644
index fa5fe0ba..00000000
--- a/subprojects/sc/linux/core/src/ProtocolManager.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/ProtocolManager.h"
-
-#include "../inc/SegmentManager.h"
-
-#include "../../common/inc/DebugLog.h"
-
-#include
-#include
-#include
-
-using namespace sc;
-
-uint16_t ProtocolManager::sPacketId = 1;
-
-void ProtocolManager::data_to_protocol_data(const uint8_t *dat, uint32_t size,
- ProtocolData *ret_pd) {
- assert(ret_pd != NULL);
- assert(size <= UINT32_MAX);
- ret_pd->id = sPacketId++;
- ret_pd->len = size;
- ret_pd->data = dat;
-
-#ifdef COMMUNICATOR_UNIT_TEST
- LOG_VERB("%d\t%u\t[%s]", ret_pd->id, ret_pd->len, ret_pd->data);
-#endif /* COMMUNICATOR_UNIT_TEST */
-}
-
-inline void ProtocolManager::serialize_header(ProtocolData *pd,
- uint8_t *vec_ptr) {
- uint32_t vec_offset = 0;
- uint16_t net_id = htons(pd->id);
- uint32_t net_len = htonl(pd->len);
-
- memcpy(vec_ptr + vec_offset, &net_id, sizeof(uint16_t));
- vec_offset += sizeof(uint16_t);
- memcpy(vec_ptr + vec_offset, &net_len, sizeof(uint32_t));
- vec_offset += sizeof(uint32_t);
-}
-
-inline void ProtocolManager::serialize_data(const uint8_t *dat_buf,
- uint32_t len, uint8_t *vec_ptr) {
- memcpy(vec_ptr, dat_buf, (size_t)len);
-}
-
-uint32_t ProtocolManager::serialize(ProtocolData *pd, const uint8_t *buf,
- uint32_t offset, uint32_t payload_size,
- uint8_t **ret_vector) {
- uint8_t *serialized_vector;
- uint32_t vector_size;
- uint32_t data_offset;
-
- data_offset = kProtHeaderSize;
- vector_size = data_offset + payload_size;
-
- serialized_vector =
- reinterpret_cast(calloc((size_t)vector_size, sizeof(uint8_t)));
-
- serialize_header(pd, serialized_vector);
- serialize_data(buf + offset, payload_size, serialized_vector + data_offset);
-
-#ifdef COMMUNICATOR_UNIT_TEST
- LOG_VERB("%p\t(%u)\tFrom %p~%p(%u)", serialized_vector, vector_size,
- buf + offset, buf + offset + payload_size - 1, payload_size);
-
- uint8_t buf_test = *(serialized_vector);
- buf_test = *(serialized_vector + vector_size - 1);
- if (buf != NULL) {
- buf_test = *(buf);
- buf_test = *(buf + offset + payload_size - 1);
- }
- LOG_VERB("Done");
-#endif /* COMMUNICATOR_UNIT_TEST */
-
- *ret_vector = serialized_vector;
-
- return vector_size;
-}
-
-uint32_t ProtocolManager::parse_header(uint8_t *serialized,
- ProtocolData *ret_pd) {
- uint32_t vec_offset = 0;
- uint16_t net_id;
- uint32_t net_len;
-
- memcpy(&net_id, serialized + vec_offset, sizeof(uint16_t));
- vec_offset += sizeof(uint16_t);
- ret_pd->id = ntohs(net_id);
-
- memcpy(&net_len, serialized + vec_offset, sizeof(uint32_t));
- vec_offset += sizeof(uint32_t);
- ret_pd->len = ntohl(net_len);
-
- return vec_offset;
-}
-
-int ProtocolManager::send_packet(uint8_t *serialized, uint32_t packet_size, bool is_control) {
- SegmentManager *sm = SegmentManager::singleton();
-#ifdef COMMUNICATOR_UNIT_TEST
- uint8_t buf_test = *serialized;
- buf_test = *(serialized + packet_size - 1);
- free(serialized);
-#endif
- // Hand over the data to the segment manager
- return sm->send_to_segment_manager(serialized, packet_size, is_control);
-}
-
-uint32_t ProtocolManager::recv_packet(uint8_t **buf, bool is_control) {
- ProtocolData pd = {0, 0, NULL};
- SegmentManager *sm = SegmentManager::singleton();
- uint8_t *p_data_buf =
- sm->recv_from_segment_manager(reinterpret_cast(&pd), is_control);
- assert(pd.len == 0 || p_data_buf != NULL);
-
- *buf = p_data_buf;
-
- return pd.len;
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/ReceiverThread.cpp b/subprojects/sc/linux/core/src/ReceiverThread.cpp
deleted file mode 100644
index c693ff95..00000000
--- a/subprojects/sc/linux/core/src/ReceiverThread.cpp
+++ /dev/null
@@ -1,139 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/ReceiverThread.h"
-
-#include "../../common/inc/DebugLog.h"
-#include "../inc/NetworkSwitcher.h"
-#include "../inc/SegmentManager.h"
-#include "../inc/ServerAdapter.h"
-
-#include
-#include
-#include
-
-#include
-#include
-#include
-
-using namespace sc;
-
-void ReceiverThread::run(void) {
- // Thread start
- LOG_ADAPTER_THREAD_LAUNCH(this->mAdapter->get_name(), "Receiver");
-
- // Initialize state
- this->set_is_thread_running(true);
- this->set_is_loop_enabled(false);
-
- // Execute Thread loop
- while (this->is_thread_running()) {
- // Wait until enable loop (Initially, the loop is disabled)
- this->wait_until_enable_loop();
-
- // Set state before receiver loop
- this->set_is_loop_ends(false);
-
- // Execute receiver loop
- LOG_DEBUG("%s: Receiver loop starts", this->mAdapter->get_name());
- this->receiver_loop();
- LOG_DEBUG("%s: Receiver loop ends", this->mAdapter->get_name());
-
- // Set state after receiver loop
- this->set_is_loop_enabled(false);
- this->set_is_loop_ends(true);
-
-// Reconnect the adapter if it is disconnected on failure
-#ifdef EXP_RECONNECT_ADAPTER_ENABLED
- if (!this->mAdapter->is_disconnecting_on_purpose()) {
- NetworkSwitcher::singleton()->reconnect_adapter(this->mAdapter, true);
- }
-#endif
- }
-
- // Set state for thread end
- this->set_is_thread_running(false);
-
- // Thread end
- LOG_ADAPTER_THREAD_FINISH(this->mAdapter->get_name(), "Receiver");
- this->mThread = NULL;
-}
-
-void ReceiverThread::receiver_loop(void) {
- while (this->is_loop_enabled()) {
- SegmentManager *sm = SegmentManager::singleton();
- Segment *segment_to_receive = sm->get_free_segment();
- void *buf = reinterpret_cast(segment_to_receive->data);
- int len = kSegSize + kSegHeaderSize;
-
-#ifdef VERBOSE_SERVER_ADAPTER_RECEIVING
- LOG_DEBUG("%s: Receiving...", this->get_name());
-#endif
- int res = this->mAdapter->receive(buf, len);
- if (res == -999) {
- continue;
- } else if (errno == EINTR) {
- continue;
- } else if (errno == EAGAIN || errno == EWOULDBLOCK ||
- errno == EINPROGRESS) {
- // Receive timeout
- continue;
- } else if (res != len) {
- if (!this->mAdapter->is_disconnecting_on_purpose()) {
- LOG_WARN("Receiving failed at %s (%d / %d; %s)",
- this->mAdapter->get_name(), errno, res, strerror(errno));
- } else {
- LOG_DEBUG("Receiving broken at %s (%d / %d; %s)",
- this->mAdapter->get_name(), errno, res, strerror(errno));
- }
- break;
- }
-
- uint32_t net_seq_no, net_len, net_flag;
- memcpy(&net_seq_no, buf, sizeof(uint32_t));
- memcpy(&net_len, (reinterpret_cast(buf) + 4), sizeof(uint32_t));
- memcpy(&net_flag, (reinterpret_cast(buf) + 8), sizeof(uint32_t));
- segment_to_receive->seq_no = ntohl(net_seq_no);
- segment_to_receive->len = ntohl(net_len);
- segment_to_receive->flag = ntohl(net_flag);
-
- bool is_control = ((segment_to_receive->flag & kSegFlagControl) != 0);
-
- if (is_control) {
-#ifdef VERBOSE_ENQUEUE_RECV
- LOG_DEBUG("%s: Receive Segment (type=Ctrl, seqno=%d, len=%d, flag=%d)",
- this->mAdapter->get_name(), segment_to_receive->seq_no,
- segment_to_receive->len, segment_to_receive->flag);
-#endif
- sm->enqueue(kSQRecvControl, segment_to_receive);
- } else {
-#ifdef VERBOSE_ENQUEUE_RECV
- LOG_DEBUG("%s: Receive Segment (type=Data, seqno=%d, len=%d, flag=%d)",
- this->mAdapter->get_name(), segment_to_receive->seq_no,
- segment_to_receive->len, segment_to_receive->flag);
-#endif
- sm->enqueue(kSQRecvData, segment_to_receive);
- }
- segment_to_receive = sm->get_free_segment();
-
-#ifdef VERBOSE_SERVER_ADAPTER_RECEIVING
- LOG_DEBUG("%s: Received: %d", this->get_name(), res);
-#endif
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/SegmentManager.cpp b/subprojects/sc/linux/core/src/SegmentManager.cpp
deleted file mode 100644
index 6f5371b4..00000000
--- a/subprojects/sc/linux/core/src/SegmentManager.cpp
+++ /dev/null
@@ -1,398 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/SegmentManager.h"
-
-#include "../inc/ProtocolManager.h"
-
-#include "../../common/inc/DebugLog.h"
-
-#include "../../configs/ExpConfig.h"
-
-#include
-#include
-#include
-#include
-
-using namespace sc;
-
-/* Singleton */
-SegmentManager *SegmentManager::sSingleton = NULL;
-
-uint32_t SegmentManager::get_next_seq_no(SegSeqNumType seq_num_type,
- uint32_t num_segments) {
- uint32_t res;
- this->mNextSeqNoLock[seq_num_type].lock();
- res = this->mNextSeqNo[seq_num_type];
- this->mNextSeqNo[seq_num_type] += num_segments;
- this->mNextSeqNoLock[seq_num_type].unlock();
- return res;
-}
-
-void SegmentManager::serialize_segment_header(Segment *seg) {
- uint32_t net_seq_no = htonl(seg->seq_no);
- uint32_t net_len = htonl(seg->len);
- uint32_t net_flag = htonl(seg->flag);
- memcpy(seg->data, &net_seq_no, sizeof(uint32_t));
- memcpy(seg->data + 4, &net_len, sizeof(uint32_t));
- memcpy(seg->data + 8, &net_flag, sizeof(uint32_t));
-}
-
-int SegmentManager::send_to_segment_manager(uint8_t *data, size_t len,
- bool is_control) {
- assert(data != NULL && len > 0);
-
- uint32_t offset = 0;
- uint32_t num_of_segments = ((len + kSegSize - 1) / kSegSize);
- assert((len + kSegSize - 1) / kSegSize < UINT32_MAX);
-
- SegSeqNumType seq_num_type = (is_control) ? kSNControl : kSNData;
-
- /* Reserve sequence numbers to this thread */
- uint32_t allocated_seq_no = get_next_seq_no(seq_num_type, num_of_segments);
-
- int seg_idx;
- for (seg_idx = 0; seg_idx < num_of_segments; seg_idx++) {
- uint32_t seg_len = (len - offset < kSegSize) ? len - offset : kSegSize;
- Segment *seg = this->get_free_segment();
-
- /* Set segment sequence number */
- seg->seq_no = allocated_seq_no++;
-
- /* Set segment length */
- seg->len = seg_len;
-
- /* Set segment MF flag and/or control segment flag */
- uint32_t flag = 0;
- if (offset + seg_len < len)
- flag = flag | kSegFlagMF;
- if (is_control)
- flag = flag | kSegFlagControl;
- seg->flag = flag;
-
- /* Set segment header to data */
- this->serialize_segment_header(seg);
-
- /* Set segment data */
- memcpy(seg->data + kSegHeaderSize, data + offset, seg_len);
- offset += seg_len;
-
- if (is_control) {
-#ifdef VERBOSE_ENQUEUE_SEND
- LOG_DEBUG("Enqueue(control) IsControl: %d / SeqNo: %lu / len: %d",
- is_control, seg->seq_no, len);
-#endif
- this->enqueue(kSQSendControl, seg);
- } else {
-#ifdef VERBOSE_ENQUEUE_SEND
- LOG_DEBUG("Enqueue(data) IsControl: %d / SeqNo: %lu", is_control,
- seg->seq_no);
-#endif
- this->enqueue(kSQSendData, seg);
- }
- }
-
- return 0;
-}
-
-uint8_t *SegmentManager::recv_from_segment_manager(void *proc_data_handle,
- bool is_control) {
- assert(proc_data_handle != NULL);
-
- ProtocolData *pd = reinterpret_cast(proc_data_handle);
- uint8_t *serialized = NULL;
- uint16_t offset = 0;
- size_t data_size = 0;
- bool cont = false;
- bool dequeued = false;
- Segment *seg;
-
- while (dequeued == false) {
- if (is_control) {
- seg = dequeue(kDeqRecvControl);
- } else {
- seg = dequeue(kDeqRecvData);
- }
- if (seg) {
- dequeued = true;
- }
- }
-
- ProtocolManager::parse_header(&(seg->data[kSegHeaderSize]), pd);
-
- if (unlikely(pd->len == 0))
- return NULL;
-
- serialized = reinterpret_cast(calloc(pd->len, sizeof(uint8_t)));
-
- data_size = seg->len - kProtHeaderSize;
- memcpy(serialized + offset, &(seg->data[kSegHeaderSize]) + kProtHeaderSize,
- data_size);
- offset += data_size;
-
- cont = ((seg->flag & kSegFlagMF) != 0);
-
- free_segment(seg);
-
- while (cont) {
- if (is_control) {
- seg = dequeue(kDeqRecvControl);
- } else {
- seg = dequeue(kDeqRecvData);
- }
- data_size = seg->len;
- memcpy(serialized + offset, &(seg->data[kSegHeaderSize]), data_size);
- cont = ((seg->flag & kSegFlagMF) != 0);
- offset += data_size;
- free_segment(seg);
- }
-
- return serialized;
-}
-
-SegDequeueType
-SegmentManager::queue_type_to_dequeue_type(SegQueueType queue_type) {
- SegDequeueType dequeue_type;
- switch (queue_type) {
- case SegQueueType::kSQRecvControl:
- dequeue_type = SegDequeueType::kDeqRecvControl;
- break;
- case SegQueueType::kSQRecvData:
- dequeue_type = SegDequeueType::kDeqRecvData;
- break;
- case SegQueueType::kSQSendControl:
- case SegQueueType::kSQSendData:
- dequeue_type = SegDequeueType::kDeqSendControlData;
- break;
- default:
- LOG_ERR("Unknown queue type: %d", queue_type);
- dequeue_type = SegDequeueType::kDeqUnknown;
- break;
- }
- return dequeue_type;
-}
-
-/*
- * This function is the end of the sending logic.
- * It enqeueus the data to the sending queue in order with the sequence number.
- */
-void SegmentManager::enqueue(SegQueueType queue_type, Segment *seg) {
- assert(queue_type < kNumSQ);
- SegDequeueType dequeue_type = queue_type_to_dequeue_type(queue_type);
- assert(dequeue_type < kNumDeq);
-
- // Dequeue Lock
- std::unique_lock dequeue_lock(this->mDequeueLock[dequeue_type]);
-
- // Enqueue the segment to the corresponding segment queue
- // If the segment has already been enqueued, the segment can be ignored.
- bool continuous_segment_enqueued =
- this->mSegmentQueues[queue_type].enqueue(seg);
-
- // If enqueue is successful, wake up threads that wait for dequeue
- if (continuous_segment_enqueued) {
- this->wake_up_dequeue_waiting(dequeue_type);
- }
-
- // Update statistics
- if (queue_type == kSQSendControl || queue_type == kSQSendData) {
- this->mSendRequest.add(SEGMENT_DATA_SIZE);
- }
-
- // Check if all the remaining segments are received
- // It is used for the pre-condition of disconnection
- this->check_receiving_done();
-}
-
-void SegmentManager::wait_for_dequeue_locked(
- SegDequeueType dequeue_type, std::unique_lock &dequeue_lock) {
- /* If queue is empty, wait until some segment is enqueued */
- bool is_wait_required = false;
- switch (dequeue_type) {
- case SegDequeueType::kDeqSendControlData: {
- int send_control_queue_length =
- this->mSegmentQueues[SegQueueType::kSQSendControl].get_queue_length();
- int send_data_queue_length =
- this->mSegmentQueues[SegQueueType::kSQSendData].get_queue_length();
- is_wait_required =
- ((send_control_queue_length == 0) && (send_data_queue_length == 0));
- break;
- }
- case SegDequeueType::kDeqRecvControl: {
- int recv_control_queue_length =
- this->mSegmentQueues[SegQueueType::kSQRecvControl].get_queue_length();
- is_wait_required = (recv_control_queue_length == 0);
- break;
- }
- case SegDequeueType::kDeqRecvData: {
- int recv_data_queue_length =
- this->mSegmentQueues[SegQueueType::kSQRecvData].get_queue_length();
- is_wait_required = (recv_data_queue_length == 0);
- break;
- }
- }
- if (is_wait_required) {
-#ifdef VERBOSE_SEGMENT_QUEUE_WAITING
- if (dequeue_type == kDeqSendControlData) {
- LOG_DEBUG("sending queue is empty. wait for another");
- } else {
- LOG_DEBUG("receiving queue is empty. wait for another");
- }
-#endif
-
- this->mDequeueCond[dequeue_type].wait(dequeue_lock);
- }
-}
-
-SegQueueType
-SegmentManager::get_target_queue_type(SegDequeueType dequeue_type) {
- SegQueueType target_queue_type = SegQueueType::kSQUnknown;
- switch (dequeue_type) {
- case SegDequeueType::kDeqSendControlData: {
- if (this->mSegmentQueues[SegQueueType::kSQSendControl].get_queue_length() !=
- 0) {
- // Priority 1. Dequeue send control queue
- target_queue_type = kSQSendControl;
- } else if (this->mSegmentQueues[SegQueueType::kSQSendData]
- .get_queue_length() != 0) {
- // Priority 2. Dequeue send data queue
- target_queue_type = kSQSendData;
- } else {
- // No segments in both two send queues
- break;
- }
- break;
- }
- case SegDequeueType::kDeqRecvControl: {
- target_queue_type = kSQRecvControl;
- break;
- }
- case SegDequeueType::kDeqRecvData: {
- target_queue_type = kSQRecvData;
- break;
- }
- default: {
- LOG_ERR("Invalid dequeue type (dequeue=%d)", dequeue_type);
- break;
- }
- }
- return target_queue_type;
-}
-
-/*
- * Dequeue the segment from the queue.
- * Note that this function is used for sending & receiving queue.
- */
-Segment *SegmentManager::dequeue(SegDequeueType dequeue_type) {
- assert(dequeue_type < kNumDeq);
- std::unique_lock dequeue_lock(this->mDequeueLock[dequeue_type]);
-
- // Wait for dequeue
- this->wait_for_dequeue_locked(dequeue_type, dequeue_lock);
-
- // Dequeue from queue
- SegQueueType target_queue_type = get_target_queue_type(dequeue_type);
- if (target_queue_type >= kNumSQ) {
- // It is not failure situation.
- return NULL;
- }
-
- // Check queue type
- if (target_queue_type >= SegQueueType::kNumSQ) {
- LOG_ERR("Dequeue failed: invalid queue type (dequeue=%d, queue=%d)",
- dequeue_type, target_queue_type);
- return NULL;
- }
-
- // Check the dequeued segment
- Segment *segment_dequeued = this->mSegmentQueues[target_queue_type].dequeue();
- if (segment_dequeued == NULL) {
- LOG_DEBUG("Dequeue interrupted: empty queue (queue=%d, dequeue=%d)",
- target_queue_type, dequeue_type);
- }
-
- return segment_dequeued;
-}
-
-/* This function returns a free segment from the list of free segments.
- * If there is no one available, allocate new one
- */
-Segment *SegmentManager::get_free_segment(void) {
- std::unique_lock lck(this->mFreeSegmentListLock);
- Segment *ret = NULL;
- if (this->mFreeSegmentListSize == 0) {
- ret = reinterpret_cast(calloc(1, sizeof(Segment)));
- } else {
- ret = this->mFreeList.front();
- this->mFreeList.pop_front();
- this->mFreeSegmentListSize--;
- }
-
- ret->seq_no = 0;
- ret->len = 0;
- ret->flag = 0;
- assert(ret != NULL);
- return ret;
-}
-
-void SegmentManager::release_segment_from_free_list(uint32_t threshold) {
- while (this->mFreeSegmentListSize > threshold) {
- Segment *to_free = this->mFreeList.front();
- this->mFreeList.pop_front();
- free(to_free);
- this->mFreeSegmentListSize--;
- }
-}
-
-/* This function releases the segment which is not further used.
- */
-void SegmentManager::free_segment(Segment *seg) {
- std::unique_lock lck(this->mFreeSegmentListLock);
- this->mFreeList.push_front(seg);
- this->mFreeSegmentListSize++;
-
- // If the free list is big enough, release the half elements of the list
- if (unlikely(this->mFreeSegmentListSize > kSegFreeThreshold)) {
- release_segment_from_free_list(kSegFreeThreshold / 2);
- }
-}
-
-void SegmentManager::free_segment_all(void) {
- std::unique_lock lck(this->mFreeSegmentListLock);
- release_segment_from_free_list(0);
-}
-
-void SegmentManager::failed_sending(Segment *seg) {
- std::unique_lock lck(this->mSendFailQueueLock);
- this->mSendFailQueue.push_back(seg);
- this->mFailedSendingQueueLength.increase();
-}
-
-Segment *SegmentManager::get_failed_sending(void) {
- std::unique_lock lck(this->mSendFailQueueLock);
- if (this->mSendFailQueue.size() == 0)
- return NULL;
-
- Segment *res = this->mSendFailQueue.front();
- this->mSendFailQueue.pop_front();
- this->mFailedSendingQueueLength.decrease();
-
- return res;
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/SenderThread.cpp b/subprojects/sc/linux/core/src/SenderThread.cpp
deleted file mode 100644
index 40663f0c..00000000
--- a/subprojects/sc/linux/core/src/SenderThread.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/SenderThread.h"
-
-#include "../../common/inc/DebugLog.h"
-#include "../inc/NetworkSwitcher.h"
-#include "../inc/SegmentManager.h"
-#include "../inc/ServerAdapter.h"
-
-#include
-#include
-#include
-
-#include
-#include
-
-using namespace sc;
-
-void SenderThread::run(void) {
- // Thread start
- LOG_ADAPTER_THREAD_LAUNCH(this->mAdapter->get_name(), "Sender");
-
- // Initialize state
- this->set_is_thread_running(true);
- this->set_is_loop_enabled(false);
- this->set_is_loop_paused(false);
-
- // Execute Thread loop
- while (this->is_thread_running()) {
- // Wait until enable loop (Initially, the loop is disabled)
- this->wait_until_enable_loop();
-
- // Set state before sender loop
- this->set_is_loop_ends(false);
-
- // Execute sender loop
- LOG_DEBUG("%s: Sender loop starts", this->mAdapter->get_name());
- this->sender_loop();
- LOG_DEBUG("%s: Sender loop ends", this->mAdapter->get_name());
-
- // Set state after sender loop
- this->set_is_loop_enabled(false);
- this->set_is_loop_paused(false);
- this->set_is_loop_ends(true);
-
-// Reconnect the adapter if it is disconnected on failure
-#ifdef EXP_RECONNECT_ADAPTER_ENABLED
- if (!this->mAdapter->is_disconnecting_on_purpose()) {
- NetworkSwitcher::singleton()->reconnect_adapter(this->mAdapter, true);
- }
-#endif
- }
-
- // Set state for thread end
- this->set_is_thread_running(false);
-
- // Thread end
- LOG_ADAPTER_THREAD_FINISH(this->mAdapter->get_name(), "Sender");
- this->mThread = NULL;
-}
-
-void SenderThread::sender_loop(void) {
- while (this->is_loop_enabled()) {
- SegmentManager *sm = SegmentManager::singleton();
- Segment *segment_to_send = NULL;
-
- // If loop is paused, wait until resume loop
- do {
- if (!this->is_loop_paused()) {
- break;
- }
- LOG_VERB("Sender thread suspended: %s", this->mAdapter->get_name());
- this->mAdapter->set_state(ServerAdapterState::kSleeping);
-
- // Wait until resume loop
- this->wait_until_resume_loop();
-
- int adapterState = this->mAdapter->get_state();
- if (adapterState != ServerAdapterState::kDisconnecting &&
- adapterState != ServerAdapterState::kDisconnected) {
- this->mAdapter->set_state(ServerAdapterState::kActive);
- }
- } while (true);
-
- // Dequeue from a queue (one of the three queues)
- // Priority 1. Failed sending queue
- segment_to_send = sm->get_failed_sending();
-#if defined(VERBOSE_DEQUEUE_SEND_CONTROL) || defined(VERBOSE_DEQUEUE_SEND_DATA)
- bool is_get_failed_segment = (segment_to_send != NULL);
-#endif
-
- // Priority 2. Send control queue
- // Priority 3. Send data queue
- if (likely(segment_to_send == NULL)) {
- segment_to_send = sm->dequeue(kDeqSendControlData);
- }
-
- if (unlikely(segment_to_send == NULL)) {
- // Nothing to send.
- // SegmentManager::wake_up_dequeue_waiting() function may make this case
- continue;
- }
-
- bool is_control = ((segment_to_send->flag & kSegFlagControl) != 0);
-#ifdef VERBOSE_DEQUEUE_SEND_CONTROL
- if (is_control) {
- LOG_DEBUG("%s: Send %s Segment (type=Ctrl, seqno=%d, len=%d)",
- this->mAdapter->get_name(),
- (is_get_failed_segment ? "Failed" : "Normal"),
- segment_to_send->seq_no, (int)segment_to_send->len);
- }
-#endif
-#ifdef VERBOSE_DEQUEUE_SEND_DATA
- if (!is_control) {
- LOG_DEBUG("%s: Send %s Segment (type=Data, seqno=%d)",
- this->mAdapter->get_name(),
- (is_get_failed_segment ? "Failed" : "Normal"),
- segment_to_send->seq_no);
- }
-#endif
-
- // If it is suspended, push the segment to the send-fail queue
- {
- if (this->is_loop_paused()) {
- LOG_VERB("Sending segment is pushed to failed queue at %s (suspended)",
- this->mAdapter->get_name());
-
- sm->failed_sending(segment_to_send);
- continue;
- }
- }
-
- int len = kSegHeaderSize + kSegSize;
- const void *data = segment_to_send->data;
-
- // Send data
- int res = this->mAdapter->send(data, len);
-
- // Error handling
- if (res <= 0) {
- if (this->mAdapter->is_disconnecting_on_purpose()) {
- // Now disconnecting on purpose... Send this segment by another
- // adapter.
- LOG_DEBUG("%s: Disconnecting on purpose (type=%d, seq_no=%lu)",
- this->mAdapter->get_name(), (int)is_control,
- segment_to_send->seq_no);
- sm->failed_sending(segment_to_send);
- break;
- } else if (errno == 0) {
- LOG_DEBUG("%s: Unknown error occured (type=%d, seq_no=%lu)",
- this->mAdapter->get_name(), (int)is_control,
- segment_to_send->seq_no);
- sm->failed_sending(segment_to_send);
- continue;
- } else if (errno == EINTR) {
- // Handling interrupted system call
- LOG_DEBUG("%s: Send interrupted (type=%d, seq_no=%lu)",
- this->mAdapter->get_name(), (int)is_control,
- segment_to_send->seq_no);
- sm->failed_sending(segment_to_send);
- continue;
- } else if (errno == EAGAIN) {
- // Kernel I/O buffer is full
- LOG_WARN(
- "%s: Send fail - Kernel I/O buffer is full (type=%d, seq_no=%lu)",
- this->mAdapter->get_name(), (int)is_control,
- segment_to_send->seq_no);
- sm->failed_sending(segment_to_send);
- continue;
- } else {
- // Other errors
- LOG_WARN("%s: Send fail - res=%d errno=%d(%s) (type=%d, seq_no=%lu)",
- this->mAdapter->get_name(), res, errno, strerror(errno),
- (int)is_control, segment_to_send->seq_no);
- sm->failed_sending(segment_to_send);
- break;
- }
- } else if (res != len) {
- LOG_WARN("%s: Send fail - sent_bytes are not accurate (type=%d, "
- "seq_no=%lu, expected=%d, sent=%d) - %d %s",
- this->mAdapter->get_name(), (int)is_control,
- segment_to_send->seq_no, len, res, errno, strerror(errno));
- sm->failed_sending(segment_to_send);
- break;
- }
-
- // If successful, update the last sequence number
- // Last sequence number is used to wait remaining segments on disconnection
- if(is_control) {
- this->set_last_seq_no_control(segment_to_send->seq_no);
- } else {
- this->set_last_seq_no_data(segment_to_send->seq_no);
- }
-
- sm->free_segment(segment_to_send);
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/ServerAdapter.cpp b/subprojects/sc/linux/core/src/ServerAdapter.cpp
deleted file mode 100644
index 47b7e66c..00000000
--- a/subprojects/sc/linux/core/src/ServerAdapter.cpp
+++ /dev/null
@@ -1,531 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- * Eunsoo Park (esevan.park@gmail.com)
- * Injung Hwang (sinban04@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/ServerAdapter.h"
-#include "../inc/ServerAdapterStateListener.h"
-
-#include "../inc/Core.h"
-#include "../inc/NetworkSwitcher.h"
-#include "../inc/SenderThread.h"
-
-#include "../../common/inc/DebugLog.h"
-
-#include "../../configs/ExpConfig.h"
-
-#include
-
-#ifdef EXP_MEASURE_INTERVAL_SENDER
-#include
-#endif
-
-using namespace sc;
-
-void ServerAdapter::launch_threads(void) {
- // Launch sender/receiver threads (initially, running but disabled state)
- // It is called by StartCoreTransaction.
- if (this->mSenderThread == NULL)
- this->mSenderThread = new SenderThread(this);
- this->mSenderThread->launch_thread();
- if (this->mReceiverThread == NULL)
- this->mReceiverThread = new ReceiverThread(this);
- this->mReceiverThread->launch_thread();
-}
-
-void ServerAdapter::finish_thread(void) {
- // Finish sender/receiver threads
- // It is called by StopCoreTransaction.
- this->mSenderThread->finish_thread();
- this->mReceiverThread->finish_thread();
-}
-
-void ServerAdapter::connect(ConnectCallback callback, bool is_send_request) {
- // Check adapter's state
- if (this->get_state() != ServerAdapterState::kDisconnected) {
- LOG_ERR(
- "It is already connected or connection/disconnection is in progress.");
- callback(this, false);
- return;
- }
-
- // Send request
- if (is_send_request) {
- Core::singleton()->get_control_sender()->send_request_connect(
- this->get_id());
- }
-
- // Connect
- this->connect_internal(callback);
-}
-
-void ServerAdapter::disconnect_on_command(DisconnectCallback callback) {
- // Check adapter's state
- // Check if the adapter is not sleeping
- ServerAdapterState state = this->get_state();
- if (state == ServerAdapterState::kGoingSleeping) {
- LOG_VERB("%s: Disconnect - waiting for sleeping...", this->get_name());
- while (state != ServerAdapterState::kSleeping) {
- ::sleep(1);
- state = this->get_state();
- }
- } else if (state != ServerAdapterState::kSleeping) {
- LOG_ERR("%s: Disconnect fail - not sleeping (state=%d)", this->get_name(),
- state);
- callback(this, false);
- return;
- }
-
- // Set this disconnection is on purpose
- this->start_disconnecting_on_purpose();
-
- // Get my final seq_no
- SegmentManager *sm = SegmentManager::singleton();
- uint32_t my_final_seq_no_control =
- this->mSenderThread->get_last_seq_no_control();
- uint32_t my_final_seq_no_data = this->mSenderThread->get_last_seq_no_data();
-
- // Send disconnect request
- Core::singleton()->get_control_sender()->send_request_disconnect(
- this->get_id(), my_final_seq_no_control, my_final_seq_no_data);
-
- this->disconnect_internal(callback);
-}
-
-void ServerAdapter::disconnect_on_peer_command(
- DisconnectCallback callback, uint32_t peer_final_seq_no_control,
- uint32_t peer_final_seq_no_data) {
- // Check adapter's state
- // Check if the adapter is not sleeping
- ServerAdapterState state = this->get_state();
- if (state == ServerAdapterState::kGoingSleeping) {
- LOG_VERB("%s: Disconnect - waiting for sleeping...", this->get_name());
- while (state != ServerAdapterState::kSleeping) {
- ::sleep(1);
- state = this->get_state();
- }
- } else if (state != ServerAdapterState::kSleeping) {
- LOG_ERR("%s: Disconnect fail - not sleeping", this->get_name());
- callback(this, false);
- return;
- }
-
- // Set this disconnection is on purpose
- this->start_disconnecting_on_purpose();
-
- // Start wait receiving
- SegmentManager *sm = SegmentManager::singleton();
- sm->wait_receiving(peer_final_seq_no_control, peer_final_seq_no_data);
-
- // Send disconnect ack
- Core::singleton()->get_control_sender()->send_request_disconnect_ack(
- this->get_id());
-
- this->disconnect_internal(callback);
-}
-
-void ServerAdapter::disconnect_on_failure(DisconnectCallback callback) {
- // Check adapter's state
- // Check if the adapter is already disconencted
- ServerAdapterState state = this->get_state();
- if (state == ServerAdapterState::kDisconnected ||
- state == ServerAdapterState::kDisconnecting) {
- LOG_ERR("%s: Disconnect fail - already disconnecting or disconnected",
- this->get_name());
- callback(this, false);
- return;
- }
-
- this->disconnect_internal(callback);
-}
-
-void ServerAdapter::connect_internal(ConnectCallback callback) {
- // Set callback and adapter's state
- this->mConnectCallback = callback;
- this->set_state(ServerAdapterState::kConnecting);
-
- bool res = this->__connect_internal();
-
- if (res) {
- this->set_state(ServerAdapterState::kActive);
- if (this->mConnectCallback != NULL) {
- this->mConnectCallback(this, true);
- this->mConnectCallback = NULL;
- }
- } else {
- this->set_state(ServerAdapterState::kDisconnected);
- if (this->mConnectCallback != NULL) {
- this->mConnectCallback(this, false);
- this->mConnectCallback = NULL;
- }
- }
-}
-
-bool ServerAdapter::__connect_internal(void) {
- if (this->mDevice == NULL || this->mP2PServer == NULL ||
- this->mServerSocket == NULL) {
- return false;
- }
-
- // Turn on device
- DeviceState deviceState = this->mDevice->get_state();
- if (deviceState != DeviceState::kOn &&
- deviceState != DeviceState::kTurningOn) {
- bool res = this->mDevice->turn_on();
- deviceState = this->mDevice->get_state();
- if (!res || deviceState != DeviceState::kOn) {
- LOG_ERR("%s: Cannot connect the server adapter - turn-on fail",
- this->get_name());
- return false;
- }
- } else {
- LOG_VERB("%s: Already turned on or turning on", this->get_name());
- }
-
- // Allow client's connection
- P2PServerState p2pServerState = this->mP2PServer->get_state();
- if (p2pServerState != P2PServerState::kAllowed) {
- bool res = this->mP2PServer->allow_discover();
-
- p2pServerState = this->mP2PServer->get_state();
- if (!res || p2pServerState != P2PServerState::kAllowed) {
- LOG_ERR("%s: Cannot connect the server adapter - allow discover fail",
- this->get_name());
- this->mDevice->turn_off();
- return false;
- }
- } else {
- LOG_VERB("%s: Already allowed discovery", this->get_name());
- }
-
- // Open server socket
- ServerSocketState socketState = this->mServerSocket->get_state();
- if (socketState != ServerSocketState::kOpened &&
- socketState != ServerSocketState::kOpening) {
- bool res = this->mServerSocket->open();
-
- socketState = this->mServerSocket->get_state();
- if (!res || socketState != ServerSocketState::kOpened) {
- LOG_ERR("%s: Cannot connect the server adapter - socket open fail",
- this->get_name());
- this->mP2PServer->disallow_discover();
- this->mDevice->turn_off();
- return false;
- }
- } else {
- LOG_VERB("%s: Already socket opened or opening", this->get_name());
- }
-
- // Enable sender thread's sender loop
- this->mSenderThread->enable_loop();
-
- // Enable receiver thread's receiver loop
- this->mReceiverThread->enable_loop();
-
- return true;
-}
-
-void ServerAdapter::disconnect_internal(DisconnectCallback callback) {
- // Set callback and adapter's state
- this->mDisconnectCallback = callback;
- ServerAdapterState oldState = this->get_state();
- this->set_state(ServerAdapterState::kDisconnecting);
-
- if (this->is_disconnecting_on_purpose() &&
- !this->is_disconnecting_on_purpose_peer()) {
- this->wait_for_disconnecting_on_purpose_peer();
- }
-
- bool res = this->__disconnect_internal(oldState);
-
- this->finish_disconnecting_on_purpose();
-
- if (res) {
- this->set_state(ServerAdapterState::kDisconnected);
- if (this->mDisconnectCallback != NULL) {
- this->mDisconnectCallback(this, true);
- this->mDisconnectCallback = NULL;
- }
- } else {
- this->set_state(oldState);
- if (this->mDisconnectCallback != NULL) {
- this->mDisconnectCallback(this, false);
- this->mDisconnectCallback = NULL;
- }
- }
-}
-
-bool ServerAdapter::__disconnect_internal(ServerAdapterState oldState) {
- // Disable sender thread's sender loop
- if (this->mSenderThread != NULL) {
- this->mSenderThread->disable_loop();
-
- // If this adapter is already sleeping(sender thread is paused),
- // resume the sender thread
- if (oldState == ServerAdapterState::kSleeping) {
- // Since it does not need state checking, it directly wakes up.
- this->wake_up_internal();
- }
- }
- // Disable receiver thread's receiver loop
- if (this->mReceiverThread != NULL) {
- this->mReceiverThread->disable_loop();
- }
-
- // Close server socket
- if (this->mServerSocket == NULL) {
- LOG_ERR("Cannot find server socket: %s", this->get_name());
- return false;
- }
-
- ServerSocketState socketState = this->mServerSocket->get_state();
- if (socketState != ServerSocketState::kClosed &&
- socketState != ServerSocketState::kClosing) {
- socketState = this->mServerSocket->get_state();
- if (socketState != ServerSocketState::kClosed) {
- bool res = this->mServerSocket->close();
-
- socketState = this->mServerSocket->get_state();
- if (!res || socketState != ServerSocketState::kClosed) {
- LOG_ERR("Cannot disconnect the server adapter - socket close fail: %s",
- this->get_name());
- return false;
- }
- }
- } else {
- LOG_VERB("%s: Already socket closed or closing", this->get_name());
- }
-
- // Disallow scan P2P Server
- if (this->mP2PServer == NULL) {
- LOG_ERR("Cannot find P2P server: %s", this->get_name());
- return false;
- }
-
- P2PServerState p2pServerState = this->mP2PServer->get_state();
- if (p2pServerState != P2PServerState::kDisallowed) {
- bool res = this->mP2PServer->disallow_discover();
-
- p2pServerState = this->mP2PServer->get_state();
- if (!res) {
- LOG_ERR(
- "Cannot disconnect the server adapter - disallow discover fail: %s",
- this->get_name());
- return false;
- }
- } else {
- LOG_VERB("%s: Already disallowed discovery", this->get_name());
- }
-
- // Turn off device
- if (this->mDevice == NULL) {
- LOG_ERR("Cannot find device: %s", this->get_name());
- return false;
- }
-
- DeviceState deviceState = this->mDevice->get_state();
- if (deviceState != DeviceState::kOff &&
- deviceState != DeviceState::kTurningOff) {
- bool res = this->mDevice->turn_off();
-
- deviceState = this->mDevice->get_state();
- if (!res) {
- LOG_ERR("Cannot disconnect the server adapter - turn-off fail: %s",
- this->get_name());
- return false;
- }
- } else {
- LOG_VERB("%s: Already turned off or turning off", this->get_name());
- }
-
- // Wait for sender/receiver thread
- if (this->mSenderThread != NULL) {
- LOG_DEBUG("Wait sender loop(%s)", this->get_name());
- this->mSenderThread->wait_until_disable_loop_done();
- LOG_DEBUG("End sender loop(%s)", this->get_name());
- }
- if (this->mReceiverThread != NULL) {
- LOG_DEBUG("Wait receiver loop(%s)", this->get_name());
- this->mReceiverThread->wait_until_disable_loop_done();
- LOG_DEBUG("End receiver loop(%s)", this->get_name());
- }
-
- return true;
-}
-
-int ServerAdapter::send(const void *buf, size_t len) {
- ServerAdapterState state = this->get_state();
- if (state == ServerAdapterState::kConnecting) {
- LOG_VERB("Send blocked: waiting for connection... (%d)", state);
- do {
- state = this->get_state();
- ::sleep(1);
- } while (state != ServerAdapterState::kActive);
- } else if (state != ServerAdapterState::kActive) {
- return -1;
- }
-
- if (this->mServerSocket == NULL) {
- return -2;
- }
-
- // Send
- int ret = this->mServerSocket->send(buf, len);
-
- // Update statistics
- if (ret > 0) {
- this->mSendDataSize.add((int)len);
- }
- return ret;
-}
-
-int ServerAdapter::receive(void *buf, size_t len) {
- ServerAdapterState state = this->get_state();
- if (state == ServerAdapterState::kConnecting) {
- LOG_VERB("Receive blocked: waiting for connection... (%d)", state);
- do {
- state = this->get_state();
- ::sleep(1);
- } while (state != ServerAdapterState::kActive);
- } else if (state != ServerAdapterState::kActive &&
- state != ServerAdapterState::kGoingSleeping &&
- state != ServerAdapterState::kSleeping &&
- state != ServerAdapterState::kWakingUp) {
- return -1;
- }
-
- if (this->mServerSocket == NULL) {
- return -2;
- }
-
- // Receive
- int ret = this->mServerSocket->receive(buf, len);
-
- // Update statistics
- if (ret > 0) {
- this->mReceiveDataSize.add((int)len);
- }
- return ret;
-}
-
-void ServerAdapter::sleep(DisconnectCallback callback, bool is_send_request) {
- ServerAdapterState state = this->get_state();
- if (state != ServerAdapterState::kActive) {
- LOG_ERR("Failed to sleep: %s (state: %d)", this->get_name(), state);
- if (callback != NULL)
- callback(this, false);
- return;
- }
-
- // Set sender thread paused
- bool sender_paused = false;
- {
- if (this->mSenderThread->is_loop_paused()) {
- LOG_ERR("Sender has already been paused!: %s", this->get_name());
- if (callback != NULL)
- callback(this, false);
- } else {
- // Send Request
- if (is_send_request) {
- Core::singleton()->get_control_sender()->send_request_sleep(
- this->get_id());
- }
-
- // Pause sender thread's sender loop
- this->set_state(ServerAdapterState::kGoingSleeping);
- this->mSenderThread->pause_loop();
-
- // Wake up sender thread waiting segment queue
- SegmentManager *sm = SegmentManager::singleton();
- sm->wake_up_dequeue_waiting(kDeqSendControlData);
- }
- }
-
- // Execute callback
- if (callback != NULL)
- callback(this, true);
-}
-
-void ServerAdapter::wake_up(DisconnectCallback callback, bool is_send_request) {
- ServerAdapterState state = this->get_state();
- if (state != ServerAdapterState::kSleeping) {
- LOG_ERR("Failed to wake up: %s (state: %d)", this->get_name(), state);
- if (callback != NULL)
- callback(this, false);
- return;
- }
-
- if (this->mSenderThread->is_loop_paused()) {
- // Send Wakeup Request
- if (is_send_request) {
- Core::singleton()->get_control_sender()->send_request_wake_up(
- this->get_id());
- }
-
- this->set_state(ServerAdapterState::kWakingUp);
-
- // Resume sender thread's sender loop
- this->wake_up_internal();
-
- if (callback != NULL)
- callback(this, true);
- } else {
- LOG_ERR("Sender has not been suspended!: %s", this->get_name());
- if (callback != NULL)
- callback(this, false);
- }
-}
-
-void ServerAdapter::wake_up_internal(void) {
- // Resume sender thread's sender loop
- this->mSenderThread->resume_loop();
-}
-
-void ServerAdapter::connect_or_wake_up(ConnectCallback callback,
- bool is_send_request) {
- ServerAdapterState state = this->get_state();
- if (state == ServerAdapterState::kDisconnected) {
- this->connect(callback, is_send_request);
- } else if (state == ServerAdapterState::kSleeping) {
- this->wake_up(callback, is_send_request);
- }
-}
-
-void ServerAdapter::set_state(ServerAdapterState new_state) {
- ServerAdapterState old_state;
-
- {
- std::unique_lock lck(this->mStateLock);
- old_state = this->mState;
- this->mState = new_state;
- }
-
- std::string old_state_str(server_adapter_state_to_string(old_state));
- std::string new_state_str(server_adapter_state_to_string(new_state));
-
- LOG_DEBUG("%s: State(%s->%s)", this->get_name(), old_state_str.c_str(),
- new_state_str.c_str());
-
- for (std::vector::iterator it =
- this->mStateListeners.begin();
- it != this->mStateListeners.end(); it++) {
- ServerAdapterStateListener *listener = (*it);
- listener->onUpdateServerAdapterState(this, old_state, new_state);
- }
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/core/src/ServerSocket.cpp b/subprojects/sc/linux/core/src/ServerSocket.cpp
deleted file mode 100644
index 5c00ad85..00000000
--- a/subprojects/sc/linux/core/src/ServerSocket.cpp
+++ /dev/null
@@ -1,90 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "../inc/ServerSocket.h"
-
-#include "../inc/ServerAdapter.h"
-
-#include "../../common/inc/DebugLog.h"
-
-#include
-#include
-
-using namespace sc;
-
-bool ServerSocket::open(void) {
- if (this->get_state() != ServerSocketState::kClosed) {
- LOG_ERR("It is already opened or opening/closing is in progress.");
- return false;
- }
-
- this->set_state(ServerSocketState::kOpening);
-
- bool res = this->open_impl();
-
- if (!res) {
- this->set_state(ServerSocketState::kClosed);
- } else {
- this->set_state(ServerSocketState::kOpened);
- }
- return res;
-}
-
-bool ServerSocket::close(void) {
- if (this->get_state() != ServerSocketState::kOpened) {
- LOG_ERR("%s: It is already closed or opening/closing is in progress.",
- this->get_name());
- return false;
- }
-
- this->set_state(ServerSocketState::kClosing);
-
- bool res = this->close_impl();
-
- this->set_state(ServerSocketState::kClosed);
- return res;
-}
-
-int ServerSocket::send(const void *data_buffer, size_t data_length) {
- if (this->get_state() != ServerSocketState::kOpened) {
- LOG_ERR("%s: Socket not opened", this->get_name());
- return -1;
- }
-
- int res = this->send_impl(data_buffer, data_length);
- if (errno != EINTR && errno != EAGAIN && errno != 0 && res < 0) {
- LOG_WARN("%s: Socket closed", this->get_name());
- this->set_state(ServerSocketState::kClosed);
- }
- return res;
-}
-
-int ServerSocket::receive(void *data_buffer, size_t data_length) {
- if (this->get_state() != ServerSocketState::kOpened) {
- LOG_ERR("%s: Socket not opened", this->get_name());
- return -1;
- }
-
- int res = this->receive_impl(data_buffer, data_length);
- if (errno != EINTR && errno != EAGAIN && errno != 0 && res != -999 && res < 0) {
- LOG_WARN("%s: Socket closed: %d / %s", this->get_name(), errno, strerror(errno));
- this->set_state(ServerSocketState::kClosed);
- }
- return res;
-}
\ No newline at end of file
diff --git a/subprojects/sc/linux/device/inc/BtDevice.h b/subprojects/sc/linux/device/inc/BtDevice.h
deleted file mode 100644
index 41c47f39..00000000
--- a/subprojects/sc/linux/device/inc/BtDevice.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __BT_DEVICE_H__
-#define __BT_DEVICE_H__
-
-#include "../../core/inc/Device.h"
-
-#include
-#include
-
-#include
-
-namespace sc {
-class BtDevice : public Device {
-public:
- virtual bool turn_on_impl(void);
- virtual bool turn_off_impl(void);
-
- BtDevice() : Device("Bluetooth") {}
- ~BtDevice(void) {}
-
-protected:
-}; /* class BtDevice */
-} /* namespace sc */
-
-#endif /* !defined(__BT_DEVICE_H__) */
diff --git a/subprojects/sc/linux/device/inc/BtP2PServer.h b/subprojects/sc/linux/device/inc/BtP2PServer.h
deleted file mode 100644
index d621e510..00000000
--- a/subprojects/sc/linux/device/inc/BtP2PServer.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __BT_P2P_SERVER_H__
-#define __BT_P2P_SERVER_H__
-
-#include "../../core/inc/P2PServer.h"
-
-#include
-#include
-
-#include
-
-namespace sc {
-class BtP2PServer : public P2PServer {
-public:
- virtual bool allow_discover_impl(void);
- virtual bool disallow_discover_impl(void);
-
- BtP2PServer(void) : P2PServer("BT") {}
- ~BtP2PServer(void) {}
-
-protected:
-}; /* class BtP2PServer */
-} /* namespace sc */
-
-#endif /* !defined(__BT_P2P_SERVER_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/device/inc/BtServerAdapter.h b/subprojects/sc/linux/device/inc/BtServerAdapter.h
deleted file mode 100644
index 6639a64d..00000000
--- a/subprojects/sc/linux/device/inc/BtServerAdapter.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __BT_SERVER_ADAPTER_H__
-#define __BT_SERVER_ADAPTER_H__
-
-#include "BtDevice.h"
-#include "BtP2PServer.h"
-#include "RfcommServerSocket.h"
-
-#include "../../core/inc/ServerAdapter.h"
-
-#include "../../configs/ExpConfig.h"
-
-#include
-#include
-
-#include
-
-namespace sc {
-class BtServerAdapter : public ServerAdapter {
-public:
- ~BtServerAdapter(void) {}
-
- /* Singleton */
- static BtServerAdapter *singleton(int id, const char *name,
- const char *service_uuid) {
- if (sSingleton == NULL) {
- sSingleton = new BtServerAdapter(id, name, service_uuid);
- }
- return sSingleton;
- }
-
-private:
- /* Singleton */
- static BtServerAdapter *sSingleton;
-
- /* Constructor */
- BtServerAdapter(int id, const char *name, const char *service_uuid)
- : ServerAdapter(id, name) {
- BtDevice *device = new BtDevice();
- BtP2PServer *p2pServer = new BtP2PServer();
- RfcommServerSocket *serverSocket =
- new RfcommServerSocket(name, service_uuid);
- this->initialize(device, p2pServer, serverSocket);
- }
-}; /* class BtServerAdapter */
-} /* namespace sc */
-
-#endif /* !defined(__BT_SERVER_ADAPTER_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/device/inc/CommInitializer.h b/subprojects/sc/linux/device/inc/CommInitializer.h
deleted file mode 100644
index 45ee95d9..00000000
--- a/subprojects/sc/linux/device/inc/CommInitializer.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __COMM_INITIALIZER_H__
-#define __COMM_INITIALIZER_H__
-
-#include
-
-namespace sc {
-class CommInitializer {
-public:
- void initialize(void);
-private:
- int kill_dhcpd(void);
- int ping_wpa_cli(char ret[], size_t len);
- void retrieve_wpa_interface_name(std::string &wpaIntfName);
-}; /* class CommInitializer */
-} /* namespace sc */
-
-#endif /* !defined(__COMM_INITIALIZER_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/device/inc/EthServerAdapter.h b/subprojects/sc/linux/device/inc/EthServerAdapter.h
deleted file mode 100644
index f17bae1e..00000000
--- a/subprojects/sc/linux/device/inc/EthServerAdapter.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __ETH_SERVER_ADAPTER_H__
-#define __ETH_SERVER_ADAPTER_H__
-
-#include "TcpServerSocket.h"
-
-#include "../../core/inc/ServerAdapter.h"
-
-#include
-#include
-#include
-#include
-
-#include
-#include
-
-#include
-
-namespace sc {
-class EthDevice : public Device {
-public:
- virtual bool turn_on_impl(void) { return true; }
- virtual bool turn_off_impl(void) { return true; }
-
- static EthDevice *getSingleton(void) {
- if (EthDevice::sSingleton == NULL) {
- EthDevice::sSingleton = new EthDevice();
- }
- return EthDevice::sSingleton;
- }
-
-protected:
- static EthDevice *sSingleton;
- EthDevice() : Device("Eth") {}
-}; /* class EthDevice */
-
-class EthP2PServer : public P2PServer {
-public:
- virtual bool allow_discover_impl(void) { return true; }
- virtual bool disallow_discover_impl(void) { return true; }
-
- EthP2PServer() : P2PServer("Eth") {}
-}; /* class EthP2PServer */
-
-class EthServerAdapter : public ServerAdapter {
-public:
- EthServerAdapter(int id, const char *name, int port)
- : ServerAdapter(id, name) {
- EthDevice *device = EthDevice::getSingleton();
- EthP2PServer *p2pServer = new EthP2PServer();
- TcpServerSocket *serverSocket = new TcpServerSocket(name, port);
- serverSocket->set_ip_address_raw(htonl(INADDR_ANY));
- this->initialize(device, p2pServer, serverSocket);
- }
-
- ~EthServerAdapter(void) {}
-
-protected:
-}; /* class EthServerAdapter */
-} /* namespace sc */
-
-#endif /* !defined(__ETH_SERVER_ADAPTER_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/device/inc/RfcommServerSocket.h b/subprojects/sc/linux/device/inc/RfcommServerSocket.h
deleted file mode 100644
index 534abcf6..00000000
--- a/subprojects/sc/linux/device/inc/RfcommServerSocket.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __RFCOMM_SERVER_SOCKET_H__
-#define __RFCOMM_SERVER_SOCKET_H__
-
-#include "../../core/inc/ServerSocket.h"
-
-#include
-#include
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-namespace sc {
-class RfcommServerSocket : public ServerSocket {
-public:
- virtual bool open_impl(void);
- virtual bool close_impl(void);
- virtual int send_impl(const void *data_buffer, size_t data_length);
- virtual int receive_impl(void *data_buffer, size_t data_length);
-
- uuid_t get_service_uuid(void) { return this->mServiceUUID; }
-
- RfcommServerSocket(const char *name, const char *service_uuid)
- : ServerSocket(name) {
- char buffer[100];
- snprintf(buffer, 100, "%s", service_uuid);
- this->str2uuid(buffer, &(this->mServiceUUID));
- this->mPort = -1;
- }
-
- ~RfcommServerSocket(void) {}
-
-protected:
- uuid_t mServiceUUID;
- int mPort;
-
- sdp_session_t *mSdpSession;
- int mServerSocket;
- int mClientSocket;
-
-private:
- int bt_dynamic_bind_rc(void);
- int bt_register_service(void);
- int str2uuid(char *str, uuid_t *uuid);
-}; /* class RfcommServerSocket */
-} /* namespace sc */
-
-#endif /* !defined(__RFCOMM_SERVER_SOCKET_H__) */
\ No newline at end of file
diff --git a/subprojects/sc/linux/device/inc/TcpServerSocket.h b/subprojects/sc/linux/device/inc/TcpServerSocket.h
deleted file mode 100644
index 3873843c..00000000
--- a/subprojects/sc/linux/device/inc/TcpServerSocket.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Copyright 2017-2018 All Rights Reserved.
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * [Contact]
- * Gyeonghwan Hong (redcarrottt@gmail.com)
- *
- * Licensed under the Apache License, Version 2.0(the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __TCP_SERVER_SOCKET_H__
-#define __TCP_SERVER_SOCKET_H__
-
-#include "WfdIpAddressListener.h"
-
-#include "../../core/inc/ServerSocket.h"
-
-#include
-#include
-
-#include
-#include