SL4N: Scripting Layer For Native

[DO NOT MERGE]

This CL contains the necessary components
for basic Android Native Testing. It also
includes some basic Bluetooth facades
to call APIs on the HAL and Binder layer.

This has been code reviewed here:
https://android-review.googlesource.com/#/c/180639

Change-Id: I3bc4f630764b0d93aa011be8b45cb404d9bb8b40
diff --git a/sl4n/Android.mk b/sl4n/Android.mk
new file mode 100644
index 0000000..286453c
--- /dev/null
+++ b/sl4n/Android.mk
@@ -0,0 +1,52 @@
+#
+#  Copyright (C) 2015 Google, Inc.
+#
+#  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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE := sl4n
+
+LOCAL_C_INCLUDES += \
+  $(ANDROID_BUILD_TOP)/system/bt \
+  $(LOCAL_PATH)/rapidjson/include \
+  $(LOCAL_PATH)/facades
+
+LOCAL_SRC_FILES := \
+  facades/bluetooth/bluetooth_binder_facade.cpp \
+  main.cpp \
+  utils/command_receiver.cpp \
+  utils/common_utils.cpp
+
+LOCAL_SHARED_LIBRARIES += \
+  libbinder \
+  libchrome \
+  libcutils \
+  libutils \
+  libhardware \
+  libhardware_legacy \
+  liblog
+
+LOCAL_STATIC_LIBRARIES += \
+  libbtcore \
+  libosi \
+  libbluetooth-client
+
+
+LOCAL_CFLAGS += -std=c++11 -Wall -Wno-unused-parameter -Wno-missing-field-initializers
+
+include $(BUILD_EXECUTABLE)
diff --git a/sl4n/base.h b/sl4n/base.h
new file mode 100644
index 0000000..0947d35
--- /dev/null
+++ b/sl4n/base.h
@@ -0,0 +1,60 @@
+//
+//  Copyright (C) 2015 Google, Inc.
+//
+//  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.
+//
+
+#pragma once
+
+#include <stdio.h>
+#include <stdbool.h>
+#include <string.h>
+
+#include <base/logging.h>
+#include <hardware/bluetooth.h>
+#include <hardware/bt_gatt.h>
+#include <hardware/bt_pan.h>
+#include <hardware/bt_sock.h>
+#include <hardware/hardware.h>
+#include <base/macros.h>
+
+namespace sl4n {
+const char kCmdStr[] = "cmd";
+const char kDeviceNameStr[] = "deviceName";
+const char kErrorStr[] = "error";
+const char kFailStr[] = "fail";
+const char kInvalidParamStr[] = "Invalid parameter";
+const char kMethodStr[] = "method";
+const char kParamsStr[] = "params";
+const char kResultStr[] = "result";
+const char kStatusStr[] = "status";
+const char kSuccessStr[] = "success";
+const char kTagStr[] = "SL4N";
+const int kFailedCounterInt = -1;
+}
+
+namespace sl4n_ble {
+const int kAdvSettingsModeLowPowerInt = 0;
+const int kAdvSettingsModeBalancedInt = 1;
+const int kAdvSettingsModeLowLatencyInt = 2;
+
+const int kAdvSettingsTxPowerLevelUltraLowInt = 0;
+const int kAdvSettingsTxPowerLevelLowInt = 1;
+const int kAdvSettingsTxPowerLevelMediumInt = 2;
+const int kAdvSettingsTxPowerLevelHighInt = 3;
+}
+
+namespace sl4n_error_codes {
+const int kFailInt = 0;
+const int kPassInt = 1;
+}
diff --git a/sl4n/facades/bluetooth/bluetooth_binder_facade.cpp b/sl4n/facades/bluetooth/bluetooth_binder_facade.cpp
new file mode 100644
index 0000000..51c1644
--- /dev/null
+++ b/sl4n/facades/bluetooth/bluetooth_binder_facade.cpp
@@ -0,0 +1,175 @@
+//
+//  Copyright (C) 2015 Google, Inc.
+//
+//  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 <base.h>
+#include <base/at_exit.h>
+#include <base/command_line.h>
+#include <base/logging.h>
+#include <base/macros.h>
+#include <base/strings/string_split.h>
+#include <base/strings/string_util.h>
+#include <binder/IPCThreadState.h>
+#include <binder/ProcessState.h>
+
+#include "bluetooth_binder_facade.h"
+#include <service/common/bluetooth/binder/IBluetooth.h>
+#include <service/common/bluetooth/binder/IBluetoothCallback.h>
+#include <service/common/bluetooth/binder/IBluetoothLowEnergy.h>
+#include <service/common/bluetooth/low_energy_constants.h>
+#include <tuple>
+
+using android::sp;
+using ipc::binder::IBluetooth;
+using ipc::binder::IBluetoothLowEnergy;
+
+std::atomic_bool ble_registering(false);
+std::atomic_int ble_client_id(0);
+
+bool BluetoothBinderFacade::SharedValidator() {
+  if (bt_iface == NULL) {
+    LOG(ERROR) << sl4n::kTagStr << " IBluetooth interface not initialized";
+    return false;
+  }
+  if (!bt_iface->IsEnabled()) {
+    LOG(ERROR) << sl4n::kTagStr << " IBluetooth interface not enabled";
+    return false;
+  }
+  return true;
+}
+
+std::tuple<bool, int> BluetoothBinderFacade::BluetoothBinderEnable() {
+  if (bt_iface == NULL) {
+    LOG(ERROR) << sl4n::kTagStr << ": IBluetooth interface not enabled";
+    return std::make_tuple(false, sl4n_error_codes::kFailInt);
+  }
+  bool result = bt_iface->Enable();
+  if (!result) {
+    LOG(ERROR) << sl4n::kTagStr << ": Failed to enable the Bluetooth service";
+    return std::make_tuple(false, sl4n_error_codes::kPassInt);
+  } else {
+    return std::make_tuple(true, sl4n_error_codes::kPassInt);
+  }
+}
+
+std::tuple<std::string, int> BluetoothBinderFacade::BluetoothBinderGetAddress() {
+  if (!SharedValidator()) {
+    return std::make_tuple(sl4n::kFailStr, sl4n_error_codes::kFailInt);
+  }
+  return std::make_tuple(bt_iface->GetAddress(), sl4n_error_codes::kPassInt);
+}
+
+std::tuple<std::string, int> BluetoothBinderFacade::BluetoothBinderGetName() {
+  if (!SharedValidator()) {
+    return std::make_tuple(sl4n::kFailStr,sl4n_error_codes::kFailInt);
+  }
+  std::string name = bt_iface->GetName();
+  if (name.empty()) {
+    LOG(ERROR) << sl4n::kTagStr << ": Failed to get device name";
+    return std::make_tuple(sl4n::kFailStr, sl4n_error_codes::kFailInt);
+  } else {
+    return std::make_tuple(name, sl4n_error_codes::kPassInt);
+  }
+}
+
+std::tuple<bool, int> BluetoothBinderFacade::BluetoothBinderSetName(
+  std::string name) {
+
+  if (!SharedValidator()) {
+    return std::make_tuple(false, sl4n_error_codes::kFailInt);
+  }
+  bool result = bt_iface->SetName(name);
+  if (!result) {
+    LOG(ERROR) << sl4n::kTagStr << ": Failed to set device name";
+    return std::make_tuple(false, sl4n_error_codes::kFailInt);
+  }
+  return std::make_tuple(true, sl4n_error_codes::kPassInt);
+}
+
+std::tuple<bool, int> BluetoothBinderFacade::BluetoothBinderInitInterface() {
+  bt_iface = IBluetooth::getClientInterface();
+  if(!bt_iface.get()) {
+    LOG(ERROR) << sl4n::kTagStr <<
+      ": Failed to initialize IBluetooth interface";
+    return std::make_tuple(false, sl4n_error_codes::kFailInt);
+  }
+  return std::make_tuple(true, sl4n_error_codes::kPassInt);
+}
+
+std::tuple<bool, int> BluetoothBinderFacade::BluetoothBinderRegisterBLE() {
+  // TODO (tturney): verify bt_iface initialized everywhere
+  if (!SharedValidator()) {
+    return std::make_tuple(false, sl4n_error_codes::kFailInt);
+  }
+  ble_iface = bt_iface->GetLowEnergyInterface();
+  if(!ble_iface.get()) {
+    LOG(ERROR) << sl4n::kTagStr << ": Failed to register BLE";
+    return std::make_tuple(false, sl4n_error_codes::kFailInt);
+  }
+  return std::make_tuple(true, sl4n_error_codes::kPassInt);
+}
+
+std::tuple<int, int> BluetoothBinderFacade::BluetoothBinderSetAdvSettings(
+  int mode, int timeout_seconds, int tx_power_level, bool is_connectable) {
+  if (!SharedValidator()) {
+    return std::make_tuple(false,sl4n_error_codes::kFailInt);
+  }
+  bluetooth::AdvertiseSettings::Mode adv_mode;
+  switch (mode) {
+    case sl4n_ble::kAdvSettingsModeLowPowerInt :
+      adv_mode = bluetooth::AdvertiseSettings::Mode::MODE_LOW_POWER;
+    case sl4n_ble::kAdvSettingsModeBalancedInt :
+      adv_mode = bluetooth::AdvertiseSettings::Mode::MODE_BALANCED;
+    case sl4n_ble::kAdvSettingsModeLowLatencyInt :
+      adv_mode = bluetooth::AdvertiseSettings::Mode::MODE_LOW_LATENCY;
+    default :
+      LOG(ERROR) << sl4n::kTagStr <<
+        ": Input mode is outside the accepted values";
+      return std::make_tuple(
+        sl4n::kFailedCounterInt, sl4n_error_codes::kFailInt);
+  }
+
+  base::TimeDelta adv_timeout = base::TimeDelta::FromSeconds(
+    timeout_seconds);
+
+  bluetooth::AdvertiseSettings::TxPowerLevel adv_tx_power_level;
+  switch (tx_power_level) {
+    case sl4n_ble::kAdvSettingsTxPowerLevelUltraLowInt: tx_power_level =
+      bluetooth::AdvertiseSettings::TxPowerLevel::TX_POWER_LEVEL_ULTRA_LOW;
+    case sl4n_ble::kAdvSettingsTxPowerLevelLowInt: tx_power_level =
+      bluetooth::AdvertiseSettings::TxPowerLevel::TX_POWER_LEVEL_LOW;
+    case sl4n_ble::kAdvSettingsTxPowerLevelMediumInt: tx_power_level =
+      bluetooth::AdvertiseSettings::TxPowerLevel::TX_POWER_LEVEL_MEDIUM;
+    case sl4n_ble::kAdvSettingsTxPowerLevelHighInt: tx_power_level =
+      bluetooth::AdvertiseSettings::TxPowerLevel::TX_POWER_LEVEL_HIGH;
+    default :
+      LOG(ERROR) << sl4n::kTagStr <<
+        ": Input tx power level is outside the accepted values";
+      return std::make_tuple(
+        sl4n::kFailedCounterInt, sl4n_error_codes::kFailInt);
+  }
+
+  bluetooth::AdvertiseSettings adv_settings = bluetooth::AdvertiseSettings(
+    adv_mode, adv_timeout, adv_tx_power_level, is_connectable);
+  adv_settings_map[adv_settings_count] = adv_settings;
+  int adv_settings_id = adv_settings_count;
+  adv_settings_count++;
+  return std::make_tuple(adv_settings_id, sl4n_error_codes::kPassInt);
+}
+
+BluetoothBinderFacade::BluetoothBinderFacade() {
+  adv_settings_count = 0;
+  manu_data_count = 0;
+}
\ No newline at end of file
diff --git a/sl4n/facades/bluetooth/bluetooth_binder_facade.h b/sl4n/facades/bluetooth/bluetooth_binder_facade.h
new file mode 100644
index 0000000..68a874f
--- /dev/null
+++ b/sl4n/facades/bluetooth/bluetooth_binder_facade.h
@@ -0,0 +1,62 @@
+//
+//  Copyright (C) 2015 Google, Inc.
+//
+//  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.
+//
+
+#pragma once
+
+#include <rapidjson/document.h>
+#include <service/common/bluetooth/binder/IBluetooth.h>
+#include <service/common/bluetooth/binder/IBluetoothLowEnergy.h>
+#include <tuple>
+
+// BluetoothBinderFacade provides simple wrappers to call Binder apis.
+// Each public function returns a tuple of the return type and an integer
+// representing the pass/fail value of the function. The functions check to see
+// if the API call is actually possible. If it is the function's tuple will
+// contain the actual result and an integer that indicates the value passed. If
+// the function is not possible then there will be a dummy return value in the
+// first position of the tuple and the second value in the tuple indicates the
+// value failed. Therefore it is up to the function to decide whether the
+// expected api call is actually possible before calling it.
+//
+// TODO(tturney): Instead of using an integer in the tuple to represent
+// pass/fail, create a class that properly represents the result of the
+// function.
+class BluetoothBinderFacade {
+ public:
+  BluetoothBinderFacade();
+  std::tuple<bool, int> BluetoothBinderEnable();
+  std::tuple<std::string, int> BluetoothBinderGetAddress();
+  std::tuple<std::string, int> BluetoothBinderGetName();
+  std::tuple<bool, int> BluetoothBinderInitInterface();
+  std::tuple<bool, int> BluetoothBinderRegisterBLE();
+  std::tuple<int, int> BluetoothBinderSetAdvSettings(
+    int mode, int timeout_seconds, int tx_power_level, bool is_connectable);
+  std::tuple<bool, int> BluetoothBinderSetName(std::string name);
+
+ private:
+  bool SharedValidator();
+  // Returns a handle to the IBluetooth Binder from the Android ServiceManager.
+  // Binder client code can use this to make calls to the service.
+  android::sp<ipc::binder::IBluetooth> bt_iface;
+
+  // Returns a handle to the IBluetoothLowEnergy Binder from the Android
+  // ServiceManager. Binder client code can use this to make calls to the
+  // service.
+  android::sp<ipc::binder::IBluetoothLowEnergy> ble_iface;
+  std::map<int, bluetooth::AdvertiseSettings> adv_settings_map;
+  int adv_settings_count;
+  int manu_data_count;
+};
diff --git a/sl4n/main.cpp b/sl4n/main.cpp
new file mode 100644
index 0000000..0aab002
--- /dev/null
+++ b/sl4n/main.cpp
@@ -0,0 +1,114 @@
+//
+//  Copyright (C) 2015 Google, Inc.
+//
+//  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 "base.h"
+#include <rapidjson/document.h>
+#include <rapidjson/writer.h>
+#include <rapidjson/stringbuffer.h>
+#include "utils/command_receiver.h"
+
+#include <arpa/inet.h>
+#include <errno.h>
+#include <iostream>
+#include <netinet/in.h>
+#include <pthread.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+const int kBacklogInt = 10;
+#define PORT 8080
+#define SOCK_BUF_LEN 100
+#define MEMSET_VALUE 0
+
+int client_sock;
+int socket_desc;
+
+void SockTest() {
+  char str[SOCK_BUF_LEN];
+  int listen_fd, comm_fd, c;
+  struct sockaddr_in servaddr, client;
+  rapidjson::Document d;
+  rapidjson::StringBuffer buffer;
+  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
+  CommandReceiver cr;
+
+  listen_fd = socket(AF_INET, SOCK_STREAM, 0);
+  memset (&servaddr, MEMSET_VALUE, sizeof(servaddr));
+  servaddr.sin_family = AF_INET;
+  servaddr.sin_addr.s_addr = INADDR_ANY;
+  servaddr.sin_port = htons(PORT);
+
+  int bind_result = bind(
+          listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));
+  if (bind_result != 0) {
+    LOG(ERROR) << sl4n::kTagStr <<
+      ": Failed to assign the address to the socket."
+      << " Error: " << strerror(errno) << ", " << errno;
+    exit(1);
+  }
+
+  int listen_result = listen(listen_fd, kBacklogInt);
+  if (listen_result != 0) {
+    LOG(ERROR) << sl4n::kTagStr << ": Failed to setup the passive socket."
+     << " Error: " << strerror(errno) << ", " << errno;
+    exit(1);
+  }
+
+  comm_fd = accept(listen_fd, (struct sockaddr*)&client, (socklen_t*)&c);
+  if (comm_fd == -1) {
+    LOG(ERROR) << sl4n::kTagStr << ": Failed to accept the socket."
+      << " Error: " << strerror(errno) << ", " << errno;
+    exit(1);
+  }
+
+  while (true) {
+    memset(str, MEMSET_VALUE, sizeof(str));
+    int read_result = read(comm_fd, str, SOCK_BUF_LEN);
+    if (read_result < 0) {
+      LOG(FATAL) << sl4n::kTagStr << ": Failed to write to the socket."
+        << " Error: " << strerror(errno) << ", " << errno;
+      exit(1);
+    }
+
+    d.Parse(str);
+    cr.Call(d);
+    d.Accept(writer);
+    std::string str2 = buffer.GetString();
+    str2 += '\n';
+    strncpy(str, str2.c_str(), sizeof(str)-1);
+    int result = write(comm_fd, str, strlen(str)+1);
+    if (result < 0) {
+      LOG(FATAL) << sl4n::kTagStr << ": Failed to write to the socket."
+        << " Error: " << strerror(errno) << ", " << errno;
+      exit(1);
+    }
+    d.RemoveAllMembers(); // Remove all members from the json object
+    buffer.Clear();
+  }
+}
+
+int main(int argc, char **argv) {
+    logging::LoggingSettings log_settings;
+    if (!logging::InitLogging(log_settings)) {
+      LOG(ERROR) << "Failed to set up logging";
+      return EXIT_FAILURE;
+    }
+    SockTest();
+    return 0;
+}
diff --git a/sl4n/utils/command_receiver.cpp b/sl4n/utils/command_receiver.cpp
new file mode 100644
index 0000000..31493bf
--- /dev/null
+++ b/sl4n/utils/command_receiver.cpp
@@ -0,0 +1,261 @@
+//
+//  Copyright (C) 2015 Google, Inc.
+//
+//  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 <rapidjson/document.h>
+#include <rapidjson/writer.h>
+#include <rapidjson/stringbuffer.h>
+#include <map>
+#include <string>
+#include <stdio.h>
+#include <tuple>
+
+#include <base.h>
+#include <facades/bluetooth/bluetooth_binder_facade.h>
+#include <service/common/bluetooth/binder/IBluetooth.h>
+#include <utils/command_receiver.h>
+#include <utils/common_utils.h>
+
+using android::sp;
+using ipc::binder::IBluetooth;
+
+typedef void (*MFP)(rapidjson::Document&);
+typedef std::map<std::string, MFP> function_map;
+function_map _funcMap;
+BluetoothBinderFacade bt_binder;
+
+void _clean_result(rapidjson::Document &doc) {
+  doc.RemoveMember(sl4n::kMethodStr);
+  doc.RemoveMember(sl4n::kParamsStr);
+}
+
+void initiate(rapidjson::Document &doc) {
+  doc.AddMember(sl4n::kStatusStr, sl4n::kSuccessStr, doc.GetAllocator());
+}
+
+// Begin Wrappers ... I'm the hiphopopotamus my lyrics are bottomless...
+void bluetooth_binder_get_local_name_wrapper(rapidjson::Document &doc) {
+  int expected_param_size = 0;
+  if (!CommonUtils::IsParamLengthMatching(doc, expected_param_size)) {
+    return;
+  }
+  //check for kfailedstr or NULL???
+  std::string name;
+  int error_code;
+  std::tie(name, error_code) = bt_binder.BluetoothBinderGetName();
+  if (error_code == sl4n_error_codes::kFailInt) {
+    doc.AddMember(sl4n::kResultStr, sl4n::kFailStr, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kFailStr, doc.GetAllocator());
+    return;
+  }
+  rapidjson::Value tmp;
+  tmp.SetString(name.c_str(), doc.GetAllocator());
+  doc.AddMember(sl4n::kResultStr, tmp, doc.GetAllocator());
+  doc.AddMember(sl4n::kErrorStr, NULL, doc.GetAllocator());
+  return;
+}
+
+void bluetooth_binder_init_interface_wapper(rapidjson::Document &doc) {
+  int expected_param_size = 0;
+  if (!CommonUtils::IsParamLengthMatching(doc, expected_param_size)) {
+    return;
+  }
+  bool init_result;
+  int error_code;
+  std::tie(init_result, error_code) = bt_binder.BluetoothBinderInitInterface();
+  if (error_code == sl4n_error_codes::kFailInt) {
+    doc.AddMember(sl4n::kErrorStr, sl4n::kFailStr, doc.GetAllocator());
+  } else {
+    doc.AddMember(sl4n::kErrorStr, NULL, doc.GetAllocator());
+  }
+  doc.AddMember(sl4n::kResultStr, init_result, doc.GetAllocator());
+  return;
+}
+
+void bluetooth_binder_set_local_name_wrapper(rapidjson::Document &doc) {
+  int expected_param_size = 1;
+  if (!CommonUtils::IsParamLengthMatching(doc, expected_param_size)) {
+    return;
+  }
+  std::string name;
+  if (!doc[sl4n::kParamsStr][0].IsString()) {
+    LOG(ERROR) << sl4n::kTagStr << ": Expected String input for name";
+    doc.AddMember(sl4n::kResultStr, false, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kFailStr, doc.GetAllocator());
+    return;
+  } else {
+    name = doc[sl4n::kParamsStr][0].GetString();
+  }
+  bool set_result;
+  int error_code;
+  std::tie(set_result, error_code) = bt_binder.BluetoothBinderSetName(name);
+  if (error_code == sl4n_error_codes::kFailInt) {
+    doc.AddMember(sl4n::kResultStr, false, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kFailStr, doc.GetAllocator());
+  } else {
+    doc.AddMember(sl4n::kResultStr, set_result, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, NULL, doc.GetAllocator());
+  }
+  return;
+}
+
+void bluetooth_binder_get_local_address_wrapper(rapidjson::Document &doc) {
+  int expected_param_size = 0;
+  if (!CommonUtils::IsParamLengthMatching(doc, expected_param_size)) {
+    return;
+  }
+  //check for kfailedstr or NULL???
+  std::string address;
+  int error_code;
+  std::tie(address, error_code) = bt_binder.BluetoothBinderGetAddress();
+  if (error_code == sl4n_error_codes::kFailInt) {
+    doc.AddMember(sl4n::kResultStr, sl4n::kFailStr, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kFailStr, doc.GetAllocator());
+  } else {
+    rapidjson::Value tmp;
+    tmp.SetString(address.c_str(), doc.GetAllocator());
+    doc.AddMember(sl4n::kResultStr, tmp, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, NULL, doc.GetAllocator());
+  }
+  return;
+}
+
+void bluetooth_binder_enable_wrapper(rapidjson::Document &doc) {
+  int expected_param_size = 0;
+  if (!CommonUtils::IsParamLengthMatching(doc, expected_param_size)) {
+    return;
+  }
+  bool enable_result;
+  int error_code;
+  std::tie(enable_result, error_code) = bt_binder.BluetoothBinderEnable();
+  if (error_code == sl4n_error_codes::kFailInt) {
+    doc.AddMember(sl4n::kResultStr, false, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kFailStr, doc.GetAllocator());
+  } else {
+    doc.AddMember(sl4n::kResultStr, enable_result, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, NULL, doc.GetAllocator());
+  }
+}
+
+void bluetooth_binder_register_ble_wrapper(rapidjson::Document &doc) {
+  int expected_param_size = 0;
+  if (!CommonUtils::IsParamLengthMatching(doc, expected_param_size)) {
+    return;
+  }
+  bool register_result;
+  int error_code;
+  std::tie(register_result, error_code) =
+    bt_binder.BluetoothBinderRegisterBLE();
+  if (error_code == sl4n_error_codes::kFailInt) {
+    doc.AddMember(sl4n::kResultStr, false, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kFailStr, doc.GetAllocator());
+  } else {
+    doc.AddMember(sl4n::kResultStr, register_result, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, NULL, doc.GetAllocator());
+  }
+}
+
+void bluetooth_binder_set_adv_settings_wrapper(rapidjson::Document &doc) {
+  int expected_param_size = 4;
+  if (!CommonUtils::IsParamLengthMatching(doc, expected_param_size)) {
+    return;
+  }
+  int mode;
+  int timeout_seconds;
+  int tx_power_level;
+  bool is_connectable;
+  // TODO(tturney) Verify inputs better
+  if (!doc[sl4n::kParamsStr][0].IsInt()) {
+    LOG(ERROR) << sl4n::kTagStr << ": Expected Int input for mode";
+    doc.AddMember(sl4n::kResultStr, false, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kInvalidParamStr, doc.GetAllocator());
+    return;
+  } else {
+    mode = doc[sl4n::kParamsStr][0].GetInt();
+  }
+  if (!doc[sl4n::kParamsStr][1].IsInt()) {
+    LOG(ERROR) << sl4n::kTagStr << ": Expected Int input for timeout";
+    doc.AddMember(sl4n::kResultStr, false, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kInvalidParamStr, doc.GetAllocator());
+    return;
+  } else {
+    timeout_seconds = doc[sl4n::kParamsStr][1].GetInt();
+  }
+  if (!doc[sl4n::kParamsStr][2].IsInt()) {
+    LOG(ERROR) << sl4n::kTagStr << ": Expected Int input for tx power level";
+    doc.AddMember(sl4n::kResultStr, false, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kInvalidParamStr, doc.GetAllocator());
+    return;
+  } else {
+    tx_power_level = doc[sl4n::kParamsStr][2].GetInt();
+  }
+  if (!doc[sl4n::kParamsStr][3].IsBool()) {
+    LOG(ERROR) << sl4n::kTagStr << ": Expected Bool input for connectable";
+    doc.AddMember(sl4n::kResultStr, false, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kInvalidParamStr, doc.GetAllocator());
+    return;
+  } else {
+    is_connectable = doc[sl4n::kParamsStr][3].GetBool();
+  }
+
+  int adv_settings;
+  int error_code;
+  std::tie(adv_settings, error_code) = bt_binder.BluetoothBinderSetAdvSettings(
+    mode, timeout_seconds, tx_power_level, is_connectable);
+  if(error_code == sl4n_error_codes::kFailInt) {
+    doc.AddMember(
+      sl4n::kResultStr, sl4n_error_codes::kFailInt, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kFailedCounterInt, doc.GetAllocator());
+    return;
+  } else {
+    doc.AddMember(sl4n::kResultStr, adv_settings, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, NULL, doc.GetAllocator());
+  }
+}
+
+// End Wrappers ... I'm not a large water dwelling mammal...
+
+CommandReceiver::CommandReceiver() {
+  _funcMap.insert(std::make_pair("initiate", &initiate));
+  _funcMap.insert(std::make_pair("BluetoothBinderInitInterface",
+    &bluetooth_binder_init_interface_wapper));
+  _funcMap.insert(std::make_pair("BluetoothBinderGetName",
+    &bluetooth_binder_get_local_name_wrapper));
+  _funcMap.insert(std::make_pair("BluetoothBinderSetName",
+    &bluetooth_binder_set_local_name_wrapper));
+  _funcMap.insert(std::make_pair("BluetoothBinderGetAddress",
+    &bluetooth_binder_get_local_address_wrapper));
+  _funcMap.insert(std::make_pair("BluetoothBinderEnable",
+    &bluetooth_binder_enable_wrapper));
+  _funcMap.insert(std::make_pair("BluetoothBinderRegisterBLE",
+    &bluetooth_binder_register_ble_wrapper));
+  _funcMap.insert(std::make_pair("BluetoothBinderSetAdvSettings",
+    &bluetooth_binder_set_adv_settings_wrapper));
+}
+
+void CommandReceiver::Call(rapidjson::Document& doc) {
+  std::string cmd;
+  if (doc.HasMember(sl4n::kCmdStr)) {
+    cmd = doc[sl4n::kCmdStr].GetString();
+  } else if (doc.HasMember(sl4n::kMethodStr)) {
+    cmd = doc[sl4n::kMethodStr].GetString();
+  }
+
+  function_map::const_iterator iter = _funcMap.find(cmd);
+  if (iter != _funcMap.end()) {
+    iter->second(doc);
+  }
+  _clean_result(doc);
+}
diff --git a/sl4n/utils/command_receiver.h b/sl4n/utils/command_receiver.h
new file mode 100644
index 0000000..b2e9531
--- /dev/null
+++ b/sl4n/utils/command_receiver.h
@@ -0,0 +1,37 @@
+//
+//  Copyright (C) 2015 Google, Inc.
+//
+//  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.
+//
+
+#pragma once
+
+#include <rapidjson/document.h>
+
+// This class defines the functions that interact with the input JSON and
+// correspondingly calls the facade associated with the input JSON doc. This
+// class also contains wrapper functions to the actual SL4N Facades and does
+// pre-verification before it directly interacts with the facade. The
+// pre-verification includes matching parameter size and verifying each
+// parameter type that is expected in the wrapping function.
+class CommandReceiver {
+
+ public:
+  CommandReceiver();
+  ~CommandReceiver();
+
+  // Function that extracts the method/cmd parameter from the JSON doc and
+  // passes the document to the corresponding wrapper function.
+  void Call(rapidjson::Document& doc);
+
+};
diff --git a/sl4n/utils/common_utils.cpp b/sl4n/utils/common_utils.cpp
new file mode 100644
index 0000000..30b3258
--- /dev/null
+++ b/sl4n/utils/common_utils.cpp
@@ -0,0 +1,33 @@
+//
+//  Copyright (C) 2015 Google, Inc.
+//
+//  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 "base.h"
+#include <base/logging.h>
+#include "common_utils.h"
+#include <rapidjson/document.h>
+
+bool CommonUtils::IsParamLengthMatching(rapidjson::Document& doc,
+  int expected_param_size) {
+
+  if ((int)doc[sl4n::kParamsStr].Size() != expected_param_size) {
+    LOG(ERROR) << sl4n::kTagStr << ": Invalid parameter length - found: "
+      << doc[sl4n::kParamsStr].Size();
+    doc.AddMember(sl4n::kResultStr, false, doc.GetAllocator());
+    doc.AddMember(sl4n::kErrorStr, sl4n::kInvalidParamStr, doc.GetAllocator());
+    return false;
+  }
+  return true;
+}
diff --git a/sl4n/utils/common_utils.h b/sl4n/utils/common_utils.h
new file mode 100644
index 0000000..8b6285f
--- /dev/null
+++ b/sl4n/utils/common_utils.h
@@ -0,0 +1,28 @@
+//
+//  Copyright (C) 2015 Google, Inc.
+//
+//  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.
+//
+
+#pragma once
+
+#include <rapidjson/document.h>
+
+// This class defines common utils to be used by SL4N.
+class CommonUtils {
+ public:
+
+  // Returns true if parameters from JSON matches the expected parameter size.
+  static bool IsParamLengthMatching(rapidjson::Document& doc,
+    int expected_param_size);
+};