am 8374641d: Merge "Support for LTE/WCDMA mode"
* commit '8374641d142f0cdc05019d52587e492bad83bc72':
Support for LTE/WCDMA mode
diff --git a/mock-ril/src/cpp/logging.h b/include/telephony/librilutils.h
similarity index 60%
copy from mock-ril/src/cpp/logging.h
copy to include/telephony/librilutils.h
index 602fbf2..d06b3e9 100644
--- a/mock-ril/src/cpp/logging.h
+++ b/include/telephony/librilutils.h
@@ -1,5 +1,5 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
+/*
+ * Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,12 +14,25 @@
* limitations under the License.
*/
-#ifndef _LOGGING_H
-#define _LOGGING_H
+#ifndef LIBRILUTILS_H
+#define LIBRILUTILS_H
-// The LOG_TAG should start with "RIL" so it shows up in the radio log
-#define LOG_TAG "RIL-MOCK"
+#include <stdint.h>
-#include <utils/Log.h>
-
+#ifdef __cplusplus
+extern "C" {
#endif
+
+/**
+ * Return system time in nanos.
+ *
+ * This is a monotonicly increasing clock and
+ * return the same value as System.nanoTime in java.
+ */
+uint64_t ril_nano_time();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // LIBRILUTILS_H
diff --git a/include/telephony/ril.h b/include/telephony/ril.h
index d26b8ed..9ce86de 100644
--- a/include/telephony/ril.h
+++ b/include/telephony/ril.h
@@ -18,6 +18,7 @@
#define ANDROID_RIL_H 1
#include <stdlib.h>
+#include <stdint.h>
#ifndef FEATURE_UNIT_TEST
#include <sys/time.h>
#endif /* !FEATURE_UNIT_TEST */
@@ -26,7 +27,7 @@
extern "C" {
#endif
-#define RIL_VERSION 7 /* Current version */
+#define RIL_VERSION 8 /* Current version */
#define RIL_VERSION_MIN 6 /* Minimum RIL_VERSION supported */
#define CDMA_ALPHA_INFO_BUFFER_LENGTH 64
@@ -209,7 +210,7 @@
The unit is miliseconds.
The value < 0 means no value is suggested.
The value 0 means retry should be done ASAP.
- The value of MAX_INT(0x7fffffff) means no retry. */
+ The value of INT_MAX(0x7fffffff) means no retry. */
int cid; /* Context ID, uniquely identifies this call */
int active; /* 0=inactive, 1=active/physical link down, 2=active/physical link up */
char * type; /* One of the PDP_type values in TS 27.007 section 10.1.1.
@@ -637,6 +638,10 @@
int bitErrorRate; /* bit error rate (0-7, 99) as defined in TS 27.007 8.5 */
} RIL_GW_SignalStrength;
+typedef struct {
+ int signalStrength; /* Valid values are (0-31, 99) as defined in TS 27.007 8.5 */
+ int bitErrorRate; /* bit error rate (0-7, 99) as defined in TS 27.007 8.5 */
+} RIL_SignalStrengthWcdma;
typedef struct {
int dbm; /* Valid values are positive integers. This value is the actual RSSI value
@@ -682,6 +687,32 @@
* Reference: 3GPP TS 36.101 9.2, 9.3, A.4 */
} RIL_LTE_SignalStrength;
+typedef struct {
+ int signalStrength; /* Valid values are (0-31, 99) as defined in TS 27.007 8.5 */
+ int rsrp; /* The current Reference Signal Receive Power in dBm multipled by -1.
+ * Range: 44 to 140 dBm
+ * INT_MAX: 0x7FFFFFFF denotes invalid value.
+ * Reference: 3GPP TS 36.133 9.1.4 */
+ int rsrq; /* The current Reference Signal Receive Quality in dB multiplied by -1.
+ * Range: 20 to 3 dB.
+ * INT_MAX: 0x7FFFFFFF denotes invalid value.
+ * Reference: 3GPP TS 36.133 9.1.7 */
+ int rssnr; /* The current reference signal signal-to-noise ratio in 0.1 dB units.
+ * Range: -200 to +300 (-200 = -20.0 dB, +300 = 30dB).
+ * INT_MAX : 0x7FFFFFFF denotes invalid value.
+ * Reference: 3GPP TS 36.101 8.1.1 */
+ int cqi; /* The current Channel Quality Indicator.
+ * Range: 0 to 15.
+ * INT_MAX : 0x7FFFFFFF denotes invalid value.
+ * Reference: 3GPP TS 36.101 9.2, 9.3, A.4 */
+ int timingAdvance; /* timing advance in micro seconds for a one way trip from cell to device.
+ * Approximate distance can be calculated using 300m/us * timingAdvance.
+ * Range: 0 to 0x7FFFFFFE
+ * INT_MAX : 0x7FFFFFFF denotes invalid value.
+ * Reference: 3GPP 36.321 section 6.1.3.5
+ * also: http://www.cellular-planningoptimization.com/2010/02/timing-advance-with-calculation.html */
+} RIL_LTE_SignalStrength_v8;
+
/* Deprecated, use RIL_SignalStrength_v6 */
typedef struct {
RIL_GW_SignalStrength GW_SignalStrength;
@@ -696,6 +727,110 @@
RIL_LTE_SignalStrength LTE_SignalStrength;
} RIL_SignalStrength_v6;
+typedef struct {
+ RIL_GW_SignalStrength GW_SignalStrength;
+ RIL_CDMA_SignalStrength CDMA_SignalStrength;
+ RIL_EVDO_SignalStrength EVDO_SignalStrength;
+ RIL_LTE_SignalStrength_v8 LTE_SignalStrength;
+} RIL_SignalStrength_v8;
+
+/** RIL_CellIdentityGsm */
+typedef struct {
+ int mcc; /* 3-digit Mobile Country Code, 0..999, INT_MAX if unknown */
+ int mnc; /* 2 or 3-digit Mobile Network Code, 0..999, INT_MAX if unknown */
+ int lac; /* 16-bit Location Area Code, 0..65535, INT_MAX if unknown */
+ int cid; /* 16-bit GSM Cell Identity described in TS 27.007, 0..65535, INT_MAX if unknown */
+} RIL_CellIdentityGsm;
+
+/** RIL_CellIdentityWcdma */
+typedef struct {
+ int mcc; /* 3-digit Mobile Country Code, 0..999, INT_MAX if unknown */
+ int mnc; /* 2 or 3-digit Mobile Network Code, 0..999, INT_MAX if unknown */
+ int lac; /* 16-bit Location Area Code, 0..65535, INT_MAX if unknown */
+ int cid; /* 28-bit UMTS Cell Identity described in TS 25.331, 0..268435455, INT_MAX if unknown */
+ int psc; /* 9-bit UMTS Primary Scrambling Code described in TS 25.331, 0..511, INT_MAX if unknown */
+} RIL_CellIdentityWcdma;
+
+/** RIL_CellIdentityCdma */
+typedef struct {
+ int networkId; /* Network Id 0..65535, INT_MAX if unknown */
+ int systemId; /* CDMA System Id 0..32767, INT_MAX if unknown */
+ int basestationId; /* Base Station Id 0..65535, INT_MAX if unknown */
+ int longitude; /* Longitude is a decimal number as specified in 3GPP2 C.S0005-A v6.0.
+ * It is represented in units of 0.25 seconds and ranges from -2592000
+ * to 2592000, both values inclusive (corresponding to a range of -180
+ * to +180 degrees). INT_MAX if unknown */
+
+ int latitude; /* Latitude is a decimal number as specified in 3GPP2 C.S0005-A v6.0.
+ * It is represented in units of 0.25 seconds and ranges from -1296000
+ * to 1296000, both values inclusive (corresponding to a range of -90
+ * to +90 degrees). INT_MAX if unknown */
+} RIL_CellIdentityCdma;
+
+/** RIL_CellIdentityLte */
+typedef struct {
+ int mcc; /* 3-digit Mobile Country Code, 0..999, INT_MAX if unknown */
+ int mnc; /* 2 or 3-digit Mobile Network Code, 0..999, INT_MAX if unknown */
+ int ci; /* 28-bit Cell Identity described in TS ???, INT_MAX if unknown */
+ int pci; /* physical cell id 0..503, INT_MAX if unknown */
+ int tac; /* 16-bit tracking area code, INT_MAX if unknown */
+} RIL_CellIdentityLte;
+
+/** RIL_CellInfoGsm */
+typedef struct {
+ RIL_CellIdentityGsm cellIdentityGsm;
+ RIL_GW_SignalStrength signalStrengthGsm;
+} RIL_CellInfoGsm;
+
+/** RIL_CellInfoWcdma */
+typedef struct {
+ RIL_CellIdentityWcdma cellIdentityWcdma;
+ RIL_SignalStrengthWcdma signalStrengthWcdma;
+} RIL_CellInfoWcdma;
+
+/** RIL_CellInfoCdma */
+typedef struct {
+ RIL_CellIdentityCdma cellIdentityCdma;
+ RIL_CDMA_SignalStrength signalStrengthCdma;
+ RIL_EVDO_SignalStrength signalStrengthEvdo;
+} RIL_CellInfoCdma;
+
+/** RIL_CellInfoLte */
+typedef struct {
+ RIL_CellIdentityLte cellIdentityLte;
+ RIL_LTE_SignalStrength_v8 signalStrengthLte;
+} RIL_CellInfoLte;
+
+// Must be the same as CellInfo.TYPE_XXX
+typedef enum {
+ RIL_CELL_INFO_TYPE_GSM = 1,
+ RIL_CELL_INFO_TYPE_CDMA = 2,
+ RIL_CELL_INFO_TYPE_LTE = 3,
+ RIL_CELL_INFO_TYPE_WCDMA = 4,
+} RIL_CellInfoType;
+
+// Must be the same as CellInfo.TIMESTAMP_TYPE_XXX
+typedef enum {
+ RIL_TIMESTAMP_TYPE_UNKNOWN = 0,
+ RIL_TIMESTAMP_TYPE_ANTENNA = 1,
+ RIL_TIMESTAMP_TYPE_MODEM = 2,
+ RIL_TIMESTAMP_TYPE_OEM_RIL = 3,
+ RIL_TIMESTAMP_TYPE_JAVA_RIL = 4,
+} RIL_TimeStampType;
+
+typedef struct {
+ RIL_CellInfoType cellInfoType; /* cell type for selecting from union CellInfo */
+ int registered; /* !0 if this cell is registered 0 if not registered */
+ RIL_TimeStampType timeStampType; /* type of time stamp represented by timeStamp */
+ uint64_t timeStamp; /* Time in nanos as returned by ril_nano_time */
+ union {
+ RIL_CellInfoGsm gsm;
+ RIL_CellInfoCdma cdma;
+ RIL_CellInfoLte lte;
+ RIL_CellInfoWcdma wcdma;
+ } CellInfo;
+} RIL_CellInfo;
+
/* Names of the CDMA info records (C.S0005 section 3.7.5) */
typedef enum {
RIL_CDMA_DISPLAY_INFO_REC,
@@ -3314,6 +3449,39 @@
*/
#define RIL_REQUEST_VOICE_RADIO_TECH 108
+/**
+ * RIL_REQUEST_GET_CELL_INFO_LIST
+ *
+ * Request all of the current cell information known to the radio. The radio
+ * must a list of all current cells, including the neighboring cells. If for a particular
+ * cell information isn't known then the appropriate unknown value will be returned.
+ * This does not cause or change the rate of RIL_UNSOL_CELL_INFO_LIST.
+ *
+ * "data" is NULL
+ *
+ * "response" is an array of RIL_CellInfo.
+ */
+#define RIL_REQUEST_GET_CELL_INFO_LIST 109
+
+/**
+ * RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE
+ *
+ * Sets the minimum time between when RIL_UNSOL_CELL_INFO_LIST should be invoked.
+ * A value of 0, means invoke RIL_UNSOL_CELL_INFO_LIST when any of the reported
+ * information changes. Setting the value to INT_MAX(0x7fffffff) means never issue
+ * a RIL_UNSOL_CELL_INFO_LIST.
+ *
+ * "data" is int *
+ * ((int *)data)[0] is minimum time in milliseconds
+ *
+ * "response" is NULL
+ *
+ * Valid errors:
+ * SUCCESS
+ * RADIO_NOT_AVAILABLE
+ * GENERIC_FAILURE
+ */
+#define RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE 110
/***********************************************************************/
@@ -3793,6 +3961,17 @@
*/
#define RIL_UNSOL_VOICE_RADIO_TECH_CHANGED 1035
+/**
+ * RIL_UNSOL_CELL_INFO_LIST
+ *
+ * Same information as returned by RIL_REQUEST_GET_CELL_INFO_LIST, but returned
+ * at the rate no greater than specified by RIL_REQUEST_SET_UNSOL_CELL_INFO_RATE.
+ *
+ * "data" is NULL
+ *
+ * "response" is an array of RIL_CellInfo.
+ */
+#define RIL_UNSOL_CELL_INFO_LIST 1036
/***********************************************************************/
diff --git a/libril/Android.mk b/libril/Android.mk
index cba6c88..b099d4b 100644
--- a/libril/Android.mk
+++ b/libril/Android.mk
@@ -8,6 +8,7 @@
ril_event.cpp
LOCAL_SHARED_LIBRARIES := \
+ liblog \
libutils \
libbinder \
libcutils \
diff --git a/libril/ril.cpp b/libril/ril.cpp
index 41e2fd2..bd83654 100644
--- a/libril/ril.cpp
+++ b/libril/ril.cpp
@@ -31,6 +31,7 @@
#include <cutils/jstring.h>
#include <sys/types.h>
+#include <sys/limits.h>
#include <pwd.h>
#include <stdio.h>
@@ -233,6 +234,7 @@
static int responseCdmaSignalInfoRecord(Parcel &p,void *response, size_t responselen);
static int responseCdmaCallWaiting(Parcel &p,void *response, size_t responselen);
static int responseSimRefresh(Parcel &p, void *response, size_t responselen);
+static int responseCellInfoList(Parcel &p, void *response, size_t responselen);
static int decodeVoiceRadioTechnology (RIL_RadioState radioState);
static int decodeCdmaSubscriptionSource (RIL_RadioState radioState);
@@ -1999,22 +2001,43 @@
p.writeInt32(p_cur->EVDO_SignalStrength.ecio);
p.writeInt32(p_cur->EVDO_SignalStrength.signalNoiseRatio);
if (responselen >= sizeof (RIL_SignalStrength_v6)) {
- p.writeInt32(p_cur->LTE_SignalStrength.signalStrength);
-
/*
- * ril version <=6 receives negative values for rsrp
- * workaround for backward compatibility
+ * Fixup LTE for backwards compatibility
*/
- p_cur->LTE_SignalStrength.rsrp =
- ((s_callbacks.version <= 6) && (p_cur->LTE_SignalStrength.rsrp < 0 )) ?
- -(p_cur->LTE_SignalStrength.rsrp) : p_cur->LTE_SignalStrength.rsrp;
+ if (s_callbacks.version <= 6) {
+ // signalStrength: -1 -> 99
+ if (p_cur->LTE_SignalStrength.signalStrength == -1) {
+ p_cur->LTE_SignalStrength.signalStrength = 99;
+ }
+ // rsrp: -1 -> INT_MAX all other negative value to positive.
+ // So remap here
+ if (p_cur->LTE_SignalStrength.rsrp == -1) {
+ p_cur->LTE_SignalStrength.rsrp = INT_MAX;
+ } else if (p_cur->LTE_SignalStrength.rsrp < -1) {
+ p_cur->LTE_SignalStrength.rsrp = -p_cur->LTE_SignalStrength.rsrp;
+ }
+ // rsrq: -1 -> INT_MAX
+ if (p_cur->LTE_SignalStrength.rsrq == -1) {
+ p_cur->LTE_SignalStrength.rsrq = INT_MAX;
+ }
+ // Not remapping rssnr is already using INT_MAX
+ // cqi: -1 -> INT_MAX
+ if (p_cur->LTE_SignalStrength.cqi == -1) {
+ p_cur->LTE_SignalStrength.cqi = INT_MAX;
+ }
+ }
+ p.writeInt32(p_cur->LTE_SignalStrength.signalStrength);
p.writeInt32(p_cur->LTE_SignalStrength.rsrp);
p.writeInt32(p_cur->LTE_SignalStrength.rsrq);
p.writeInt32(p_cur->LTE_SignalStrength.rssnr);
p.writeInt32(p_cur->LTE_SignalStrength.cqi);
} else {
- memset(&p_cur->LTE_SignalStrength, sizeof (RIL_LTE_SignalStrength), 0);
+ p.writeInt32(99);
+ p.writeInt32(INT_MAX);
+ p.writeInt32(INT_MAX);
+ p.writeInt32(INT_MAX);
+ p.writeInt32(INT_MAX);
}
startResponse;
@@ -2163,6 +2186,137 @@
return 0;
}
+static int responseCellInfoList(Parcel &p, void *response, size_t responselen)
+{
+ if (response == NULL && responselen != 0) {
+ RLOGE("invalid response: NULL");
+ return RIL_ERRNO_INVALID_RESPONSE;
+ }
+
+ if (responselen % sizeof(RIL_CellInfo) != 0) {
+ RLOGE("invalid response length %d expected multiple of %d",
+ (int)responselen, (int)sizeof(RIL_CellInfo));
+ return RIL_ERRNO_INVALID_RESPONSE;
+ }
+
+ int num = responselen / sizeof(RIL_CellInfo);
+ p.writeInt32(num);
+
+ RIL_CellInfo *p_cur = (RIL_CellInfo *) response;
+ startResponse;
+ int i;
+ for (i = 0; i < num; i++) {
+ appendPrintBuf("%s[%d: type=%d,registered=%d,timeStampType=%d,timeStamp=%lld", printBuf, i,
+ p_cur->cellInfoType, p_cur->registered, p_cur->timeStampType, p_cur->timeStamp);
+ p.writeInt32((int)p_cur->cellInfoType);
+ p.writeInt32(p_cur->registered);
+ p.writeInt32(p_cur->timeStampType);
+ p.writeInt64(p_cur->timeStamp);
+ switch(p_cur->cellInfoType) {
+ case RIL_CELL_INFO_TYPE_GSM: {
+ appendPrintBuf("%s GSM id: mcc=%d,mnc=%d,lac=%d,cid=%d,", printBuf,
+ p_cur->CellInfo.gsm.cellIdentityGsm.mcc,
+ p_cur->CellInfo.gsm.cellIdentityGsm.mnc,
+ p_cur->CellInfo.gsm.cellIdentityGsm.lac,
+ p_cur->CellInfo.gsm.cellIdentityGsm.cid);
+ appendPrintBuf("%s gsmSS: ss=%d,ber=%d],", printBuf,
+ p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength,
+ p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
+
+ p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mcc);
+ p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mnc);
+ p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.lac);
+ p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.cid);
+ p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength);
+ p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
+ break;
+ }
+ case RIL_CELL_INFO_TYPE_WCDMA: {
+ appendPrintBuf("%s WCDMA id: mcc=%d,mnc=%d,lac=%d,cid=%d,psc=%d,", printBuf,
+ p_cur->CellInfo.wcdma.cellIdentityWcdma.mcc,
+ p_cur->CellInfo.wcdma.cellIdentityWcdma.mnc,
+ p_cur->CellInfo.wcdma.cellIdentityWcdma.lac,
+ p_cur->CellInfo.wcdma.cellIdentityWcdma.cid,
+ p_cur->CellInfo.wcdma.cellIdentityWcdma.psc);
+ appendPrintBuf("%s wcdmaSS: ss=%d,ber=%d],", printBuf,
+ p_cur->CellInfo.wcdma.signalStrengthWcdma.signalStrength,
+ p_cur->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
+
+ p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mcc);
+ p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mnc);
+ p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.lac);
+ p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.cid);
+ p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.psc);
+ p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.signalStrength);
+ p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
+ break;
+ }
+ case RIL_CELL_INFO_TYPE_CDMA: {
+ appendPrintBuf("%s CDMA id: nId=%d,sId=%d,bsId=%d,long=%d,lat=%d", printBuf,
+ p_cur->CellInfo.cdma.cellIdentityCdma.networkId,
+ p_cur->CellInfo.cdma.cellIdentityCdma.systemId,
+ p_cur->CellInfo.cdma.cellIdentityCdma.basestationId,
+ p_cur->CellInfo.cdma.cellIdentityCdma.longitude,
+ p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
+
+ p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.networkId);
+ p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.systemId);
+ p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.basestationId);
+ p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.longitude);
+ p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
+
+ appendPrintBuf("%s cdmaSS: dbm=%d ecio=%d evdoSS: dbm=%d,ecio=%d,snr=%d", printBuf,
+ p_cur->CellInfo.cdma.signalStrengthCdma.dbm,
+ p_cur->CellInfo.cdma.signalStrengthCdma.ecio,
+ p_cur->CellInfo.cdma.signalStrengthEvdo.dbm,
+ p_cur->CellInfo.cdma.signalStrengthEvdo.ecio,
+ p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
+
+ p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.dbm);
+ p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.ecio);
+ p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.dbm);
+ p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.ecio);
+ p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
+ break;
+ }
+ case RIL_CELL_INFO_TYPE_LTE: {
+ appendPrintBuf("%s LTE id: mcc=%d,mnc=%d,ci=%d,pci=%d,tac=%d", printBuf,
+ p_cur->CellInfo.lte.cellIdentityLte.mcc,
+ p_cur->CellInfo.lte.cellIdentityLte.mnc,
+ p_cur->CellInfo.lte.cellIdentityLte.ci,
+ p_cur->CellInfo.lte.cellIdentityLte.pci,
+ p_cur->CellInfo.lte.cellIdentityLte.tac);
+
+ p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mcc);
+ p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mnc);
+ p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.ci);
+ p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.pci);
+ p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.tac);
+
+ appendPrintBuf("%s lteSS: ss=%d,rsrp=%d,rsrq=%d,rssnr=%d,cqi=%d,ta=%d", printBuf,
+ p_cur->CellInfo.lte.signalStrengthLte.signalStrength,
+ p_cur->CellInfo.lte.signalStrengthLte.rsrp,
+ p_cur->CellInfo.lte.signalStrengthLte.rsrq,
+ p_cur->CellInfo.lte.signalStrengthLte.rssnr,
+ p_cur->CellInfo.lte.signalStrengthLte.cqi,
+ p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
+ p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.signalStrength);
+ p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrp);
+ p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrq);
+ p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rssnr);
+ p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.cqi);
+ p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
+ break;
+ }
+ }
+ p_cur += 1;
+ }
+ removeLastChar;
+ closeResponse;
+
+ return 0;
+}
+
static void triggerEvLoop() {
int ret;
if (!pthread_equal(pthread_self(), s_tid_dispatch)) {
@@ -3445,6 +3599,8 @@
case RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU: return "RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU";
case RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS: return "RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS";
case RIL_REQUEST_VOICE_RADIO_TECH: return "VOICE_RADIO_TECH";
+ case RIL_REQUEST_GET_CELL_INFO_LIST: return"GET_CELL_INFO_LIST";
+ case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE: return"SET_UNSOL_CELL_INFO_LIST_RATE";
case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED: return "UNSOL_RESPONSE_RADIO_STATE_CHANGED";
case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED: return "UNSOL_RESPONSE_CALL_STATE_CHANGED";
case RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED: return "UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED";
@@ -3480,6 +3636,7 @@
case RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE: return "UNSOL_EXIT_EMERGENCY_CALLBACK_MODE";
case RIL_UNSOL_RIL_CONNECTED: return "UNSOL_RIL_CONNECTED";
case RIL_UNSOL_VOICE_RADIO_TECH_CHANGED: return "UNSOL_VOICE_RADIO_TECH_CHANGED";
+ case RIL_UNSOL_CELL_INFO_LIST: return "UNSOL_CELL_INFO_LIST";
default: return "<unknown request>";
}
}
diff --git a/libril/ril_commands.h b/libril/ril_commands.h
index 069ee75..0519a2a 100644
--- a/libril/ril_commands.h
+++ b/libril/ril_commands.h
@@ -123,3 +123,5 @@
{RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU, dispatchStrings, responseVoid},
{RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS, dispatchString, responseSIM_IO},
{RIL_REQUEST_VOICE_RADIO_TECH, dispatchVoiceRadioTech, responseInts},
+ {RIL_REQUEST_GET_CELL_INFO_LIST, dispatchVoid, responseCellInfoList},
+ {RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE, dispatchInts, responseVoid},
diff --git a/libril/ril_unsol_commands.h b/libril/ril_unsol_commands.h
index 7e3f8f0..0711225 100644
--- a/libril/ril_unsol_commands.h
+++ b/libril/ril_unsol_commands.h
@@ -50,3 +50,4 @@
{RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE, responseVoid, WAKE_PARTIAL},
{RIL_UNSOL_RIL_CONNECTED, responseInts, WAKE_PARTIAL},
{RIL_UNSOL_VOICE_RADIO_TECH_CHANGED, responseInts, WAKE_PARTIAL},
+ {RIL_UNSOL_CELL_INFO_LIST, responseCellInfoList, WAKE_PARTIAL},
diff --git a/librilutils/Android.mk b/librilutils/Android.mk
new file mode 100644
index 0000000..a959202
--- /dev/null
+++ b/librilutils/Android.mk
@@ -0,0 +1,33 @@
+# Copyright 2013 The Android Open Source Project
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+ librilutils.c
+
+LOCAL_CFLAGS :=
+
+LOCAL_MODULE:= librilutils
+
+LOCAL_LDLIBS += -lpthread
+
+include $(BUILD_SHARED_LIBRARY)
+
+
+# Create static library for those that want it
+# =========================================
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+ librilutils.c
+
+LOCAL_STATIC_LIBRARIES :=
+
+LOCAL_CFLAGS :=
+
+LOCAL_MODULE:= librilutils_static
+
+LOCAL_LDLIBS += -lpthread
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/mock-ril/src/cpp/logging.h b/librilutils/librilutils.c
similarity index 67%
rename from mock-ril/src/cpp/logging.h
rename to librilutils/librilutils.c
index 602fbf2..b1b930e 100644
--- a/mock-ril/src/cpp/logging.h
+++ b/librilutils/librilutils.c
@@ -1,5 +1,5 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
+/*
+ * Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,12 +14,11 @@
* limitations under the License.
*/
-#ifndef _LOGGING_H
-#define _LOGGING_H
+#include <telephony/librilutils.h>
+#include <time.h>
-// The LOG_TAG should start with "RIL" so it shows up in the radio log
-#define LOG_TAG "RIL-MOCK"
-
-#include <utils/Log.h>
-
-#endif
+uint64_t ril_nano_time() {
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ return now.tv_sec * 1000000000LL + now.tv_nsec;
+}
diff --git a/mock-ril/.gitignore b/mock-ril/.gitignore
deleted file mode 100644
index d18402d..0000000
--- a/mock-ril/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-*.pyc
-.*.swp
diff --git a/mock-ril/Android.mk b/mock-ril/Android.mk
deleted file mode 100644
index 0560de1..0000000
--- a/mock-ril/Android.mk
+++ /dev/null
@@ -1,86 +0,0 @@
-# Copyright 2010 The Android Open Source Project
-#
-# not currently building V8 for x86 targets
-
-LOCAL_PATH:= $(call my-dir)
-
-# Directories of source files
-src_cpp := src/cpp
-src_java := src/java
-src_py := src/py
-src_js := src/js
-src_proto := src/proto
-
-ifneq ($(TARGET_BUILD_PDK), true)
-ifeq ($(TARGET_ARCH),arm)
-# Mock-ril only buid for debug variants
-ifneq ($(filter userdebug eng tests, $(TARGET_BUILD_VARIANT)),)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES:= \
- $(src_cpp)/ctrl_server.cpp \
- $(src_cpp)/experiments.cpp \
- $(src_cpp)/js_support.cpp \
- $(src_cpp)/mock_ril.cpp \
- $(src_cpp)/node_buffer.cpp \
- $(src_cpp)/node_util.cpp \
- $(src_cpp)/protobuf_v8.cpp \
- $(src_cpp)/responses.cpp \
- $(src_cpp)/requests.cpp \
- $(src_cpp)/util.cpp \
- $(src_cpp)/worker.cpp \
- $(src_cpp)/worker_v8.cpp \
- $(call all-proto-files-under, $(src_proto))
-
-LOCAL_SHARED_LIBRARIES := \
- libz libcutils libutils libril
-
-LOCAL_STATIC_LIBRARIES := \
- libv8
-
-LOCAL_CFLAGS := -D_GNU_SOURCE -UNDEBUG -DRIL_SHLIB
-
-LOCAL_C_INCLUDES := \
- $(LOCAL_PATH)/$(src_cpp) \
- external/v8/include \
- bionic \
- $(KERNEL_HEADERS)
-
-LOCAL_SHARED_LIBRARIES += libstlport
-LOCAL_C_INCLUDES += external/stlport/stlport
-
-# __BSD_VISIBLE for htolexx macros.
-LOCAL_STRIP_MODULE := true
-
-LOCAL_LDLIBS += -lpthread
-LOCAL_CFLAGS += -DMOCK_RIL -D__BSD_VISIBLE
-LOCAL_PROTOC_OPTIMIZE_TYPE := full
-LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE:= libmock_ril
-
-include $(BUILD_SHARED_LIBRARY)
-
-endif
-endif
-
-# Java librilproto
-# =======================================================
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := librilproto-java
-
-LOCAL_PROTOC_OPTIMIZE_TYPE := micro
-
-LOCAL_SRC_FILES := $(call all-java-files-under, $(src_java)) \
- $(call all-proto-files-under, $(src_proto))
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-# =======================================================
-
-endif
-
-src_cpp :=
-src_java :=
-src_py :=
-src_js :=
-src_proto :=
diff --git a/mock-ril/MODULE_LICENSE_APACHE2 b/mock-ril/MODULE_LICENSE_APACHE2
deleted file mode 100644
index e69de29..0000000
--- a/mock-ril/MODULE_LICENSE_APACHE2
+++ /dev/null
diff --git a/mock-ril/Makefile b/mock-ril/Makefile
deleted file mode 100644
index d85c2cf..0000000
--- a/mock-ril/Makefile
+++ /dev/null
@@ -1,154 +0,0 @@
-# This has various targets to assist in developing
-# and testing the mock ril. The default "all" target
-# invokes protoc to generate the appropriate protobuf
-# code. The other targest are used for testing.
-
-# Assume this Makefile is run in place then top
-# point to the top of the android source tree
-top=../../../
-
-PROTOC=$(wildcard $(top)out/host/*/bin/aprotoc)
-#if ((($(words $(PROTO)) != 1)))
-ifneq ($(words $(PROTOC)),1)
-$(error expecting 1 protoc we have $(words $(PROTOC)), PROTOC='$(PROTOC)')
-endif
-
-ifeq ("$(ANDROID_DEVICE)","")
-$(warning Default to ANDROID_DEVICE=passion")
-ANDROID_DEVICE=passion
-endif
-
-# Directories of source files
-device=$(ANDROID_DEVICE)
-src_js=src/js
-src_proto=src/proto
-src_generated=$(top)out/target/product/$(device)/obj/SHARED_LIBRARIES/libmock_ril_intermediates/proto/hardware/ril/mock-ril/src/proto
-
-# Directories of generated source files
-gen_src_py=$(src_generated)/python
-gen_src_desc=$(src_generated)/desc
-
-# Generated files
-generated=$(gen_src_desc)/msgheader.desc $(gen_src_py)/msgheader_pb2.py \
- $(gen_src_desc)/ril.desc $(gen_src_py)/ril_pb2.py \
- $(gen_src_desc)/ctrl.desc $(gen_src_py)/ctrl_pb2.py
-
-# A Makefile to run protoc and simplify testing.
-.PHONY : all
-all : $(generated)
-
-# TODO: Document/cleanup these testing targets as we learn whats needed.
-
-# Make the unit tests
-.PHONY : ut
-ut :
- source $(top)build/envsetup.sh ; mmm $(top)frameworks/base/telephony/tests/telephonytests
- adb install -r $(top)out/target/product/$(device)/data/app/FrameworksTelephonyTests.apk
-
-t : $(gen_src_desc)/msgheader.desc $(gen_src_py)/msgheader_pb2.py
-
-# Run protoc to create the descriptor files for msgheader
-$(gen_src_desc)/msgheader.desc : $(src_proto)/msgheader.proto
- mkdir -p $(gen_src_desc)
- $(PROTOC) --descriptor_set_out=$@ --proto_path=$(src_proto) --include_imports $<
-
-# Run protoc to create the python files for msgheader
-$(gen_src_py)/msgheader_pb2.py : $(src_proto)/msgheader.proto
- mkdir -p $(gen_src_py)
- $(PROTOC) --python_out=$(gen_src_py) --proto_path=$(src_proto) $<
-
-# Run protoc to create the ril descriptor file for ril
-$(gen_src_desc)/ril.desc : $(src_proto)/ril.proto
- mkdir -p $(gen_src_desc)
- $(PROTOC) --descriptor_set_out=$@ --proto_path=$(src_proto) --include_imports $<
-
-# Run protoc to create the python files for ril
-$(gen_src_py)/ril_pb2.py : $(src_proto)/ril.proto
- mkdir -p $(gen_src_py)
- $(PROTOC) --python_out=$(gen_src_py) --proto_path=$(src_proto) $<
-
-# Run protoc to create the python files for control
-$(gen_src_py)/ctrl_pb2.py : $(src_proto)/ctrl.proto
- mkdir -p $(gen_src_py)
- $(PROTOC) --python_out=$(gen_src_py) --proto_path=$(top) --proto_path=$(src_proto) $<
-
-# Run protoc to create the ctrl descriptor file for control
-$(gen_src_desc)/ctrl.desc : $(src_proto)/ctrl.proto
- mkdir -p $(gen_src_desc)
- $(PROTOC) --descriptor_set_out=$@ --proto_path=$(top) --proto_path=$(src_proto) --include_imports $<
-
-# After starting phone do this first to get lastest ril.desc/proto and setup rild
-.PHONY : first
-first : root_remount copy_all forward
-
-# copy js and descriptors, restart rild and run mockril_tests
-.PHONY : tmr
-tmr : copy_js_desc restart_rild mockril_tests
-
-# Copy all files, restart rild and run mockril_tests
-.PHONY : test
-test : copy_all restart_rild install_mockril_tests mockril_tests
-
-# Restart rild
-.PHONY : restart_rild
-restart_rild :
- adb shell setprop ctl.restart ril-daemon
-
-# Update only the js/copy and restart rild
-.PHONY : tjs
-tjs : copy_js_desc restart_rild
-
-# Run test control server python script
-.PHONY : tcs
-tcs :
- ./tcs.py 127.0.0.1 11111
-
-# Run the mock ril tests (use adb shell pm list instrumentation to see the Runner)
-.PHONY : mockril_tests
-mockril_tests :
- adb shell am instrument -e class 'com.android.internal.telephony.mockril.MockRilTest' -w com.android.frameworks.telephonytests/.TelephonyMockRilTestRunner
-
-# forward the control server tcp port (54312) to a port on the PC side (11111)
-.PHONY : forward
-forward :
- adb forward tcp:11111 tcp:54312
-
-# change to root and remount device
-.PHONY : root_remount
-root_remount :
- adb root ; sleep 3 ; adb remount ; adb shell setprop rild.libpath /data/lib/libmock_ril.so
-
-# Copy all files
-.PHONY : copy_all
-copy_all : copy_js_desc copy_mockril
-
-# Copy js and the protobuf descriptor files
-.PHONY : copy_js_desc
-copy_js_desc :
- adb push $(src_js)/mock_ril.js /sdcard/data/
- adb push $(src_js)/mock_ril_tests.js /sdcard/data/
- adb push $(src_js)/simulated_radio.js /sdcard/data/
- adb push $(src_js)/simulated_radio_tests.js /sdcard/data/
- adb push $(src_js)/simulated_icc.js /sdcard/data/
- adb push $(src_js)/simulated_icc_tests.js /sdcard/data/
- adb push $(src_js)/ctrl_server.js /sdcard/data/
- adb push $(src_js)/ctrl_server_tests.js /sdcard/data/
- adb push $(src_js)/ril_vars.js /sdcard/data/
- adb push $(gen_src_desc)/ril.desc /sdcard/data/
- adb push $(gen_src_desc)/ctrl.desc /sdcard/data/
- adb forward tcp:11111 tcp:54312
-
-
-# Copy the mock ril library
-.PHONY : copy_mockril
-copy_mockril :
- adb push $(top)out/target/product/$(device)/system/lib/libmock_ril.so /data/lib/
-
-.PHONY : install_mockril_tests
-install_mockril_tests :
- adb install -r $(top)out/target/product/$(device)/data/app/FrameworksTelephonyTests.apk
-
-# Remove generated files
-.PHONY : clean
-clean :
- rm -f $(generated)
diff --git a/mock-ril/NOTICE b/mock-ril/NOTICE
deleted file mode 100644
index 15930fa..0000000
--- a/mock-ril/NOTICE
+++ /dev/null
@@ -1,221 +0,0 @@
-
- Copyright (c) 2005-2008, The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
-
- 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
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------
-The following files are copied from http://www.nodejs.obj and modified:
- node_buffer.h
- node_buffer.cc (renamed to node_buffer.cpp)
- node_object_wrap.h
-
-The following files are snippets from http://www.nodejs.obj node.cc/node.h
- node_util.h
- node_util.cpp
-
-
-Node's license follows:
-
-Copyright 2009, 2010 Ryan Lienhart Dahl. All rights reserved.
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-IN THE SOFTWARE.
--------------------------------------------------------------------------
diff --git a/mock-ril/README.txt b/mock-ril/README.txt
deleted file mode 100644
index 0b7bef6..0000000
--- a/mock-ril/README.txt
+++ /dev/null
@@ -1,140 +0,0 @@
-Mock-ril:
-
-Install:
-
-The protoc is now part of the Android build but its
-called "aprotoc" so it doesn't conflict with versions
-already installed. If you wish to install it permanetly
-see external/protobuf/INSTALL.txt and
-external/protobuf/python/README.txt. If you get
-"from google.protobuf import xxxx" statements that
-google.protobuf is not found, you didn't install the
-python support for protobuf. Also on Mac OSX I got an
-error running the protoc tests but installing was fine.
-
-Running/testing:
-
-See "Testing a new ril:" below for general instructions but
-for the mock-ril I've added some targets to the Makefile to
-ease testing. Also Makefile needs to know the device being
-used as this determines the directory where files are found
-and stored. ANDROID_DEVICE is an environment variable and
-maybe either exported:
- $ export ANDROID_DEVICE=stingray
-
-or it can be passed on the command line:
- $ make clean ANDROID_DEVICE=stingray
-
-If it's not set "passion" is the default.
-
-Execute the "first" target first to setup appropriate
-environment:
- $ cd hardware/ril/mock-ril
- $ make first
-
-If changes made to ".proto" files run make with the default
-"all" target:
- $ make
-
-If changes are made to "c++" file create a new library and
-run the "test" target:
- $ mm
- $ make test
-
-If changes to only the execute "js" target:
- $ make js
-
-To run the test control server:
- $ make tcs
-
-Implementation:
-
-The mock-ril is a library where the ril is implemented primarily
-in javascript, mock-ril.js. In addition it can be controlled by
-sending messages from another computer to port 54312 (TODO make
-programmable) to the ctrlServer, a Worker in In mock-ril.js.
-
-See mock_ril.js for additional documentation.
-
-files:
- ctrl.proto Protobuf messages for the control server
- ctrl.* Protobuf generated files.
- ctrl_pb2.py Python files generated from ctrl.proto
- ctrl_server.* Cpp interface routines between ctrlServer
- in javascript and the controller.
- experiments.* Early experiments
- js_support.* Java script support methods. Exposes various
- routines to javascript, such as print, readFile
- and include.
- logging.h LOG_TAG and include utils/log.h
- mock_ril.[cpp|h] Main module inteface code.
- mock_ril.js The mock ril
- node_buffer.* A Buffer for communicating between c++ and js.
- This was ported from nodejs.org.
- node_object.* An object wrapper to make it easier to expose
- c++ code to js. Ported from nodejs.org.
- node_util.* Some utilities ported from nodejs.org.
- protobuf_v8.* Protobuf code for javascript ported from
- http://code.google.com/p/protobuf-for-node/.
- requests.* Interface code for handling framework requests.
- responses* Interface code for handling framework responses.
- ril.proto The protobuf version of ril.h
- ril_vars.js Some additional variables defined for enums in
- ril.h.
- ril_pb2.py Python files generated from ril.proto.
- status.h STATUS constants.
- tcs.py Test the ctrlServer.
- util.* Utility routines
- worker.* Define WorkerThread and WorkerQueue.
- worker_v8.* Expose WorkerQueue to js.
-
-
-TODO: more documentation.
-
-
-Testing a new ril:
-
-The Makefile is used to generate files and make testing easier.
-and there are has several targets:
-
-all runs protoc and generates files, ril.desc ril.pb.*
-
-clean target removes generated files.
-
-first changes to root, remounts r/w and copies some files.
-
-test copies the latest libmock_ril.so and kills rild
- to run the new mockril
-
-General instructions for testing ril's:
-
-1) On the device login in as root and remount file system so it's read/write:
- $ adb root
- restarting adbd as root
-
- $ adb remount
- remount succeeded
-
-2) Set rild.libpath to the name of the ril:
- adb shell setprop rild.libpath /system/lib/libmock_ril.so
-
- Using setprop makes the change temporary and the old ril will be
- used after rebooting. (Another option is to set rild.libpath in
- /data/local.prop, but don't forget to reboot for it to take effect).
-
-3) Compile and copy the ril to /system/lib/:
- adb push out/target/product/passion/system/lib/libmock_ril.so /system/lib/
-
-4) To restart the ril, kill the currently running ril and the new one
- will automatically be restarted. You can use the ps command to find
- /system/bin/rild PID, 3212 below and kill it:
- $ adb shell ps | grep rild
- radio 3212 1 3224 628 ffffffff afd0e4fc S /system/bin/rild
-
- $ adb shell kill 3212
-
- or
-
- $ adb shell setprop ctl.restart ril-daemon
-
-5) Make modifications, go to step 3.
diff --git a/mock-ril/src/cpp/ctrl_server.cpp b/mock-ril/src/cpp/ctrl_server.cpp
deleted file mode 100644
index 3ac3a9f..0000000
--- a/mock-ril/src/cpp/ctrl_server.cpp
+++ /dev/null
@@ -1,473 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 <alloca.h>
-#include <pthread.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/endian.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <unistd.h>
-
-#include <cutils/sockets.h>
-
-#include "logging.h"
-#include "node_buffer.h"
-#include "status.h"
-#include "util.h"
-#include "worker.h"
-
-#include "hardware/ril/mock-ril/src/proto/msgheader.pb.h"
-
-#include "hardware/ril/mock-ril/src/proto/ctrl.pb.h"
-#include "ctrl_server.h"
-
-//#define CONTROL_SERVER_DEBUG
-#ifdef CONTROL_SERVER_DEBUG
-
-#define DBG(...) ALOGD(__VA_ARGS__)
-
-#else
-
-#define DBG(...)
-
-#endif
-
-#define MOCK_RIL_CONTROL_SERVER_STOPPING_SOCKET 54311
-#define MOCK_RIL_CONTROL_SERVER_SOCKET 54312
-
-using communication::MsgHeader;
-
-class CtrlServerThread;
-static CtrlServerThread *g_ctrl_server;
-
-class CtrlServerThread : public WorkerThread {
- private:
- #define SOCKET_NAME_MOCK_RIL_CST_STOPPER "mock-ril-cst-stopper"
- v8::Handle<v8::Context> context_;
- int server_accept_socket_;
- int server_to_client_socket_;
- int stop_server_fd_;
- int stop_client_fd_;
- int stopper_fd_;
- fd_set rd_fds_;
- fd_set wr_fds_;
- bool done_;
-
- Buffer *ObtainBuffer(int length) {
- Buffer *b = Buffer::New(length);
- return b;
- }
-
- int WriteAll(int s, void *data, int length) {
- int ret_value;
- uint8_t *bytes = (uint8_t *)data;
- int count = length;
-
- while (length > 0) {
- ret_value = send(s, bytes, length, 0);
- if (ret_value < 0) {
- return STATUS_ERR;
- }
- if (ret_value == 0) {
- return STATUS_CLIENT_CLOSED_CONNECTION;
- }
- bytes += ret_value;
- length -= ret_value;
- }
-
- return STATUS_OK;
- }
-
- int ReadAll(int s, void *data, int length) {
- int ret_value;
- uint8_t *bytes = (uint8_t *)data;
- int count = length;
-
- while (length != 0) {
- ret_value = recv(s, bytes, length, 0);
- if (ret_value < 0) {
- return STATUS_ERR;
- }
- if (ret_value == 0) {
- return STATUS_CLIENT_CLOSED_CONNECTION;
- }
- bytes += ret_value;
- length -= ret_value;
- }
-
- return STATUS_OK;
- }
-
- int ReadMessage(MsgHeader *mh, Buffer **pBuffer) {
- int status;
- int32_t len_msg_header;
-
- // Reader header length
- status = ReadAll(server_to_client_socket_, &len_msg_header, sizeof(len_msg_header));
- len_msg_header = letoh32(len_msg_header);
- DBG("rm: read len_msg_header=%d status=%d", len_msg_header, status);
- if (status != STATUS_OK) return status;
-
- // Read header into an array allocated on the stack and unmarshall
- uint8_t *msg_header_raw = (uint8_t *)alloca(len_msg_header);
- status = ReadAll(server_to_client_socket_, msg_header_raw, len_msg_header);
- DBG("rm: read msg_header_raw=%p status=%d", msg_header_raw, status);
- if (status != STATUS_OK) return status;
- mh->ParseFromArray(msg_header_raw, len_msg_header);
-
- // Read auxillary data
- Buffer *buffer;
- if (mh->length_data() > 0) {
- buffer = ObtainBuffer(mh->length_data());
- status = ReadAll(server_to_client_socket_, buffer->data(), buffer->length());
- DBG("rm: read protobuf status=%d", status);
- if (status != STATUS_OK) return status;
- } else {
- DBG("rm: NO protobuf");
- buffer = NULL;
- }
-
- *pBuffer = buffer;
- return STATUS_OK;
- }
-
- public:
- int WriteMessage(MsgHeader *mh, Buffer *buffer) {
- int status;
- uint32_t i;
- uint64_t l;
-
- // Set length of data
- if (buffer == NULL) {
- mh->set_length_data(0);
- } else {
- mh->set_length_data(buffer->length());
- }
-
- // Serialize header
- uint32_t len_msg_header = mh->ByteSize();
- uint8_t *msg_header_raw = (uint8_t *)alloca(len_msg_header);
- mh->SerializeToArray(msg_header_raw, len_msg_header);
-
- // Write length in little endian followed by the header
- i = htole32(len_msg_header);
- status = WriteAll(server_to_client_socket_, &i, 4);
- DBG("wm: write len_msg_header=%d status=%d", len_msg_header, status);
- if (status != 0) return status;
- status = WriteAll(server_to_client_socket_, msg_header_raw, len_msg_header);
- DBG("wm: write msg_header_raw=%p status=%d", msg_header_raw, status);
- if (status != 0) return status;
-
- // Write data
- if (mh->length_data() > 0) {
- status = WriteAll(server_to_client_socket_, buffer->data(), buffer->length());
- DBG("wm: protobuf data=%p len=%d status=%d",
- buffer->data(), buffer->length(), status);
- if (status != 0) return status;
- }
-
- return STATUS_OK;
- }
-
- CtrlServerThread(v8::Handle<v8::Context> context) :
- context_(context),
- server_accept_socket_(-1),
- server_to_client_socket_(-1),
- done_(false) {
- }
-
- virtual int Run() {
- DBG("CtrlServerThread::Run E");
-
- // Create a server socket.
- server_accept_socket_ = socket_inaddr_any_server(
- MOCK_RIL_CONTROL_SERVER_SOCKET, SOCK_STREAM);
- if (server_accept_socket_ < 0) {
- ALOGE("CtrlServerThread::Run error creating server_accept_socket_ '%s'",
- strerror(errno));
- return STATUS_ERR;
- }
-
- // Create a server socket that will be used for stopping
- stop_server_fd_ = socket_loopback_server(
- MOCK_RIL_CONTROL_SERVER_STOPPING_SOCKET, SOCK_STREAM);
- if (stop_server_fd_ < 0) {
- ALOGE("CtrlServerThread::Run error creating stop_server_fd_ '%s'",
- strerror(errno));
- return STATUS_ERR;
- }
-
- // Create a client socket that will be used for sending a stop
- stop_client_fd_ = socket_loopback_client(
- MOCK_RIL_CONTROL_SERVER_STOPPING_SOCKET, SOCK_STREAM);
- if (stop_client_fd_ < 0) {
- ALOGE("CtrlServerThread::Run error creating stop_client_fd_ '%s'",
- strerror(errno));
- return STATUS_ERR;
- }
-
- // Accept the connection of the stop_client_fd_
- stopper_fd_ = accept(stop_server_fd_, NULL, NULL);
- if (stopper_fd_ < 0) {
- ALOGE("CtrlServerThread::Run error accepting stop_client_fd '%s'",
- strerror(errno));
- return STATUS_ERR;
- }
-
- // Run the new thread
- int ret_value = WorkerThread::Run(NULL);
- DBG("CtrlServerThread::Run X");
- return ret_value;
- }
-
- virtual void Stop() {
- DBG("CtrlServerThread::Stop E");
- if (BeginStopping()) {
- done_ = true;
- int rv = send(stop_client_fd_, &done_, sizeof(done_), 0);
- if (rv <= 0) {
- ALOGE("CtrlServerThread::Stop could not send stop"
- "WE WILL PROBABLY HANG");
- }
- WaitUntilStopped();
- }
- DBG("CtrlServerThread::Stop X");
- }
-
- virtual bool isRunning() {
- bool rv = done_ || WorkerThread::isRunning();
- return rv;
- }
-
- int WaitOnSocketOrStopping(fd_set *rfds, int s) {
- DBG("WaitOnSocketOrStopping E s=%d stopper_fd_=%d", s, stopper_fd_);
- FD_ZERO(rfds);
- FD_SET(s, rfds);
- FD_SET(stopper_fd_, rfds);
- int fd_number = s > stopper_fd_ ? s + 1 : stopper_fd_ + 1;
- v8::Unlocker unlocker;
- int rv = select(fd_number, rfds, NULL, NULL, NULL);
- v8::Locker locker;
- DBG("WaitOnSocketOrStopping X rv=%d s=%d stopper_fd_=%d", rv, s, stopper_fd_);
- return rv;
- }
-
- int sendToCtrlServer(MsgHeader *mh, Buffer *buffer) {
- DBG("sendToCtrlServer E: cmd=%d token=%lld", mh->cmd(), mh->token());
-
- int status = STATUS_OK;
- v8::HandleScope handle_scope;
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- // Get the onRilRequest Function
- v8::Handle<v8::String> name = v8::String::New("onCtrlServerCmd");
- v8::Handle<v8::Value> onCtrlServerCmdFunctionValue =
- context_->Global()->Get(name);
- v8::Handle<v8::Function> onCtrlServerCmdFunction =
- v8::Handle<v8::Function>::Cast(onCtrlServerCmdFunctionValue);
-
- // Create the CmdValue and TokenValue
- v8::Handle<v8::Value> v8CmdValue = v8::Number::New(mh->cmd());
- v8::Handle<v8::Value> v8TokenValue = v8::Number::New(mh->token());
-
- // Invoke onRilRequest
- const int argc = 3;
- v8::Handle<v8::Value> buf;
- if (mh->length_data() == 0) {
- buf = v8::Undefined();
- } else {
- buf = buffer->handle_;
- }
- v8::Handle<v8::Value> argv[argc] = {
- v8CmdValue, v8TokenValue, buf };
- v8::Handle<v8::Value> result =
- onCtrlServerCmdFunction->Call(context_->Global(), argc, argv);
- if (try_catch.HasCaught()) {
- ReportException(&try_catch);
- status = STATUS_ERR;
- } else {
- v8::String::Utf8Value result_string(result);
- DBG("sendToCtrlServer result=%s", ToCString(result_string));
- status = STATUS_OK;
- }
-
- if (status != STATUS_OK) {
- ALOGE("sendToCtrlServer Error: status=%d", status);
- // An error report complete now
- mh->set_length_data(0);
- mh->set_status(ril_proto::CTRL_STATUS_ERR);
- g_ctrl_server->WriteMessage(mh, NULL);
- }
-
- DBG("sendToCtrlServer X: status=%d", status);
- return status;
- }
-
- virtual void * Worker(void *param) {
- DBG("CtrlServerThread::Worker E param=%p stopper_fd_=%d",
- param, stopper_fd_);
-
- v8::Locker locker;
- v8::HandleScope handle_scope;
- v8::Context::Scope context_scope(context_);
-
- while (isRunning()) {
- int ret_value;
-
- // Wait on either server_accept_socket_ or stopping
- DBG("CtrlServerThread::Worker wait on server for a client");
- WaitOnSocketOrStopping(&rd_fds_, server_accept_socket_);
- if (isRunning() != true) {
- break;
- }
-
- if (FD_ISSET(server_accept_socket_, &rd_fds_)) {
- server_to_client_socket_ = accept(server_accept_socket_, NULL, NULL);
- DBG("CtrlServerThread::Worker accepted server_to_client_socket_=%d isRunning()=%d",
- server_to_client_socket_, isRunning());
-
- int status;
- Buffer *buffer;
- MsgHeader mh;
- while ((server_to_client_socket_ > 0) && isRunning()) {
- DBG("CtrlServerThread::Worker wait on client for message");
- WaitOnSocketOrStopping(&rd_fds_, server_to_client_socket_);
- if (isRunning() != true) {
- break;
- }
-
- status = ReadMessage(&mh, &buffer);
- if (status != STATUS_OK) break;
-
- if (mh.cmd() == ril_proto::CTRL_CMD_ECHO) {
- ALOGD("CtrlServerThread::Worker echo");
- status = WriteMessage(&mh, buffer);
- if (status != STATUS_OK) break;
- } else {
- DBG("CtrlServerThread::Worker sendToCtrlServer");
- status = sendToCtrlServer(&mh, buffer);
- if (status != STATUS_OK) break;
- }
- }
- close(server_to_client_socket_);
- server_to_client_socket_ = -1;
- }
- }
- close(stop_server_fd_);
- stop_server_fd_ = -1;
-
- close(stop_client_fd_);
- stop_client_fd_ = -1;
-
- close(stopper_fd_);
- stopper_fd_ = -1;
-
- close(server_accept_socket_);
- server_accept_socket_ = -1;
-
- DBG("CtrlServerThread::Worker X param=%p", param);
- return NULL;
- }
-};
-
-/**
- * Send a control request complete response.
- */
-v8::Handle<v8::Value> SendCtrlRequestComplete(const v8::Arguments& args) {
- DBG("SendCtrlRequestComplete E:");
- v8::HandleScope handle_scope;
- v8::Handle<v8::Value> retValue;
-
- void *data;
- size_t datalen;
-
- Buffer* buffer;
- MsgHeader mh;
-
- /**
- * Get the arguments. There should be at least 3, reqNum,
- * ril error code and token. Optionally a Buffer containing
- * the protobuf representation of the data to return.
- */
- if (args.Length() < 3) {
- // Expecting a reqNum, ERROR and token
- ALOGE("SendCtrlRequestComplete X %d parameters"
- " expecting at least 3: status, reqNum, and token",
- args.Length());
- return v8::Undefined();
- }
- v8::Handle<v8::Value> v8CtrlStatus(args[0]->ToObject());
- mh.set_status(ril_proto::CtrlStatus(v8CtrlStatus->NumberValue()));
- DBG("SendCtrlRequestComplete: status=%d", mh.status());
-
- v8::Handle<v8::Value> v8ReqNum(args[1]->ToObject());
- mh.set_cmd(int(v8ReqNum->NumberValue()));
- DBG("SendCtrlRequestComplete: cmd=%d", mh.cmd());
-
- v8::Handle<v8::Value> v8Token(args[2]->ToObject());
- mh.set_token(int64_t(v8Token->NumberValue()));
- DBG("SendCtrlRequestComplete: token=%lld", mh.token());
-
- if (args.Length() >= 4) {
- buffer = ObjectWrap::Unwrap<Buffer>(args[3]->ToObject());
- mh.set_length_data(buffer->length());
- DBG("SendCtrlRequestComplete: mh.length_data=%d",
- mh.length_data());
- } else {
- mh.set_length_data(0);
- buffer = NULL;
- DBG("SendCtrlRequestComplete: NO PROTOBUF");
- }
-
- DBG("SendCtrlRequestComplete: WriteMessage");
- int status = g_ctrl_server->WriteMessage(&mh, buffer);
-
- DBG("SendCtrlRequestComplete E:");
- return v8::Undefined();
-}
-
-void ctrlServerInit(v8::Handle<v8::Context> context) {
- int status;
-
- g_ctrl_server = new CtrlServerThread(context);
- status = g_ctrl_server->Run();
- if (status != STATUS_OK) {
- ALOGE("mock_ril control server could not start");
- } else {
- ALOGD("CtrlServer started");
- }
-
-#if 0
- ALOGD("Test CtrlServerThread stop sleeping 10 seconds...");
- v8::Unlocker unlocker;
- sleep(10);
- ALOGD("Test CtrlServerThread call Stop");
- g_ctrl_server->Stop();
- v8::Locker locker;
-
- // Restart
- g_ctrl_server = new CtrlServerThread(context);
- status = g_ctrl_server->Run();
- if (status != STATUS_OK) {
- ALOGE("mock_ril control server could not start");
- } else {
- DBG("mock_ril control server started");
- }
-#endif
-}
diff --git a/mock-ril/src/cpp/ctrl_server.h b/mock-ril/src/cpp/ctrl_server.h
deleted file mode 100644
index 2850f04..0000000
--- a/mock-ril/src/cpp/ctrl_server.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 MOCK_RIL_CONTROL_SERVER_H_
-#define MOCK_RIL_CONTROL_SERVER_H_
-
-#include <v8.h>
-
-extern v8::Handle<v8::Value> SendCtrlRequestComplete(const v8::Arguments& args);
-
-extern void ctrlServerInit(v8::Handle<v8::Context> context);
-
-#endif // MOCK_RIL_CONTROL_SERVER_H_
diff --git a/mock-ril/src/cpp/experiments.cpp b/mock-ril/src/cpp/experiments.cpp
deleted file mode 100644
index 0bb6b98..0000000
--- a/mock-ril/src/cpp/experiments.cpp
+++ /dev/null
@@ -1,281 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 <v8.h>
-#include "ril.h"
-
-#include "logging.h"
-#include "status.h"
-#include "worker.h"
-#include "util.h"
-
-#include "hardware/ril/mock-ril/src/proto/ril.pb.h"
-
-#include "logging.h"
-#include "js_support.h"
-#include "node_buffer.h"
-#include "node_util.h"
-#include "protobuf_v8.h"
-#include "requests.h"
-
-#include "experiments.h"
-
-void testStlPort() {
- // Test using STLport
- std::queue<int *> q;
- int data[] = {1, 2, 3};
-
- int *param = data;
- ALOGD("before push q.size=%d", q.size());
- q.push(param);
- ALOGD("after push q.size=%d", q.size());
- void *p = q.front();
- if (p == param) {
- ALOGD("q.push succeeded");
- } else {
- ALOGD("q.push failed");
- }
- q.pop();
- ALOGD("after pop q.size=%d", q.size());
-}
-
-v8::Handle<v8::Value> GetReqScreenState(v8::Local<v8::String> property,
- const v8::AccessorInfo &info) {
- v8::Local<v8::Object> self = info.Holder();
- v8::Local<v8::External> wrap =
- v8::Local<v8::External>::Cast(self->GetInternalField(0));
- void *p = wrap->Value();
- int state = static_cast<int *>(p)[0];
- ALOGD("GetReqScreenState state=%d", state);
- return v8::Integer::New(state);
-}
-
-bool callOnRilRequest(v8::Handle<v8::Context> context, int request,
- void *data, size_t datalen, RIL_Token t) {
- v8::HandleScope handle_scope;
- v8::TryCatch try_catch;
-
- // Get the onRilRequestFunction, making sure its a function
- v8::Handle<v8::String> name = v8::String::New("onRilRequest");
- v8::Handle<v8::Value> onRilRequestFunctionValue = context->Global()->Get(name);
- if(!onRilRequestFunctionValue->IsFunction()) {
- // Wasn't a function
- ALOGD("callOnRilRequest X wasn't a function");
- return false;
- }
- v8::Handle<v8::Function> onRilRequestFunction =
- v8::Handle<v8::Function>::Cast(onRilRequestFunctionValue);
-
- // Create the request
- v8::Handle<v8::Value> v8RequestValue = v8::Number::New(request);
-
- // Create the parameter for the request
- v8::Handle<v8::Object> params_obj =
- v8::ObjectTemplate::New()->NewInstance();
- switch(request) {
- case(RIL_REQUEST_SCREEN_STATE): {
- ALOGD("callOnRilRequest RIL_REQUEST_SCREEN_STATE");
- if (datalen < sizeof(int)) {
- ALOGD("callOnRilRequest err size < sizeof int");
- } else {
- v8::Handle<v8::ObjectTemplate> params_obj_template =
- v8::ObjectTemplate::New();
- params_obj_template->SetInternalFieldCount(1);
- params_obj_template->SetAccessor(v8::String::New(
- "ReqScreenState"), GetReqScreenState, NULL);
- // How to not leak this pointer!!!
- int *p = new int;
- *p = ((int *)data)[0];
- params_obj = params_obj_template->NewInstance();
- params_obj->SetInternalField(0, v8::External::New(p));
- }
- break;
- }
- default: {
- ALOGD("callOnRilRequest X unknown request");
- break;
- }
- }
-
- // Invoke onRilRequest
- bool retValue;
- const int argc = 2;
- v8::Handle<v8::Value> argv[argc] = { v8RequestValue, params_obj };
- v8::Handle<v8::Value> result =
- onRilRequestFunction->Call(context->Global(), argc, argv);
- if (try_catch.HasCaught()) {
- ALOGD("callOnRilRequest error");
- ReportException(&try_catch);
- retValue = false;
- } else {
- v8::String::Utf8Value result_string(result);
- ALOGD("callOnRilRequest result=%s", ToCString(result_string));
- retValue = true;
- }
- return retValue;
-}
-
-void testOnRilRequestUsingCppRequestObjs(v8::Handle<v8::Context> context) {
- ALOGD("testOnRilRequestUsingCppRequestObjs E:");
- v8::HandleScope handle_scope;
-
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- runJs(context, &try_catch, "local-string",
- "function onRilRequest(reqNum, params) {\n"
- " print(\"reqNum=\" + reqNum);\n"
- " if (reqNum == 61) {\n"
- " print(\"params.ReqScreenState=\" + params.ReqScreenState);\n"
- " }\n"
- " return \"Hello World\";\n"
- "}\n");
- if (!try_catch.HasCaught()) {
- // Call the onRilRequest function
- int data[1] = { 0 };
- callOnRilRequest(context, RIL_REQUEST_SCREEN_STATE, data,
- sizeof(data), NULL);
- }
- ALOGD("testOnRilRequestUsingCppRequestObjs X:");
-}
-
-void testReqScreenStateProtobuf() {
- v8::HandleScope handle_scope;
- v8::TryCatch try_catch;
-
- ALOGD("testReqScreenStateProtobuf E");
-
- ALOGD("create ReqScreenState");
- ril_proto::ReqScreenState* ss = new ril_proto::ReqScreenState();
- ss->set_state(true);
- bool state = ss->state();
- ALOGD("state=%d", state);
- ss->set_state(false);
- state = ss->state();
- ALOGD("state=%d", state);
- int len = ss->ByteSize();
- ALOGD("create buffer len=%d", len);
- char *buffer = new char[len];
- ALOGD("serialize");
- bool ok = ss->SerializeToArray(buffer, len);
- if (!ok) {
- ALOGD("testReqScreenStateProtobuf X: Could not serialize ss");
- return;
- }
- ALOGD("ReqScreenState serialized ok");
- ril_proto::ReqScreenState *newSs = new ril_proto::ReqScreenState();
- ok = newSs->ParseFromArray(buffer, len);
- if (!ok) {
- ALOGD("testReqScreenStateProtobuf X: Could not deserialize ss");
- return;
- }
- ALOGD("newSs->state=%d", newSs->state());
-
- delete [] buffer;
- delete ss;
- delete newSs;
- ALOGD("testReqScreenStateProtobuf X");
-}
-
-void testReqHangUpProtobuf() {
- v8::HandleScope handle_scope;
- v8::TryCatch try_catch;
-
- ALOGD("testReqHangUpProtobuf E");
-
- ALOGD("create ReqHangUp");
- ril_proto::ReqHangUp* hu = new ril_proto::ReqHangUp();
- hu->set_connection_index(3);
- bool connection_index = hu->connection_index();
- ALOGD("connection_index=%d", connection_index);
- hu->set_connection_index(2);
- connection_index = hu->connection_index();
- ALOGD("connection_index=%d", connection_index);
- ALOGD("create buffer");
- int len = hu->ByteSize();
- char *buffer = new char[len];
- ALOGD("serialize");
- bool ok = hu->SerializeToArray(buffer, len);
- if (!ok) {
- ALOGD("testReqHangUpProtobuf X: Could not serialize hu");
- return;
- }
- ALOGD("ReqHangUp serialized ok");
- ril_proto::ReqHangUp *newHu = new ril_proto::ReqHangUp();
- ok = newHu->ParseFromArray(buffer, len);
- if (!ok) {
- ALOGD("testReqHangUpProtobuf X: Could not deserialize hu");
- return;
- }
- ALOGD("newHu->connection_index=%d", newHu->connection_index());
-
- delete [] buffer;
- delete hu;
- delete newHu;
- ALOGD("testReqHangUpProtobuf X");
-}
-
-void testProtobufV8(v8::Handle<v8::Context> context) {
- ALOGD("testProtobufV8 E:");
- v8::HandleScope handle_scope;
-
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- if (try_catch.HasCaught()) {
- ALOGD("TryCatch.hasCaught is true after protobuf_v8::init");
- ReportException(&try_catch);
- }
- runJs(context, &try_catch, "local-string",
- "fileContents = readFileToString('mock_ril.js');\n"
- "print('fileContents:\\n' + fileContents);\n"
- "\n"
- "buffer = readFileToBuffer('ril.desc');\n"
- "var schema = new Schema(buffer);\n"
- "\n"
- "var originalReqEnterSimPin = { pin : 'hello-the-pin' };\n"
- "print('originalReqEnterSimPin: pin=' + originalReqEnterSimPin.pin);\n"
- "var ReqEnterSimPinSchema = schema['ril_proto.ReqEnterSimPin'];\n"
- "serializedOriginalReqEnterSimPin = ReqEnterSimPinSchema.serialize(originalReqEnterSimPin);\n"
- "print('serializedOriginalReqEnterSimPin.length=' + serializedOriginalReqEnterSimPin.length);\n"
- "newReqEnterSimPin = ReqEnterSimPinSchema.parse(serializedOriginalReqEnterSimPin);\n"
- "print('newReqEnterSimPin: pin=' + newReqEnterSimPin.pin);\n"
- "\n"
- "var originalReqScreenState = { state : true };\n"
- "print('originalReqScreenState: state=' + originalReqScreenState.state);\n"
- "var ReqScreenStateSchema = schema['ril_proto.ReqScreenState'];\n"
- "var serializedOriginalReqScreenState = ReqScreenStateSchema.serialize(originalReqScreenState);\n"
- "print('serializedOriginalReqScreenState.length=' + serializedOriginalReqScreenState.length);\n"
- "var newReqScreenState = ReqScreenStateSchema.parse(serializedOriginalReqScreenState);\n"
- "print('newReqScreenState: state=' + newReqScreenState.state);\n"
- "\n"
- "originalReqScreenState.state = false;\n"
- "print('originalReqScreenState: state=' + originalReqScreenState.state);\n"
- "serializedOriginalReqScreenState = ReqScreenStateSchema.serialize(originalReqScreenState);\n"
- "print('serializedOriginalReqScreenState.length=' + serializedOriginalReqScreenState.length);\n"
- "newReqScreenState = ReqScreenStateSchema.parse(serializedOriginalReqScreenState);\n"
- "print('newReqScreenState: state=' + newReqScreenState.state);\n");
- ALOGD("testProtobufV8 X");
-}
-
-void experiments(v8::Handle<v8::Context> context) {
- ALOGD("experiments E: ********");
- testStlPort();
- testReqScreenStateProtobuf();
- testOnRilRequestUsingCppRequestObjs(context);
- testProtobufV8(context);
- ALOGD("experiments X: ********\n");
-}
diff --git a/mock-ril/src/cpp/experiments.h b/mock-ril/src/cpp/experiments.h
deleted file mode 100644
index 54044ab..0000000
--- a/mock-ril/src/cpp/experiments.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 MOCK_RIL_INITIAL_TESTS_H_
-#define MOCK_RIL_INITIAL_TESTS_H_
-
-#include <v8.h>
-
-void experiments(v8::Handle<v8::Context> context);
-
-#endif // MOCK_RIL_INITIAL_TESTS_H_
diff --git a/mock-ril/src/cpp/js_support.cpp b/mock-ril/src/cpp/js_support.cpp
deleted file mode 100644
index ec10e38..0000000
--- a/mock-ril/src/cpp/js_support.cpp
+++ /dev/null
@@ -1,415 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 <v8.h>
-#include "ril.h"
-
-#include "ctrl_server.h"
-#include "logging.h"
-#include "node_buffer.h"
-#include "node_object_wrap.h"
-#include "node_util.h"
-#include "protobuf_v8.h"
-#include "responses.h"
-#include "status.h"
-#include "util.h"
-#include "worker.h"
-#include "worker_v8.h"
-
-#include "js_support.h"
-
-//#define JS_SUPPORT_DEBUG
-#ifdef JS_SUPPORT_DEBUG
-
-#define DBG(...) ALOGD(__VA_ARGS__)
-
-#else
-
-#define DBG(...)
-
-#endif
-
-/**
- * Current Radio state
- */
-RIL_RadioState gRadioState = RADIO_STATE_UNAVAILABLE;
-
-v8::Handle<v8::Value> RadioStateGetter(v8::Local<v8::String> property,
- const v8::AccessorInfo& info) {
- return v8::Integer::New((int)gRadioState);
-}
-
-void RadioStateSetter(v8::Local<v8::String> property,
- v8::Local<v8::Value> value, const v8::AccessorInfo& info) {
- gRadioState = RIL_RadioState(value->Int32Value());
-}
-
-// A javascript sleep for a number of milli-seconds
-v8::Handle<v8::Value> MsSleep(const v8::Arguments& args) {
- if (args.Length() != 1) {
- DBG("MsSleep: expecting milli-seconds to sleep");
- } else {
- v8::Handle<v8::Value> v8MsValue(args[0]->ToObject());
- int ms = int(v8MsValue->NumberValue());
- v8::Unlocker unlocker;
- usleep(ms * 1000);
- v8::Locker locker;
- }
- return v8::Undefined();
-}
-
-// A javascript print function
-v8::Handle<v8::Value> Print(const v8::Arguments& args) {
- bool first = true;
- const int str_size = 1000;
- char* str = new char[str_size];
- int offset = 0;
- for (int i = 0; i < args.Length(); i++) {
- v8::HandleScope handle_scope;
- if (first) {
- first = false;
- } else {
- offset += snprintf(&str[offset], str_size, " ");
- }
- v8::String::Utf8Value strUtf8(args[i]);
- const char* cstr = ToCString(strUtf8);
- offset += snprintf(&str[offset], str_size, "%s", cstr);
- }
- ALOGD("%s", str);
- delete [] str;
- return v8::Undefined();
-}
-
-int ReadFile(const char *fileName, char** data, size_t *length) {
- int status;
- char* buffer = NULL;
- size_t fileLength = 0;
- FILE *f;
-
- DBG("ReadFile E fileName=%s", fileName);
-
- f = fopen(fileName, "rb");
- if (f == NULL) {
- DBG("Could not fopen '%s'", fileName);
- status = STATUS_COULD_NOT_OPEN_FILE;
- } else {
- // Determine the length of the file
- fseek(f, 0, SEEK_END);
- fileLength = ftell(f);
- DBG("fileLength=%d", fileLength);
- rewind(f);
-
- // Read file into a buffer
- buffer = new char[fileLength+1];
- size_t readLength = fread(buffer, 1, fileLength, f);
- if (readLength != fileLength) {
- DBG("Couldn't read entire file");
- delete [] buffer;
- buffer = NULL;
- status = STATUS_COULD_NOT_READ_FILE;
- } else {
- DBG("File read");
- buffer[fileLength] = 0;
- status = STATUS_OK;
- }
- fclose(f);
- }
-
- if (length != NULL) {
- *length = fileLength;
- }
- *data = buffer;
- DBG("ReadFile X status=%d", status);
- return status;
-}
-
-char *CreateFileName(const v8::Arguments& args) {
- v8::String::Utf8Value fileNameUtf8Value(args[0]);
- const char* fileName = ToCString(fileNameUtf8Value);
- const char* directory = "/sdcard/data/";
-
- int fullPathLength = strlen(directory) + strlen(fileName) + 1;
- char * fullPath = new char[fullPathLength];
- strncpy(fullPath, directory, fullPathLength);
- strncat(fullPath, fileName, fullPathLength);
- return fullPath;
-}
-
-// A javascript read file function arg[0] = filename
-v8::Handle<v8::Value> ReadFileToString(const v8::Arguments& args) {
- DBG("ReadFileToString E");
- v8::HandleScope handle_scope;
- v8::Handle<v8::Value> retValue;
-
- if (args.Length() < 1) {
- // No file name return Undefined
- DBG("ReadFile X no argumens");
- return v8::Undefined();
- } else {
- char *fileName = CreateFileName(args);
-
- char *buffer;
- int status = ReadFile(fileName, &buffer);
- if (status == 0) {
- retValue = v8::String::New(buffer);
- } else {
- retValue = v8::Undefined();
- }
- }
- DBG("ReadFileToString X");
- return retValue;
-}
-
-// A javascript read file function arg[0] = filename
-v8::Handle<v8::Value> ReadFileToBuffer(const v8::Arguments& args) {
- DBG("ReadFileToBuffer E");
- v8::HandleScope handle_scope;
- v8::Handle<v8::Value> retValue;
-
- if (args.Length() < 1) {
- // No file name return Undefined
- DBG("ReadFileToBuffer X no argumens");
- return v8::Undefined();
- } else {
- char *fileName = CreateFileName(args);
-
- char *buffer;
- size_t length;
- int status = ReadFile(fileName, &buffer, &length);
- if (status == 0) {
- Buffer *buf = Buffer::New(length);
- memmove(buf->data(), buffer, length);
- retValue = buf->handle_;
- } else {
- retValue = v8::Undefined();
- }
- }
- DBG("ReadFileToBuffer X");
- return retValue;
-}
-
-void ErrorCallback(v8::Handle<v8::Message> message,
- v8::Handle<v8::Value> data) {
- LogErrorMessage(message, "");
-}
-
-// Read, compile and run a javascript file
-v8::Handle<v8::Value> Include(const v8::Arguments& args) {
- DBG("Include E");
- v8::HandleScope handle_scope;
- v8::Handle<v8::Value> retValue;
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- if (args.Length() < 1) {
- // No file name return Undefined
- DBG("Include X no argumens");
- return v8::Undefined();
- } else {
- char *fileName = CreateFileName(args);
-
- char *buffer;
- int status = ReadFile(fileName, &buffer);
- if (status == 0) {
- runJs(v8::Context::GetCurrent(), &try_catch, fileName, buffer);
- } else {
- retValue = v8::Undefined();
- }
- }
- DBG("Include X");
- return retValue;
-}
-
-
-/**
- * Create a JsContext, must be called within a HandleScope?
- */
-v8::Persistent<v8::Context> makeJsContext() {
- v8::HandleScope handle_scope;
- v8::TryCatch try_catch;
-
- // Add a Message listner to Catch errors as they occur
- v8::V8::AddMessageListener(ErrorCallback);
-
- // Create a template for the global object and
- // add the function template for print to it.
- v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
- global->SetAccessor(v8::String::New("gRadioState"),
- RadioStateGetter, RadioStateSetter);
- global->Set(v8::String::New("msSleep"), v8::FunctionTemplate::New(MsSleep));
- global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));
- global->Set(v8::String::New("readFileToBuffer"),
- v8::FunctionTemplate::New(ReadFileToBuffer));
- global->Set(v8::String::New("readFileToString"),
- v8::FunctionTemplate::New(ReadFileToString));
- global->Set(v8::String::New("sendRilRequestComplete"),
- v8::FunctionTemplate::New(SendRilRequestComplete));
- global->Set(v8::String::New("sendRilUnsolicitedResponse"),
- v8::FunctionTemplate::New(SendRilUnsolicitedResponse));
- global->Set(v8::String::New("sendCtrlRequestComplete"),
- v8::FunctionTemplate::New(SendCtrlRequestComplete));
- global->Set(v8::String::New("include"), v8::FunctionTemplate::New(Include));
- WorkerV8ObjectTemplateInit(global);
- SchemaObjectTemplateInit(global);
- Buffer::InitializeObjectTemplate(global);
-
- // Create context with our globals and make it the current scope
- v8::Persistent<v8::Context> context = v8::Context::New(NULL, global);
-
-
- if (try_catch.HasCaught()) {
- DBG("makeJsContext: Exception making the context");
- ReportException(&try_catch);
- try_catch.ReThrow();
- }
-
- return context;
-}
-
-/**
- * Run some javascript code.
- */
-void runJs(v8::Handle<v8::Context> context, v8::TryCatch *try_catch,
- const char *fileName, const char *code) {
- v8::HandleScope handle_scope;
-
- // Compile the source
- v8::Handle<v8::Script> script = v8::Script::Compile(
- v8::String::New(code), v8::String::New(fileName));
- if (try_catch->HasCaught()) {
- ALOGE("-- Compiling the source failed");
- } else {
- // Run the resulting script
- v8::Handle<v8::Value> result = script->Run();
- if (try_catch->HasCaught()) {
- ALOGE("-- Running the script failed");
- }
- }
-}
-
-void testRadioState(v8::Handle<v8::Context> context) {
- ALOGD("testRadioState E:");
- v8::HandleScope handle_scope;
-
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- runJs(context, &try_catch, "local-string",
- "for(i = 0; i < 10; i++) {\n"
- " gRadioState = i;\n"
- " print('gRadioState=' + gRadioState);\n"
- "}\n"
- "gRadioState = 1;\n"
- "print('last gRadioState=' + gRadioState);\n");
- ALOGD("testRadioState X:");
-}
-
-void testMsSleep(v8::Handle<v8::Context> context) {
- ALOGD("testMsSleep E:");
- v8::HandleScope handle_scope;
-
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- runJs(context, &try_catch, "local-string",
- "for(i = 0; i < 10; i++) {\n"
- " sleeptime = i * 200\n"
- " print('msSleep ' + sleeptime);\n"
- " msSleep(sleeptime);\n"
- "}\n");
- ALOGD("testMsSleep X:");
-}
-
-void testPrint(v8::Handle<v8::Context> context) {
- ALOGD("testPrint E:");
- v8::HandleScope handle_scope;
-
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- runJs(context, &try_catch, "local-string", "print(\"Hello\")");
- ALOGD("testPrint X:");
-}
-
-void testCompileError(v8::Handle<v8::Context> context) {
- ALOGD("testCompileError E:");
- v8::HandleScope handle_scope;
-
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- // +++ generate a compile time error
- runJs(context, &try_catch, "local-string", "+++");
- ALOGD("testCompileError X:");
-}
-
-void testRuntimeError(v8::Handle<v8::Context> context) {
- ALOGD("testRuntimeError E:");
- v8::HandleScope handle_scope;
-
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- // Runtime error
- runJs(context, &try_catch, "local-string",
- "function hello() {\n"
- " print(\"Hi there\");\n"
- "}\n"
- "helloo()");
- ALOGD("testRuntimeError X:");
-}
-
-void testReadFile() {
- char *buffer;
- size_t length;
- int status;
-
- ALOGD("testReadFile E:");
-
- status = ReadFile("/sdcard/data/no-file", &buffer, &length);
- ALOGD("testReadFile expect status != 0, status=%d, buffer=%p, length=%d",
- status, buffer, length);
-
- ALOGD("testReadFile X:");
-}
-
-
-void testReadFileToStringBuffer(v8::Handle<v8::Context> context) {
- ALOGD("testReadFileToStringBuffer E:");
- v8::HandleScope handle_scope;
-
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- runJs(context, &try_catch, "local-string",
- "fileContents = readFileToString(\"mock_ril.js\");\n"
- "print(\"fileContents:\\n\" + fileContents);\n"
- "buffer = readFileToBuffer(\"ril.desc\");\n"
- "print(\"buffer.length=\" + buffer.length);\n");
- ALOGD("testReadFileToStringBuffer X:");
-}
-
-void testJsSupport(v8::Handle<v8::Context> context) {
- ALOGD("testJsSupport E: ********");
- testRadioState(context);
- testMsSleep(context);
- testPrint(context);
- testCompileError(context);
- testRuntimeError(context);
- testReadFile();
- testReadFileToStringBuffer(context);
- ALOGD("testJsSupport X: ********\n");
-}
diff --git a/mock-ril/src/cpp/js_support.h b/mock-ril/src/cpp/js_support.h
deleted file mode 100644
index 3116f1d..0000000
--- a/mock-ril/src/cpp/js_support.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 MOCK_RIL_JS_SUPPORT_H_
-#define MOCK_RIL_JS_SUPPORT_H_
-
-#include <v8.h>
-#include "ril.h"
-
-// The global value of radio state shared between cpp and js code.
-extern RIL_RadioState gRadioState;
-
-// A javascript print function
-extern v8::Handle<v8::Value> Print(const v8::Arguments& args);
-
-// Read a file into a array returning the buffer and the size
-extern int ReadFile(const char *fileName, char** data, size_t *length = NULL);
-
-// A javascript read file function arg[0] = filename
-extern v8::Handle<v8::Value> ReadFileToString(const v8::Arguments& args);
-
-// A javascript read file function arg[0] = filename
-extern v8::Handle<v8::Value> ReadFileToBuffer(const v8::Arguments& args);
-
-// make the Java
-extern v8::Persistent<v8::Context> makeJsContext();
-
-// Run a javascript
-extern void runJs(v8::Handle<v8::Context> context, v8::TryCatch *try_catch,
- const char *fileName, const char *code);
-
-// Test this module
-extern void testJsSupport(v8::Handle<v8::Context> context);
-
-#endif // MOCK_RIL_JS_SUPPORT_H_
diff --git a/mock-ril/src/cpp/mock_ril.cpp b/mock-ril/src/cpp/mock_ril.cpp
deleted file mode 100644
index 7c199c9..0000000
--- a/mock-ril/src/cpp/mock_ril.cpp
+++ /dev/null
@@ -1,362 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 <stdio.h>
-#include <assert.h>
-#include <string.h>
-#include <errno.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <alloca.h>
-#include <getopt.h>
-#include <sys/socket.h>
-#include <cutils/sockets.h>
-#include <termios.h>
-
-#include <v8.h>
-#include "ril.h"
-
-#include "hardware/ril/mock-ril/src/proto/ril.pb.h"
-
-#include "ctrl_server.h"
-#include "logging.h"
-#include "experiments.h"
-#include "js_support.h"
-#include "node_buffer.h"
-#include "node_object_wrap.h"
-#include "node_util.h"
-#include "protobuf_v8.h"
-#include "requests.h"
-#include "responses.h"
-#include "status.h"
-#include "util.h"
-#include "worker.h"
-#include "worker_v8.h"
-
-#include "mock_ril.h"
-
-extern "C" {
-// Needed so we can call it prior to calling startMockRil
-extern void RIL_register(const RIL_RadioFunctions *callbacks);
-}
-
-//#define MOCK_RIL_DEBUG
-#ifdef MOCK_RIL_DEBUG
-
-#define DBG(...) ALOGD(__VA_ARGS__)
-
-#else
-
-#define DBG(...)
-
-#endif
-
-
-#define MOCK_RIL_VER_STRING "Android Mock-ril 0.1"
-
-/**
- * Forward declarations
- */
-static void onRequest (int request, void *data, size_t datalen, RIL_Token t);
-static RIL_RadioState currentState();
-static int onSupports (int requestCode);
-static void onCancel (RIL_Token t);
-static const char *getVersion();
-
-static void testOnRequestComplete(RIL_Token t, RIL_Errno e,
- void *response, size_t responselen);
-static void testRequestTimedCallback(RIL_TimedCallback callback,
- void *param, const struct timeval *relativeTime);
-static void testOnUnsolicitedResponse(int unsolResponse, const void *data,
- size_t datalen);
-
-/**
- * The environment from rild with the completion routine
- */
-const struct RIL_Env *s_rilenv;
-
-/**
- * Expose our routines to rild
- */
-static const RIL_RadioFunctions s_callbacks = {
- RIL_VERSION,
- onRequest,
- currentState,
- onSupports,
- onCancel,
- getVersion
-};
-
-/**
- * A test environment
- */
-static const RIL_Env testEnv = {
- testOnRequestComplete,
- testOnUnsolicitedResponse,
- testRequestTimedCallback
-};
-
-/**
- * The request worker queue to handle requests
- */
-static RilRequestWorkerQueue *s_requestWorkerQueue;
-
-/**
- * Call from RIL to us to make a RIL_REQUEST
- *
- * Must be completed with a call to RIL_onRequestComplete()
- *
- * RIL_onRequestComplete() may be called from any thread, before or after
- * this function returns.
- *
- * Will always be called from the same thread, so returning here implies
- * that the radio is ready to process another command (whether or not
- * the previous command has c1mpleted).
- */
-static void onRequest (int request, void *data, size_t datalen, RIL_Token t)
-{
- DBG("onRequest: request=%d data=%p datalen=%d token=%p",
- request, data, datalen, t);
- s_requestWorkerQueue->AddRequest(request, data, datalen, t);
-}
-
-/**
- * Synchronous call from the RIL to us to return current radio state.
- * RADIO_STATE_UNAVAILABLE should be the initial state.
- */
-static RIL_RadioState currentState()
-{
- DBG("currentState: gRadioState=%d", gRadioState);
- return gRadioState;
-}
-
-/**
- * Call from RIL to us to find out whether a specific request code
- * is supported by this implementation.
- *
- * Return 1 for "supported" and 0 for "unsupported"
- */
-
-static int
-onSupports (int requestCode)
-{
- DBG("onSupports: nothing supported at the moment, return 0");
- return 0;
-}
-
-static void onCancel (RIL_Token t)
-{
- DBG("onCancel: ignorning");
-}
-
-static const char * getVersion(void)
-{
- DBG("getVersion: return '%s'", MOCK_RIL_VER_STRING);
- return MOCK_RIL_VER_STRING;
-}
-
-/**
- * "t" is parameter passed in on previous call to RIL_Notification
- * routine.
- *
- * If "e" != SUCCESS, then response can be null/is ignored
- *
- * "response" is owned by caller, and should not be modified or
- * freed by callee
- *
- * RIL_onRequestComplete will return as soon as possible
- */
-void testOnRequestComplete(RIL_Token t, RIL_Errno e,
- void *response, size_t responselen) {
- DBG("testOnRequestComplete E: token=%p rilErrCode=%d data=%p datalen=%d",
- t, e, response, responselen);
- DBG("testOnRequestComplete X:");
-}
-
-/**
- * "unsolResponse" is one of RIL_UNSOL_RESPONSE_*
- * "data" is pointer to data defined for that RIL_UNSOL_RESPONSE_*
- *
- * "data" is owned by caller, and should not be modified or freed by callee
- */
-void testOnUnsolicitedResponse(int unsolResponse, const void *data,
- size_t datalen) {
- DBG("testOnUnsolicitedResponse ignoring");
-}
-
-/**
- * Call user-specifed "callback" function on on the same thread that
- * RIL_RequestFunc is called. If "relativeTime" is specified, then it specifies
- * a relative time value at which the callback is invoked. If relativeTime is
- * NULL or points to a 0-filled structure, the callback will be invoked as
- * soon as possible
- */
-void testRequestTimedCallback(RIL_TimedCallback callback,
- void *param, const struct timeval *relativeTime) {
- DBG("testRequestTimedCallback ignoring");
-}
-
-#if 0
-class UnsolicitedThread : public WorkerThread {
- private:
- v8::Handle<v8::Context> context_;
-
- public:
- UnsolicitedThread(v8::Handle<v8::Context> context) :
- context_(context) {
- }
-
- int OnUnsolicitedTick(int tick) {
- v8::HandleScope handle_scope;
-
- // Get handle to onUnslicitedTick.
- v8::Handle<v8::String> name = v8::String::New("onUnsolicitedTick");
- v8::Handle<v8::Value> functionValue = context_->Global()->Get(name);
- v8::Handle<v8::Function> onUnsolicitedTick =
- v8::Handle<v8::Function>::Cast(functionValue);
-
- // Create the argument array
- v8::Handle<v8::Value> v8TickValue = v8::Number::New(tick);
- v8::Handle<v8::Value> argv[1] = { v8TickValue };
-
- v8::Handle<v8::Value> resultValue =
- onUnsolicitedTick->Call(context_->Global(), 1, argv);
- int result = int(resultValue->NumberValue());
- return result;
- }
-
- void * Worker(void *param)
- {
- ALOGD("UnsolicitedThread::Worker E param=%p", param);
-
- v8::Locker locker;
-
- for (int i = 0; isRunning(); i++) {
- // Get access and setup scope
- v8::HandleScope handle_scope;
- v8::Context::Scope context_scope(context_);
-
- // Do it
- int sleepTime = OnUnsolicitedTick(i);
-
- // Wait
- v8::Unlocker unlocker;
- sleep(sleepTime);
- v8::Locker locker;
- }
-
- ALOGD("UnsolicitedThread::Worker X param=%p", param);
-
- return NULL;
- }
-};
-#endif
-
-void startMockRil(v8::Handle<v8::Context> context) {
- v8::HandleScope handle_scope;
- v8::TryCatch try_catch;
-
- // Get handle to startMockRil and call it.
- v8::Handle<v8::String> name = v8::String::New("startMockRil");
- v8::Handle<v8::Value> functionValue = context->Global()->Get(name);
- v8::Handle<v8::Function> start =
- v8::Handle<v8::Function>::Cast(functionValue);
-
- v8::Handle<v8::Value> result = start->Call(context->Global(), 0, NULL);
- if (try_catch.HasCaught()) {
- ALOGE("startMockRil error");
- ReportException(&try_catch);
- ALOGE("FATAL ERROR: Unsable to startMockRil.");
- } else {
- v8::String::Utf8Value result_string(result);
- ALOGE("startMockRil result=%s", ToCString(result_string));
- }
-
-}
-
-
-const RIL_RadioFunctions *RIL_Init(const struct RIL_Env *env, int argc,
- char **argv) {
- int ret;
- pthread_attr_t attr;
-
- ALOGD("RIL_Init E: ----------------");
-
- // Initialize V8
- v8::V8::Initialize();
-
- // We're going to use multiple threads need to start locked
- v8::Locker locker;
-
- // Initialize modules
- protobuf_v8::Init();
- WorkerV8Init();
-
- // Make a context and setup a scope
- v8::Persistent<v8::Context> context = makeJsContext();
- v8::Context::Scope context_scope(context);
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- // Initialize modules needing context
- ctrlServerInit(context);
-
- s_rilenv = &testEnv;
-
- // load/run mock_ril.js
- char *buffer;
- int status = ReadFile("/sdcard/data/mock_ril.js", &buffer);
- if (status == 0) {
- runJs(context, &try_catch, "mock_ril.js", buffer);
- if (try_catch.HasCaught()) {
- // TODO: Change to event this is fatal
- ALOGE("FATAL ERROR: Unable to run mock_ril.js");
- }
- }
-
- s_rilenv = env;
- requestsInit(context, &s_requestWorkerQueue);
- responsesInit(context);
-
-#if 0
- ALOGD("RIL_Init run tests #####################");
- testJsSupport(context);
- testRequests(context);
- experiments(context);
- testWorker();
- testWorkerV8(context);
- ALOGD("RIL_Init tests completed ###############");
-#endif
-
- // Register our call backs so when we startMockRil
- // and it wants to send unsolicited messages the
- // mock ril is registered
- RIL_register(&s_callbacks);
-
- // Start the mock ril
- startMockRil(context);
-
-#if 0
- UnsolicitedThread *ut = new UnsolicitedThread(context);
- ut->Run(NULL);
-#endif
-
- ALOGD("RIL_Init X: ----------------");
- return &s_callbacks;
-}
diff --git a/mock-ril/src/cpp/mock_ril.h b/mock-ril/src/cpp/mock_ril.h
deleted file mode 100644
index 38745d6..0000000
--- a/mock-ril/src/cpp/mock_ril.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 MOCK_RIL_MOCK_RIL_H_
-#define MOCK_RIL_MOCK_RIL_H_
-
-#include "ril.h"
-
-extern const struct RIL_Env *s_rilenv;
-
-#endif // MOCK_RIL_MOCK_RIL_H_
diff --git a/mock-ril/src/cpp/msgheader.pb.cpp b/mock-ril/src/cpp/msgheader.pb.cpp
deleted file mode 100644
index dd10c94..0000000
--- a/mock-ril/src/cpp/msgheader.pb.cpp
+++ /dev/null
@@ -1,429 +0,0 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-
-#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
-#include "hardware/ril/mock-ril/src/proto/msgheader.pb.h"
-#include <google/protobuf/stubs/once.h>
-#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/wire_format_lite_inl.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/reflection_ops.h>
-#include <google/protobuf/wire_format.h>
-// @@protoc_insertion_point(includes)
-
-namespace communication {
-
-namespace {
-
-const ::google::protobuf::Descriptor* MsgHeader_descriptor_ = NULL;
-const ::google::protobuf::internal::GeneratedMessageReflection*
- MsgHeader_reflection_ = NULL;
-
-} // namespace
-
-
-void protobuf_AssignDesc_msgheader_2eproto() {
- protobuf_AddDesc_msgheader_2eproto();
- const ::google::protobuf::FileDescriptor* file =
- ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
- "msgheader.proto");
- GOOGLE_CHECK(file != NULL);
- MsgHeader_descriptor_ = file->message_type(0);
- static const int MsgHeader_offsets_[4] = {
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MsgHeader, cmd_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MsgHeader, length_data_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MsgHeader, status_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MsgHeader, token_),
- };
- MsgHeader_reflection_ =
- new ::google::protobuf::internal::GeneratedMessageReflection(
- MsgHeader_descriptor_,
- MsgHeader::default_instance_,
- MsgHeader_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MsgHeader, _has_bits_[0]),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MsgHeader, _unknown_fields_),
- -1,
- ::google::protobuf::DescriptorPool::generated_pool(),
- ::google::protobuf::MessageFactory::generated_factory(),
- sizeof(MsgHeader));
-}
-
-namespace {
-
-GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
- ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
- &protobuf_AssignDesc_msgheader_2eproto);
-}
-
-void protobuf_RegisterTypes(const ::std::string&) {
- protobuf_AssignDescriptorsOnce();
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- MsgHeader_descriptor_, &MsgHeader::default_instance());
-}
-
-} // namespace
-
-void protobuf_ShutdownFile_msgheader_2eproto() {
- delete MsgHeader::default_instance_;
- delete MsgHeader_reflection_;
-}
-
-void protobuf_AddDesc_msgheader_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- "\n\017msgheader.proto\022\rcommunication\"L\n\tMsgH"
- "eader\022\013\n\003cmd\030\001 \002(\r\022\023\n\013length_data\030\002 \002(\r\022"
- "\016\n\006status\030\003 \001(\r\022\r\n\005token\030\004 \001(\004B$\n\"com.an"
- "droid.internal.communication", 148);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "msgheader.proto", &protobuf_RegisterTypes);
- MsgHeader::default_instance_ = new MsgHeader();
- MsgHeader::default_instance_->InitAsDefaultInstance();
- ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_msgheader_2eproto);
-}
-
-// Force AddDescriptors() to be called at static initialization time.
-struct StaticDescriptorInitializer_msgheader_2eproto {
- StaticDescriptorInitializer_msgheader_2eproto() {
- protobuf_AddDesc_msgheader_2eproto();
- }
-} static_descriptor_initializer_msgheader_2eproto_;
-
-
-// ===================================================================
-
-#ifndef _MSC_VER
-const int MsgHeader::kCmdFieldNumber;
-const int MsgHeader::kLengthDataFieldNumber;
-const int MsgHeader::kStatusFieldNumber;
-const int MsgHeader::kTokenFieldNumber;
-#endif // !_MSC_VER
-
-MsgHeader::MsgHeader()
- : ::google::protobuf::Message() {
- SharedCtor();
-}
-
-void MsgHeader::InitAsDefaultInstance() {
-}
-
-MsgHeader::MsgHeader(const MsgHeader& from)
- : ::google::protobuf::Message() {
- SharedCtor();
- MergeFrom(from);
-}
-
-void MsgHeader::SharedCtor() {
- _cached_size_ = 0;
- cmd_ = 0u;
- length_data_ = 0u;
- status_ = 0u;
- token_ = GOOGLE_ULONGLONG(0);
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
-}
-
-MsgHeader::~MsgHeader() {
- SharedDtor();
-}
-
-void MsgHeader::SharedDtor() {
- if (this != default_instance_) {
- }
-}
-
-void MsgHeader::SetCachedSize(int size) const {
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
-}
-const ::google::protobuf::Descriptor* MsgHeader::descriptor() {
- protobuf_AssignDescriptorsOnce();
- return MsgHeader_descriptor_;
-}
-
-const MsgHeader& MsgHeader::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_msgheader_2eproto(); return *default_instance_;
-}
-
-MsgHeader* MsgHeader::default_instance_ = NULL;
-
-MsgHeader* MsgHeader::New() const {
- return new MsgHeader;
-}
-
-void MsgHeader::Clear() {
- if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
- cmd_ = 0u;
- length_data_ = 0u;
- status_ = 0u;
- token_ = GOOGLE_ULONGLONG(0);
- }
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
- mutable_unknown_fields()->Clear();
-}
-
-bool MsgHeader::MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
- ::google::protobuf::uint32 tag;
- while ((tag = input->ReadTag()) != 0) {
- switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
- // required uint32 cmd = 1;
- case 1: {
- if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
- DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
- ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
- input, &cmd_)));
- _set_bit(0);
- } else {
- goto handle_uninterpreted;
- }
- if (input->ExpectTag(16)) goto parse_length_data;
- break;
- }
-
- // required uint32 length_data = 2;
- case 2: {
- if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
- parse_length_data:
- DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
- ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
- input, &length_data_)));
- _set_bit(1);
- } else {
- goto handle_uninterpreted;
- }
- if (input->ExpectTag(24)) goto parse_status;
- break;
- }
-
- // optional uint32 status = 3;
- case 3: {
- if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
- parse_status:
- DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
- ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
- input, &status_)));
- _set_bit(2);
- } else {
- goto handle_uninterpreted;
- }
- if (input->ExpectTag(32)) goto parse_token;
- break;
- }
-
- // optional uint64 token = 4;
- case 4: {
- if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
- parse_token:
- DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
- ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
- input, &token_)));
- _set_bit(3);
- } else {
- goto handle_uninterpreted;
- }
- if (input->ExpectAtEnd()) return true;
- break;
- }
-
- default: {
- handle_uninterpreted:
- if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
- ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
- return true;
- }
- DO_(::google::protobuf::internal::WireFormat::SkipField(
- input, tag, mutable_unknown_fields()));
- break;
- }
- }
- }
- return true;
-#undef DO_
-}
-
-void MsgHeader::SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const {
- // required uint32 cmd = 1;
- if (_has_bit(0)) {
- ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->cmd(), output);
- }
-
- // required uint32 length_data = 2;
- if (_has_bit(1)) {
- ::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->length_data(), output);
- }
-
- // optional uint32 status = 3;
- if (_has_bit(2)) {
- ::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->status(), output);
- }
-
- // optional uint64 token = 4;
- if (_has_bit(3)) {
- ::google::protobuf::internal::WireFormatLite::WriteUInt64(4, this->token(), output);
- }
-
- if (!unknown_fields().empty()) {
- ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- unknown_fields(), output);
- }
-}
-
-::google::protobuf::uint8* MsgHeader::SerializeWithCachedSizesToArray(
- ::google::protobuf::uint8* target) const {
- // required uint32 cmd = 1;
- if (_has_bit(0)) {
- target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->cmd(), target);
- }
-
- // required uint32 length_data = 2;
- if (_has_bit(1)) {
- target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(2, this->length_data(), target);
- }
-
- // optional uint32 status = 3;
- if (_has_bit(2)) {
- target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(3, this->status(), target);
- }
-
- // optional uint64 token = 4;
- if (_has_bit(3)) {
- target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(4, this->token(), target);
- }
-
- if (!unknown_fields().empty()) {
- target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- unknown_fields(), target);
- }
- return target;
-}
-
-int MsgHeader::ByteSize() const {
- int total_size = 0;
-
- if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
- // required uint32 cmd = 1;
- if (has_cmd()) {
- total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::UInt32Size(
- this->cmd());
- }
-
- // required uint32 length_data = 2;
- if (has_length_data()) {
- total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::UInt32Size(
- this->length_data());
- }
-
- // optional uint32 status = 3;
- if (has_status()) {
- total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::UInt32Size(
- this->status());
- }
-
- // optional uint64 token = 4;
- if (has_token()) {
- total_size += 1 +
- ::google::protobuf::internal::WireFormatLite::UInt64Size(
- this->token());
- }
-
- }
- if (!unknown_fields().empty()) {
- total_size +=
- ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- unknown_fields());
- }
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
- return total_size;
-}
-
-void MsgHeader::MergeFrom(const ::google::protobuf::Message& from) {
- GOOGLE_CHECK_NE(&from, this);
- const MsgHeader* source =
- ::google::protobuf::internal::dynamic_cast_if_available<const MsgHeader*>(
- &from);
- if (source == NULL) {
- ::google::protobuf::internal::ReflectionOps::Merge(from, this);
- } else {
- MergeFrom(*source);
- }
-}
-
-void MsgHeader::MergeFrom(const MsgHeader& from) {
- GOOGLE_CHECK_NE(&from, this);
- if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
- if (from._has_bit(0)) {
- set_cmd(from.cmd());
- }
- if (from._has_bit(1)) {
- set_length_data(from.length_data());
- }
- if (from._has_bit(2)) {
- set_status(from.status());
- }
- if (from._has_bit(3)) {
- set_token(from.token());
- }
- }
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
-}
-
-void MsgHeader::CopyFrom(const ::google::protobuf::Message& from) {
- if (&from == this) return;
- Clear();
- MergeFrom(from);
-}
-
-void MsgHeader::CopyFrom(const MsgHeader& from) {
- if (&from == this) return;
- Clear();
- MergeFrom(from);
-}
-
-bool MsgHeader::IsInitialized() const {
- if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false;
-
- return true;
-}
-
-void MsgHeader::Swap(MsgHeader* other) {
- if (other != this) {
- std::swap(cmd_, other->cmd_);
- std::swap(length_data_, other->length_data_);
- std::swap(status_, other->status_);
- std::swap(token_, other->token_);
- std::swap(_has_bits_[0], other->_has_bits_[0]);
- _unknown_fields_.Swap(&other->_unknown_fields_);
- std::swap(_cached_size_, other->_cached_size_);
- }
-}
-
-::google::protobuf::Metadata MsgHeader::GetMetadata() const {
- protobuf_AssignDescriptorsOnce();
- ::google::protobuf::Metadata metadata;
- metadata.descriptor = MsgHeader_descriptor_;
- metadata.reflection = MsgHeader_reflection_;
- return metadata;
-}
-
-
-// @@protoc_insertion_point(namespace_scope)
-
-} // namespace communication
-
-// @@protoc_insertion_point(global_scope)
diff --git a/mock-ril/src/cpp/msgheader.pb.h b/mock-ril/src/cpp/msgheader.pb.h
deleted file mode 100644
index a98bf3e..0000000
--- a/mock-ril/src/cpp/msgheader.pb.h
+++ /dev/null
@@ -1,237 +0,0 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: msgheader.proto
-
-#ifndef PROTOBUF_msgheader_2eproto__INCLUDED
-#define PROTOBUF_msgheader_2eproto__INCLUDED
-
-#include <string>
-
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 2003000
-#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
-#error your headers.
-#endif
-#if 2003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
-#error This file was generated by an older version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please
-#error regenerate this file with a newer version of protoc.
-#endif
-
-#include <google/protobuf/generated_message_util.h>
-#include <google/protobuf/repeated_field.h>
-#include <google/protobuf/extension_set.h>
-#include <google/protobuf/generated_message_reflection.h>
-// @@protoc_insertion_point(includes)
-
-namespace communication {
-
-// Internal implementation detail -- do not call these.
-void protobuf_AddDesc_msgheader_2eproto();
-void protobuf_AssignDesc_msgheader_2eproto();
-void protobuf_ShutdownFile_msgheader_2eproto();
-
-class MsgHeader;
-
-// ===================================================================
-
-class MsgHeader : public ::google::protobuf::Message {
- public:
- MsgHeader();
- virtual ~MsgHeader();
-
- MsgHeader(const MsgHeader& from);
-
- inline MsgHeader& operator=(const MsgHeader& from) {
- CopyFrom(from);
- return *this;
- }
-
- inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
- return _unknown_fields_;
- }
-
- inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
- return &_unknown_fields_;
- }
-
- static const ::google::protobuf::Descriptor* descriptor();
- static const MsgHeader& default_instance();
-
- void Swap(MsgHeader* other);
-
- // implements Message ----------------------------------------------
-
- MsgHeader* New() const;
- void CopyFrom(const ::google::protobuf::Message& from);
- void MergeFrom(const ::google::protobuf::Message& from);
- void CopyFrom(const MsgHeader& from);
- void MergeFrom(const MsgHeader& from);
- void Clear();
- bool IsInitialized() const;
-
- int ByteSize() const;
- bool MergePartialFromCodedStream(
- ::google::protobuf::io::CodedInputStream* input);
- void SerializeWithCachedSizes(
- ::google::protobuf::io::CodedOutputStream* output) const;
- ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
- int GetCachedSize() const { return _cached_size_; }
- private:
- void SharedCtor();
- void SharedDtor();
- void SetCachedSize(int size) const;
- public:
-
- ::google::protobuf::Metadata GetMetadata() const;
-
- // nested types ----------------------------------------------------
-
- // accessors -------------------------------------------------------
-
- // required uint32 cmd = 1;
- inline bool has_cmd() const;
- inline void clear_cmd();
- static const int kCmdFieldNumber = 1;
- inline ::google::protobuf::uint32 cmd() const;
- inline void set_cmd(::google::protobuf::uint32 value);
-
- // required uint32 length_data = 2;
- inline bool has_length_data() const;
- inline void clear_length_data();
- static const int kLengthDataFieldNumber = 2;
- inline ::google::protobuf::uint32 length_data() const;
- inline void set_length_data(::google::protobuf::uint32 value);
-
- // optional uint32 status = 3;
- inline bool has_status() const;
- inline void clear_status();
- static const int kStatusFieldNumber = 3;
- inline ::google::protobuf::uint32 status() const;
- inline void set_status(::google::protobuf::uint32 value);
-
- // optional uint64 token = 4;
- inline bool has_token() const;
- inline void clear_token();
- static const int kTokenFieldNumber = 4;
- inline ::google::protobuf::uint64 token() const;
- inline void set_token(::google::protobuf::uint64 value);
-
- // @@protoc_insertion_point(class_scope:communication.MsgHeader)
- private:
- ::google::protobuf::UnknownFieldSet _unknown_fields_;
- mutable int _cached_size_;
-
- ::google::protobuf::uint32 cmd_;
- ::google::protobuf::uint32 length_data_;
- ::google::protobuf::uint32 status_;
- ::google::protobuf::uint64 token_;
- friend void protobuf_AddDesc_msgheader_2eproto();
- friend void protobuf_AssignDesc_msgheader_2eproto();
- friend void protobuf_ShutdownFile_msgheader_2eproto();
-
- ::google::protobuf::uint32 _has_bits_[(4 + 31) / 32];
-
- // WHY DOES & HAVE LOWER PRECEDENCE THAN != !?
- inline bool _has_bit(int index) const {
- return (_has_bits_[index / 32] & (1u << (index % 32))) != 0;
- }
- inline void _set_bit(int index) {
- _has_bits_[index / 32] |= (1u << (index % 32));
- }
- inline void _clear_bit(int index) {
- _has_bits_[index / 32] &= ~(1u << (index % 32));
- }
-
- void InitAsDefaultInstance();
- static MsgHeader* default_instance_;
-};
-// ===================================================================
-
-
-// ===================================================================
-
-// MsgHeader
-
-// required uint32 cmd = 1;
-inline bool MsgHeader::has_cmd() const {
- return _has_bit(0);
-}
-inline void MsgHeader::clear_cmd() {
- cmd_ = 0u;
- _clear_bit(0);
-}
-inline ::google::protobuf::uint32 MsgHeader::cmd() const {
- return cmd_;
-}
-inline void MsgHeader::set_cmd(::google::protobuf::uint32 value) {
- _set_bit(0);
- cmd_ = value;
-}
-
-// required uint32 length_data = 2;
-inline bool MsgHeader::has_length_data() const {
- return _has_bit(1);
-}
-inline void MsgHeader::clear_length_data() {
- length_data_ = 0u;
- _clear_bit(1);
-}
-inline ::google::protobuf::uint32 MsgHeader::length_data() const {
- return length_data_;
-}
-inline void MsgHeader::set_length_data(::google::protobuf::uint32 value) {
- _set_bit(1);
- length_data_ = value;
-}
-
-// optional uint32 status = 3;
-inline bool MsgHeader::has_status() const {
- return _has_bit(2);
-}
-inline void MsgHeader::clear_status() {
- status_ = 0u;
- _clear_bit(2);
-}
-inline ::google::protobuf::uint32 MsgHeader::status() const {
- return status_;
-}
-inline void MsgHeader::set_status(::google::protobuf::uint32 value) {
- _set_bit(2);
- status_ = value;
-}
-
-// optional uint64 token = 4;
-inline bool MsgHeader::has_token() const {
- return _has_bit(3);
-}
-inline void MsgHeader::clear_token() {
- token_ = GOOGLE_ULONGLONG(0);
- _clear_bit(3);
-}
-inline ::google::protobuf::uint64 MsgHeader::token() const {
- return token_;
-}
-inline void MsgHeader::set_token(::google::protobuf::uint64 value) {
- _set_bit(3);
- token_ = value;
-}
-
-
-// @@protoc_insertion_point(namespace_scope)
-
-} // namespace communication
-
-#ifndef SWIG
-namespace google {
-namespace protobuf {
-
-
-} // namespace google
-} // namespace protobuf
-#endif // SWIG
-
-// @@protoc_insertion_point(global_scope)
-
-#endif // PROTOBUF_msgheader_2eproto__INCLUDED
diff --git a/mock-ril/src/cpp/node_buffer.cpp b/mock-ril/src/cpp/node_buffer.cpp
deleted file mode 100644
index 4c08a26..0000000
--- a/mock-ril/src/cpp/node_buffer.cpp
+++ /dev/null
@@ -1,642 +0,0 @@
-/**
- * Copied from node_buffer.cc
- * see http://www.nodejs.org/
- *
- * Node's license follows:
- *
- * Copyright 2009, 2010 Ryan Lienhart Dahl. All rights reserved.
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
- * IN THE SOFTWARE.
- */
-
-#include "node_buffer.h"
-
-#include <assert.h>
-#include <stdlib.h> // malloc, free
-#include <v8.h>
-
-#include <string.h> // memcpy
-
-#include <arpa/inet.h> // htons, htonl
-
-#include "logging.h"
-#include "node_util.h"
-#include "util.h"
-
-//#define BUFFER_DEBUG
-#ifdef BUFFER_DEBUG
-
-#define DBG(...) ALOGD(__VA_ARGS__)
-
-#else
-
-#define DBG(...)
-
-#endif
-
-#define MIN(a,b) ((a) < (b) ? (a) : (b))
-
-using namespace v8;
-
-#define SLICE_ARGS(start_arg, end_arg) \
- if (!start_arg->IsInt32() || !end_arg->IsInt32()) { \
- return ThrowException(Exception::TypeError( \
- v8::String::New("Bad argument."))); \
- } \
- int32_t start = start_arg->Int32Value(); \
- int32_t end = end_arg->Int32Value(); \
- if (start < 0 || end < 0) { \
- return ThrowException(Exception::TypeError( \
- v8::String::New("Bad argument."))); \
- } \
- if (!(start <= end)) { \
- return ThrowException(Exception::Error( \
- v8::String::New("Must have start <= end"))); \
- } \
- if ((size_t)end > parent->length_) { \
- return ThrowException(Exception::Error( \
- v8::String::New("end cannot be longer than parent.length"))); \
- }
-
-static Persistent<String> length_symbol;
-static Persistent<String> chars_written_sym;
-static Persistent<String> write_sym;
-Persistent<FunctionTemplate> Buffer::constructor_template;
-
-
-// Each javascript Buffer object is backed by a Blob object.
-// the Blob is just a C-level chunk of bytes.
-// It has a reference count.
-struct Blob_ {
- unsigned int refs;
- size_t length;
- char *data;
-};
-typedef struct Blob_ Blob;
-
-
-static inline Blob * blob_new(size_t length) {
- DBG("blob_new E");
- Blob * blob = (Blob*) malloc(sizeof(Blob));
- if (!blob) return NULL;
-
- blob->data = (char*) malloc(length);
- if (!blob->data) {
- DBG("blob_new X no memory for data");
- free(blob);
- return NULL;
- }
-
- V8::AdjustAmountOfExternalAllocatedMemory(sizeof(Blob) + length);
- blob->length = length;
- blob->refs = 0;
- DBG("blob_new X");
- return blob;
-}
-
-
-static inline void blob_ref(Blob *blob) {
- blob->refs++;
-}
-
-
-static inline void blob_unref(Blob *blob) {
- assert(blob->refs > 0);
- if (--blob->refs == 0) {
- DBG("blob_unref == 0");
- //fprintf(stderr, "free %d bytes\n", blob->length);
- V8::AdjustAmountOfExternalAllocatedMemory(-(sizeof(Blob) + blob->length));
- free(blob->data);
- free(blob);
- DBG("blob_unref blob and its data freed");
- }
-}
-
-#if 0
-// When someone calls buffer.asciiSlice, data is not copied. Instead V8
-// references in the underlying Blob with this ExternalAsciiStringResource.
-class AsciiSliceExt: public String::ExternalAsciiStringResource {
- friend class Buffer;
- public:
- AsciiSliceExt(Buffer *parent, size_t start, size_t end) {
- blob_ = parent->blob();
- blob_ref(blob_);
-
- assert(start <= end);
- length_ = end - start;
- assert(start + length_ <= parent->length());
- data_ = parent->data() + start;
- }
-
-
- ~AsciiSliceExt() {
- //fprintf(stderr, "free ascii slice (%d refs left)\n", blob_->refs);
- blob_unref(blob_);
- }
-
-
- const char* data() const { return data_; }
- size_t length() const { return length_; }
-
- private:
- const char *data_;
- size_t length_;
- Blob *blob_;
-};
-#endif
-
-Buffer* Buffer::New(size_t size) {
- DBG("Buffer::New(size) E");
- HandleScope scope;
-
- Local<Value> arg = Integer::NewFromUnsigned(size);
- Local<Object> b = constructor_template->GetFunction()->NewInstance(1, &arg);
-
- DBG("Buffer::New(size) X");
- return ObjectWrap::Unwrap<Buffer>(b);
-}
-
-
-Handle<Value> Buffer::New(const Arguments &args) {
- DBG("Buffer::New(args) E");
- HandleScope scope;
-
- Buffer *buffer;
- if ((args.Length() == 0) || args[0]->IsInt32()) {
- size_t length = 0;
- if (args[0]->IsInt32()) {
- length = args[0]->Uint32Value();
- }
- buffer = new Buffer(length);
- } else if (args[0]->IsArray()) {
- Local<Array> a = Local<Array>::Cast(args[0]);
- buffer = new Buffer(a->Length());
- char *p = buffer->data();
- for (unsigned int i = 0; i < a->Length(); i++) {
- p[i] = a->Get(i)->Uint32Value();
- }
- } else if (args[0]->IsString()) {
- Local<String> s = args[0]->ToString();
- enum encoding e = ParseEncoding(args[1], UTF8);
- int length = e == UTF8 ? s->Utf8Length() : s->Length();
- buffer = new Buffer(length);
- } else if (Buffer::HasInstance(args[0]) && args.Length() > 2) {
- // var slice = new Buffer(buffer, 123, 130);
- // args: parent, start, end
- Buffer *parent = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject());
- SLICE_ARGS(args[1], args[2])
- buffer = new Buffer(parent, start, end);
- } else {
- DBG("Buffer::New(args) X Bad argument");
- return ThrowException(Exception::TypeError(String::New("Bad argument")));
- }
-
- buffer->Wrap(args.This());
- args.This()->SetIndexedPropertiesToExternalArrayData(buffer->data(),
- kExternalUnsignedByteArray,
- buffer->length());
- args.This()->Set(length_symbol, Integer::New(buffer->length_));
-
- if (args[0]->IsString()) {
- if (write_sym.IsEmpty()) {
- write_sym = Persistent<String>::New(String::NewSymbol("write"));
- }
-
- Local<Value> write_v = args.This()->Get(write_sym);
- assert(write_v->IsFunction());
- Local<Function> write = Local<Function>::Cast(write_v);
-
- Local<Value> argv[2] = { args[0], args[1] };
-
- TryCatch try_catch;
-
- write->Call(args.This(), 2, argv);
-
- if (try_catch.HasCaught()) {
- ReportException(&try_catch);
- }
- }
-
- DBG("Buffer::New(args) X");
- return args.This();
-}
-
-
-Buffer::Buffer(size_t length) : ObjectWrap() {
- DBG("Buffer::Buffer(length) E");
- blob_ = blob_new(length);
- off_ = 0;
- length_ = length;
-
- blob_ref(blob_);
-
- V8::AdjustAmountOfExternalAllocatedMemory(sizeof(Buffer));
- DBG("Buffer::Buffer(length) X");
-}
-
-
-Buffer::Buffer(Buffer *parent, size_t start, size_t end) : ObjectWrap() {
- DBG("Buffer::Buffer(parent, start, end) E");
- blob_ = parent->blob_;
- assert(blob_->refs > 0);
- blob_ref(blob_);
-
- assert(start <= end);
- off_ = parent->off_ + start;
- length_ = end - start;
- assert(length_ <= parent->length_);
-
- V8::AdjustAmountOfExternalAllocatedMemory(sizeof(Buffer));
- DBG("Buffer::Buffer(parent, start, end) X");
-}
-
-
-Buffer::~Buffer() {
- DBG("Buffer::~Buffer() E");
- assert(blob_->refs > 0);
- //fprintf(stderr, "free buffer (%d refs left)\n", blob_->refs);
- blob_unref(blob_);
- V8::AdjustAmountOfExternalAllocatedMemory(-static_cast<long int>(sizeof(Buffer)));
- DBG("Buffer::~Buffer() X");
-}
-
-
-char* Buffer::data() {
- char *p = blob_->data + off_;
- DBG("Buffer::data() EX p=%p", p);
- return p;
-}
-
-void Buffer::NewBlob(size_t length) {
- DBG("Buffer::NewBlob(length) E");
- blob_unref(blob_);
- blob_ = blob_new(length);
- off_ = 0;
- length_ = length;
-
- blob_ref(blob_);
-
- V8::AdjustAmountOfExternalAllocatedMemory(sizeof(Buffer));
- DBG("Buffer::NewBlob(length) X");
-}
-
-
-Handle<Value> Buffer::BinarySlice(const Arguments &args) {
- DBG("Buffer::BinarySlice(args) E");
- HandleScope scope;
- Buffer *parent = ObjectWrap::Unwrap<Buffer>(args.This());
- SLICE_ARGS(args[0], args[1])
-
- const char *data = const_cast<char*>(parent->data() + start);
- //Local<String> string = String::New(data, end - start);
-
- Local<Value> b = Encode(data, end - start, BINARY);
-
- DBG("Buffer::BinarySlice(args) X");
- return scope.Close(b);
-}
-
-
-Handle<Value> Buffer::AsciiSlice(const Arguments &args) {
- DBG("Buffer::AsciiSlice(args) E");
- HandleScope scope;
- Buffer *parent = ObjectWrap::Unwrap<Buffer>(args.This());
- SLICE_ARGS(args[0], args[1])
-
-#if 0
- AsciiSliceExt *ext = new AsciiSliceExt(parent, start, end);
- Local<String> string = String::NewExternal(ext);
- // There should be at least two references to the blob now - the parent
- // and the slice.
- assert(parent->blob_->refs >= 2);
-#endif
-
- const char *data = const_cast<char*>(parent->data() + start);
- Local<String> string = String::New(data, end - start);
-
-
- DBG("Buffer::AsciiSlice(args) X");
- return scope.Close(string);
-}
-
-
-Handle<Value> Buffer::Utf8Slice(const Arguments &args) {
- DBG("Buffer::Utf8Slice(args) E");
- HandleScope scope;
- Buffer *parent = ObjectWrap::Unwrap<Buffer>(args.This());
- SLICE_ARGS(args[0], args[1])
- const char *data = const_cast<char*>(parent->data() + start);
- Local<String> string = String::New(data, end - start);
- DBG("Buffer::Utf8Slice(args) X");
- return scope.Close(string);
-}
-
-
-Handle<Value> Buffer::Slice(const Arguments &args) {
- DBG("Buffer::Slice(args) E");
- HandleScope scope;
- Local<Value> argv[3] = { args.This(), args[0], args[1] };
- Local<Object> slice =
- constructor_template->GetFunction()->NewInstance(3, argv);
- DBG("Buffer::Slice(args) X");
- return scope.Close(slice);
-}
-
-
-// var bytesCopied = buffer.copy(target, targetStart, sourceStart, sourceEnd);
-Handle<Value> Buffer::Copy(const Arguments &args) {
- DBG("Buffer::Copy(args) E");
- HandleScope scope;
-
- Buffer *source = ObjectWrap::Unwrap<Buffer>(args.This());
-
- if (!Buffer::HasInstance(args[0])) {
- DBG("Buffer::Copy(args) X arg[0] not buffer");
- return ThrowException(Exception::TypeError(String::New(
- "First arg should be a Buffer")));
- }
-
- Buffer *target = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject());
-
- ssize_t target_start = args[1]->Int32Value();
- ssize_t source_start = args[2]->Int32Value();
- ssize_t source_end = args[3]->IsInt32() ? args[3]->Int32Value()
- : source->length();
-
- if (source_end < source_start) {
- DBG("Buffer::Copy(args) X end < start");
- return ThrowException(Exception::Error(String::New(
- "sourceEnd < sourceStart")));
- }
-
- if (target_start < 0 || ((size_t)target_start) > target->length()) {
- DBG("Buffer::Copy(args) X targetStart bad");
- return ThrowException(Exception::Error(String::New(
- "targetStart out of bounds")));
- }
-
- if (source_start < 0 || ((size_t)source_start) > source->length()) {
- DBG("Buffer::Copy(args) X base source start");
- return ThrowException(Exception::Error(String::New(
- "sourceStart out of bounds")));
- }
-
- if (source_end < 0 || ((size_t)source_end) > source->length()) {
- DBG("Buffer::Copy(args) X bad source");
- return ThrowException(Exception::Error(String::New(
- "sourceEnd out of bounds")));
- }
-
- ssize_t to_copy = MIN(source_end - source_start,
- target->length() - target_start);
-
- memcpy((void*)(target->data() + target_start),
- (const void*)(source->data() + source_start),
- to_copy);
-
- DBG("Buffer::Copy(args) X");
- return scope.Close(Integer::New(to_copy));
-}
-
-
-// var charsWritten = buffer.utf8Write(string, offset);
-Handle<Value> Buffer::Utf8Write(const Arguments &args) {
- DBG("Buffer::Utf8Write(args) X");
- HandleScope scope;
- Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args.This());
-
- if (!args[0]->IsString()) {
- DBG("Buffer::Utf8Write(args) X arg[0] not string");
- return ThrowException(Exception::TypeError(String::New(
- "Argument must be a string")));
- }
-
- Local<String> s = args[0]->ToString();
-
- size_t offset = args[1]->Int32Value();
-
- if (offset >= buffer->length_) {
- DBG("Buffer::Utf8Write(args) X offset bad");
- return ThrowException(Exception::TypeError(String::New(
- "Offset is out of bounds")));
- }
-
- const char *p = buffer->data() + offset;
-
- int char_written;
-
- int written = s->WriteUtf8((char*)p,
- buffer->length_ - offset,
- &char_written,
- String::HINT_MANY_WRITES_EXPECTED);
-
- constructor_template->GetFunction()->Set(chars_written_sym,
- Integer::New(char_written));
-
- if (written > 0 && p[written-1] == '\0') written--;
-
- DBG("Buffer::Utf8Write(args) X");
- return scope.Close(Integer::New(written));
-}
-
-
-// var charsWritten = buffer.asciiWrite(string, offset);
-Handle<Value> Buffer::AsciiWrite(const Arguments &args) {
- DBG("Buffer::AsciiWrite(args) E");
- HandleScope scope;
-
- Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args.This());
-
- if (!args[0]->IsString()) {
- DBG("Buffer::AsciiWrite(args) X arg[0] not string");
- return ThrowException(Exception::TypeError(String::New(
- "Argument must be a string")));
- }
-
- Local<String> s = args[0]->ToString();
-
- size_t offset = args[1]->Int32Value();
-
- if (offset >= buffer->length_) {
- DBG("Buffer::AsciiWrite(args) X bad offset");
- return ThrowException(Exception::TypeError(String::New(
- "Offset is out of bounds")));
- }
-
- const char *p = buffer->data() + offset;
-
- size_t towrite = MIN((unsigned long) s->Length(), buffer->length_ - offset);
-
- int written = s->WriteAscii((char*)p, 0, towrite, String::HINT_MANY_WRITES_EXPECTED);
- DBG("Buffer::AsciiWrite(args) X");
- return scope.Close(Integer::New(written));
-}
-
-
-Handle<Value> Buffer::BinaryWrite(const Arguments &args) {
- DBG("Buffer::BinaryWrite(args) E");
- HandleScope scope;
-
- Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args.This());
-
- if (!args[0]->IsString()) {
- DBG("Buffer::BinaryWrite(args) X arg[0] not string");
- return ThrowException(Exception::TypeError(String::New(
- "Argument must be a string")));
- }
-
- Local<String> s = args[0]->ToString();
-
- size_t offset = args[1]->Int32Value();
-
- if (offset >= buffer->length_) {
- DBG("Buffer::BinaryWrite(args) X offset bad");
- return ThrowException(Exception::TypeError(String::New(
- "Offset is out of bounds")));
- }
-
- char *p = (char*)buffer->data() + offset;
-
- size_t towrite = MIN((unsigned long) s->Length(), buffer->length_ - offset);
-
- int written = DecodeWrite(p, towrite, s, BINARY);
- DBG("Buffer::BinaryWrite(args) X");
- return scope.Close(Integer::New(written));
-}
-
-
-// buffer.unpack(format, index);
-// Starting at 'index', unpacks binary from the buffer into an array.
-// 'format' is a string
-//
-// FORMAT RETURNS
-// N uint32_t a 32bit unsigned integer in network byte order
-// n uint16_t a 16bit unsigned integer in network byte order
-// o uint8_t a 8bit unsigned integer
-Handle<Value> Buffer::Unpack(const Arguments &args) {
- DBG("Buffer::Unpack(args) E");
- HandleScope scope;
- Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args.This());
-
- if (!args[0]->IsString()) {
- DBG("Buffer::Unpack(args) X arg[0] not string");
- return ThrowException(Exception::TypeError(String::New(
- "Argument must be a string")));
- }
-
- String::AsciiValue format(args[0]->ToString());
- uint32_t index = args[1]->Uint32Value();
-
-#define OUT_OF_BOUNDS ThrowException(Exception::Error(String::New("Out of bounds")))
-
- Local<Array> array = Array::New(format.length());
-
- uint8_t uint8;
- uint16_t uint16;
- uint32_t uint32;
-
- for (int i = 0; i < format.length(); i++) {
- switch ((*format)[i]) {
- // 32bit unsigned integer in network byte order
- case 'N':
- if (index + 3 >= buffer->length_) return OUT_OF_BOUNDS;
- uint32 = htonl(*(uint32_t*)(buffer->data() + index));
- array->Set(Integer::New(i), Integer::NewFromUnsigned(uint32));
- index += 4;
- break;
-
- // 16bit unsigned integer in network byte order
- case 'n':
- if (index + 1 >= buffer->length_) return OUT_OF_BOUNDS;
- uint16 = htons(*(uint16_t*)(buffer->data() + index));
- array->Set(Integer::New(i), Integer::NewFromUnsigned(uint16));
- index += 2;
- break;
-
- // a single octet, unsigned.
- case 'o':
- if (index >= buffer->length_) return OUT_OF_BOUNDS;
- uint8 = (uint8_t)buffer->data()[index];
- array->Set(Integer::New(i), Integer::NewFromUnsigned(uint8));
- index += 1;
- break;
-
- default:
- DBG("Buffer::Unpack(args) X unknown format character");
- return ThrowException(Exception::Error(
- String::New("Unknown format character")));
- }
- }
-
- DBG("Buffer::Unpack(args) X");
- return scope.Close(array);
-}
-
-
-// var nbytes = Buffer.byteLength("string", "utf8")
-Handle<Value> Buffer::ByteLength(const Arguments &args) {
- DBG("Buffer::ByteLength(args) E");
- HandleScope scope;
-
- if (!args[0]->IsString()) {
- DBG("Buffer::ByteLength(args) X arg[0] not a string");
- return ThrowException(Exception::TypeError(String::New(
- "Argument must be a string")));
- }
-
- Local<String> s = args[0]->ToString();
- enum encoding e = ParseEncoding(args[1], UTF8);
-
- Local<Integer> length =
- Integer::New(e == UTF8 ? s->Utf8Length() : s->Length());
-
- DBG("Buffer::ByteLength(args) X");
- return scope.Close(length);
-}
-
-void Buffer::InitializeObjectTemplate(Handle<ObjectTemplate> target) {
- DBG("InitializeObjectTemplate(target) E:");
- HandleScope scope;
-
- length_symbol = Persistent<String>::New(String::NewSymbol("length"));
- chars_written_sym = Persistent<String>::New(String::NewSymbol("_charsWritten"));
-
- Local<FunctionTemplate> t = FunctionTemplate::New(Buffer::New);
- constructor_template = Persistent<FunctionTemplate>::New(t);
- constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
- constructor_template->SetClassName(String::NewSymbol("Buffer"));
-
- // copy free
- SET_PROTOTYPE_METHOD(constructor_template, "binarySlice", Buffer::BinarySlice);
- SET_PROTOTYPE_METHOD(constructor_template, "asciiSlice", Buffer::AsciiSlice);
- SET_PROTOTYPE_METHOD(constructor_template, "slice", Buffer::Slice);
- // TODO SET_PROTOTYPE_METHOD(t, "utf16Slice", Utf16Slice);
- // copy
- SET_PROTOTYPE_METHOD(constructor_template, "utf8Slice", Buffer::Utf8Slice);
-
- SET_PROTOTYPE_METHOD(constructor_template, "utf8Write", Buffer::Utf8Write);
- SET_PROTOTYPE_METHOD(constructor_template, "asciiWrite", Buffer::AsciiWrite);
- SET_PROTOTYPE_METHOD(constructor_template, "binaryWrite", Buffer::BinaryWrite);
- SET_PROTOTYPE_METHOD(constructor_template, "unpack", Buffer::Unpack);
- SET_PROTOTYPE_METHOD(constructor_template, "copy", Buffer::Copy);
-
- SET_PROTOTYPE_METHOD(constructor_template, "byteLength", Buffer::ByteLength);
-
- target->Set(String::NewSymbol("Buffer"), constructor_template);
- DBG("InitializeObjectTemplate(target) X:");
-}
diff --git a/mock-ril/src/cpp/node_buffer.h b/mock-ril/src/cpp/node_buffer.h
deleted file mode 100644
index 0d3d774..0000000
--- a/mock-ril/src/cpp/node_buffer.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * Copied from node_buffer.h
- * see http://www.nodejs.org/
- *
- * Node's license follows:
- *
- * Copyright 2009, 2010 Ryan Lienhart Dahl. All rights reserved.
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
- * IN THE SOFTWARE.
- */
-
-#ifndef MOCK_RIL_NODE_BUFFER_H_
-#define MOCK_RIL_NODE_BUFFER_H_
-
-#include <v8.h>
-#include "node_object_wrap.h"
-
-/* A buffer is a chunk of memory stored outside the V8 heap, mirrored by an
- * object in javascript. The object is not totally opaque, one can access
- * individual bytes with [] and slice it into substrings or sub-buffers
- * without copying memory.
- *
- * // return an ascii encoded string - no memory iscopied
- * buffer.asciiSlide(0, 3)
- *
- * // returns another buffer - no memory is copied
- * buffer.slice(0, 3)
- *
- * Interally, each javascript buffer object is backed by a "struct buffer"
- * object. These "struct buffer" objects are either a root buffer (in the
- * case that buffer->root == NULL) or slice objects (in which case
- * buffer->root != NULL). A root buffer is only GCed once all its slices
- * are GCed.
- */
-
-
-struct Blob_;
-
-class Buffer : public ObjectWrap {
- public:
- ~Buffer();
-
- static void Initialize(v8::Handle<v8::Object> target);
- static void InitializeObjectTemplate(v8::Handle<v8::ObjectTemplate> target);
- static Buffer* New(size_t length); // public constructor
- static inline bool HasInstance(v8::Handle<v8::Value> val) {
- if (!val->IsObject()) return false;
- v8::Local<v8::Object> obj = val->ToObject();
- return constructor_template->HasInstance(obj);
- }
-
- char* data();
- size_t length() const { return length_; }
- struct Blob_* blob() const { return blob_; }
- void NewBlob(size_t length);
-
- int AsciiWrite(char *string, int offset, int length);
- int Utf8Write(char *string, int offset, int length);
-
- private:
- static v8::Persistent<v8::FunctionTemplate> constructor_template;
-
- static v8::Handle<v8::Value> New(const v8::Arguments &args);
- static v8::Handle<v8::Value> Slice(const v8::Arguments &args);
- static v8::Handle<v8::Value> BinarySlice(const v8::Arguments &args);
- static v8::Handle<v8::Value> AsciiSlice(const v8::Arguments &args);
- static v8::Handle<v8::Value> Utf8Slice(const v8::Arguments &args);
- static v8::Handle<v8::Value> BinaryWrite(const v8::Arguments &args);
- static v8::Handle<v8::Value> AsciiWrite(const v8::Arguments &args);
- static v8::Handle<v8::Value> Utf8Write(const v8::Arguments &args);
- static v8::Handle<v8::Value> ByteLength(const v8::Arguments &args);
- static v8::Handle<v8::Value> Unpack(const v8::Arguments &args);
- static v8::Handle<v8::Value> Copy(const v8::Arguments &args);
-
- Buffer(size_t length);
- Buffer(Buffer *parent, size_t start, size_t end);
-
- size_t off_; // offset inside blob_
- size_t length_; // length inside blob_
- struct Blob_ *blob_;
-};
-
-#endif // MOCK_RIL_NODE_BUFFER_H_
diff --git a/mock-ril/src/cpp/node_object_wrap.h b/mock-ril/src/cpp/node_object_wrap.h
deleted file mode 100644
index 1bcee62..0000000
--- a/mock-ril/src/cpp/node_object_wrap.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * Copied from node_object_wrap.h
- * see http://www.nodejs.org/
- *
- * Node's license follows:
- *
- * Copyright 2009, 2010 Ryan Lienhart Dahl. All rights reserved.
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
- * IN THE SOFTWARE.
- */
-
-#ifndef MOCK_RIL_NODE_OBJECT_WRAP_H_
-#define MOCK_RIL_NODE_OBJECT_WRAP_H_
-
-#include <v8.h>
-#include <assert.h>
-
-class ObjectWrap {
- public:
- ObjectWrap ( ) {
- refs_ = 0;
- }
-
- virtual ~ObjectWrap ( ) {
- if (!handle_.IsEmpty()) {
- assert(handle_.IsNearDeath());
- handle_->SetInternalField(0, v8::Undefined());
- handle_.Dispose();
- handle_.Clear();
- }
- }
-
- template <class T>
- static inline T* Unwrap (v8::Handle<v8::Object> handle)
- {
- assert(!handle.IsEmpty());
- assert(handle->InternalFieldCount() > 0);
- return static_cast<T*>(v8::Handle<v8::External>::Cast(
- handle->GetInternalField(0))->Value());
- }
-
- v8::Persistent<v8::Object> handle_; // ro
-
- protected:
- inline void Wrap (v8::Handle<v8::Object> handle)
- {
- assert(handle_.IsEmpty());
- assert(handle->InternalFieldCount() > 0);
- handle_ = v8::Persistent<v8::Object>::New(handle);
- handle_->SetInternalField(0, v8::External::New(this));
- MakeWeak();
- }
-
- inline void MakeWeak (void)
- {
- handle_.MakeWeak(this, WeakCallback);
- }
-
- /* Ref() marks the object as being attached to an event loop.
- * Refed objects will not be garbage collected, even if
- * all references are lost.
- */
- virtual void Ref() {
- assert(!handle_.IsEmpty());
- refs_++;
- handle_.ClearWeak();
- }
-
- /* Unref() marks an object as detached from the event loop. This is its
- * default state. When an object with a "weak" reference changes from
- * attached to detached state it will be freed. Be careful not to access
- * the object after making this call as it might be gone!
- * (A "weak reference" means an object that only has a
- * persistant handle.)
- *
- * DO NOT CALL THIS FROM DESTRUCTOR
- */
- virtual void Unref() {
- assert(!handle_.IsEmpty());
- assert(!handle_.IsWeak());
- assert(refs_ > 0);
- if (--refs_ == 0) { MakeWeak(); }
- }
-
- int refs_; // ro
-
- private:
- static void WeakCallback (v8::Persistent<v8::Value> value, void *data)
- {
- ObjectWrap *obj = static_cast<ObjectWrap*>(data);
- assert(value == obj->handle_);
- assert(!obj->refs_);
- if (value.IsNearDeath()) delete obj;
- }
-};
-
-#endif // MOCK_RIL_NODE_OBJECT_WRAP_H_
diff --git a/mock-ril/src/cpp/node_util.cpp b/mock-ril/src/cpp/node_util.cpp
deleted file mode 100644
index 5048e53..0000000
--- a/mock-ril/src/cpp/node_util.cpp
+++ /dev/null
@@ -1,144 +0,0 @@
-/**
- * Contents of this file are snippets from node.cc
- * see http://www.nodejs.org/
- *
- * Node's license follows:
- *
- * Copyright 2009, 2010 Ryan Lienhart Dahl. All rights reserved.
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- */
-#include <v8.h>
-#include <string.h>
-
-#include "logging.h"
-#include "node_object_wrap.h"
-
-#include "node_util.h"
-
-enum encoding ParseEncoding(v8::Handle<v8::Value> encoding_v, enum encoding _default) {
- v8::HandleScope scope;
-
- if (!encoding_v->IsString()) return _default;
-
- v8::String::Utf8Value encoding(encoding_v->ToString());
-
- if (strcasecmp(*encoding, "utf8") == 0) {
- return UTF8;
- } else if (strcasecmp(*encoding, "utf-8") == 0) {
- return UTF8;
- } else if (strcasecmp(*encoding, "ascii") == 0) {
- return ASCII;
- } else if (strcasecmp(*encoding, "binary") == 0) {
- return BINARY;
- } else if (strcasecmp(*encoding, "raw") == 0) {
- fprintf(stderr, "'raw' (array of integers) has been removed. "
- "Use 'binary'.\n");
- return BINARY;
- } else if (strcasecmp(*encoding, "raws") == 0) {
- fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
- "Please update your code.\n");
- return BINARY;
- } else {
- return _default;
- }
-}
-
-v8::Local<v8::Value> Encode(const void *buf, size_t len, enum encoding encoding) {
- v8::HandleScope scope;
-
- if (!len) return scope.Close(v8::String::Empty());
-
- if (encoding == BINARY) {
- const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
- uint16_t * twobytebuf = new uint16_t[len];
- for (size_t i = 0; i < len; i++) {
- // XXX is the following line platform independent?
- twobytebuf[i] = cbuf[i];
- }
- v8::Local<v8::String> chunk = v8::String::New(twobytebuf, len);
- delete [] twobytebuf; // TODO use ExternalTwoBytev8::String?
- return scope.Close(chunk);
- }
-
- // utf8 or ascii encoding
- v8::Local<v8::String> chunk = v8::String::New((const char*)buf, len);
- return scope.Close(chunk);
-}
-
-// Returns -1 if the handle was not valid for decoding
-ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
- v8::HandleScope scope;
-
- if (val->IsArray()) {
- fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
- "Use 'binary'.\n");
- assert(0);
- return -1;
- }
-
- v8::Local<v8::String> str = val->ToString();
-
- if (encoding == UTF8) return str->Utf8Length();
-
- return str->Length();
-}
-
-#ifndef MIN
-# define MIN(a, b) ((a) < (b) ? (a) : (b))
-#endif
-
-// Returns number of bytes written.
-ssize_t DecodeWrite(char *buf,
- size_t buflen,
- v8::Handle<v8::Value> val,
- enum encoding encoding) {
- v8::HandleScope scope;
-
- // XXX
- // A lot of improvement can be made here. See:
- // http://code.google.com/p/v8/issues/detail?id=270
- // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
- // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
-
- if (val->IsArray()) {
- fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
- "Use 'binary'.\n");
- assert(0);
- return -1;
- }
-
- v8::Local<v8::String> str = val->ToString();
-
- if (encoding == UTF8) {
- str->WriteUtf8(buf, buflen, NULL, v8::String::HINT_MANY_WRITES_EXPECTED);
- return buflen;
- }
-
- if (encoding == ASCII) {
- str->WriteAscii(buf, 0, buflen, v8::String::HINT_MANY_WRITES_EXPECTED);
- return buflen;
- }
-
- // THIS IS AWFUL!!! FIXME
-
- assert(encoding == BINARY);
-
- uint16_t * twobytebuf = new uint16_t[buflen];
-
- str->Write(twobytebuf, 0, buflen, v8::String::HINT_MANY_WRITES_EXPECTED);
-
- for (size_t i = 0; i < buflen; i++) {
- unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
- assert(b[1] == 0);
- buf[i] = b[0];
- }
-
- delete [] twobytebuf;
-
- return buflen;
-}
diff --git a/mock-ril/src/cpp/node_util.h b/mock-ril/src/cpp/node_util.h
deleted file mode 100644
index e19a8e7..0000000
--- a/mock-ril/src/cpp/node_util.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * Contents of this file are snippets from node.h and node.cc
- * see http://www.nodejs.org/
- *
- * Node's license follows:
- *
- * Copyright 2009, 2010 Ryan Lienhart Dahl. All rights reserved.
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- */
-
-
-#ifndef MOCK_RIL_NODE_UTIL_H_
-#define MOCK_RIL_NODE_UTIL_H_
-
-#include <v8.h>
-
-enum encoding {ASCII, UTF8, BINARY};
-
-enum encoding ParseEncoding(v8::Handle<v8::Value> encoding_v,
- enum encoding _default = BINARY);
-
-void FatalException(v8::TryCatch &try_catch);
-
-v8::Local<v8::Value> Encode(const void *buf, size_t len,
- enum encoding encoding = BINARY);
-
-// returns bytes written.
-ssize_t DecodeWrite(char *buf,
- size_t buflen,
- v8::Handle<v8::Value>,
- enum encoding encoding = BINARY);
-
-#define SET_PROTOTYPE_METHOD(templ, name, callback) \
-do { \
- v8::Local<v8::Signature> __callback##_SIG = v8::Signature::New(templ); \
- v8::Local<v8::FunctionTemplate> __callback##_TEM = \
- v8::FunctionTemplate::New(callback, v8::Handle<v8::Value>(), \
- __callback##_SIG); \
- templ->PrototypeTemplate()->Set(v8::String::NewSymbol(name), \
- __callback##_TEM); \
-} while (0)
-
-#define SET_METHOD(obj, name, callback) \
- obj->Set(v8::String::NewSymbol(name), \
- v8::FunctionTemplate::New(callback)->GetFunction())
-
-
-#endif // MOCK_RIL_NODE_UTIL_H_
diff --git a/mock-ril/src/cpp/protobuf_v8.cpp b/mock-ril/src/cpp/protobuf_v8.cpp
deleted file mode 100644
index 19f87c1..0000000
--- a/mock-ril/src/cpp/protobuf_v8.cpp
+++ /dev/null
@@ -1,553 +0,0 @@
-// Copyright 2010 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 "protobuf_v8.h"
-
-#include <map>
-#include <string>
-#include <iostream>
-#include <sstream>
-
-#include <google/protobuf/dynamic_message.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/descriptor.pb.h>
-
-#include "logging.h"
-#include "util.h"
-
-#include "node_buffer.h"
-#include "node_object_wrap.h"
-
-#include "node_util.h"
-
-//#define PROTOBUF_V8_DEBUG
-#ifdef PROTOBUF_V8_DEBUG
-
-#define DBG(...) ALOGD(__VA_ARGS__)
-
-#else
-
-#define DBG(...)
-
-#endif
-
-using google::protobuf::Descriptor;
-using google::protobuf::DescriptorPool;
-using google::protobuf::DynamicMessageFactory;
-using google::protobuf::FieldDescriptor;
-using google::protobuf::FileDescriptorSet;
-using google::protobuf::Message;
-using google::protobuf::Reflection;
-
-//using ObjectWrap;
-//using Buffer;
-
-using std::map;
-using std::string;
-
-using v8::Array;
-using v8::AccessorInfo;
-using v8::Arguments;
-using v8::Boolean;
-using v8::Context;
-using v8::External;
-using v8::Function;
-using v8::FunctionTemplate;
-using v8::Integer;
-using v8::Handle;
-using v8::HandleScope;
-using v8::InvocationCallback;
-using v8::Local;
-using v8::NamedPropertyGetter;
-using v8::Number;
-using v8::Object;
-using v8::ObjectTemplate;
-using v8::Persistent;
-using v8::Script;
-using v8::String;
-using v8::Value;
-using v8::V8;
-
-namespace protobuf_v8 {
-
- template <typename T>
- static T* UnwrapThis(const Arguments& args) {
- return ObjectWrap::Unwrap<T>(args.This());
- }
-
- template <typename T>
- static T* UnwrapThis(const AccessorInfo& args) {
- return ObjectWrap::Unwrap<T>(args.This());
- }
-
- Persistent<FunctionTemplate> SchemaTemplate;
- Persistent<FunctionTemplate> TypeTemplate;
- Persistent<FunctionTemplate> ParseTemplate;
- Persistent<FunctionTemplate> SerializeTemplate;
-
- class Schema : public ObjectWrap {
- public:
- Schema(Handle<Object> self, const DescriptorPool* pool)
- : pool_(pool) {
- DBG("Schema::Schema E:");
- factory_.SetDelegateToGeneratedFactory(true);
- self->SetInternalField(1, Array::New());
- Wrap(self);
- DBG("Schema::Schema X:");
- }
-
- virtual ~Schema() {
- DBG("~Schema::Schema E:");
- if (pool_ != DescriptorPool::generated_pool())
- delete pool_;
- DBG("~Schema::Schema X:");
- }
-
- class Type : public ObjectWrap {
- public:
- Schema* schema_;
- const Descriptor* descriptor_;
-
- Message* NewMessage() const {
- DBG("Type::NewMessage() EX:");
- return schema_->NewMessage(descriptor_);
- }
-
- Handle<Function> Constructor() const {
- DBG("Type::Constrocutor() EX:");
- return handle_->GetInternalField(2).As<Function>();
- }
-
- Local<Object> NewObject(Handle<Value> properties) const {
- DBG("Type::NewObjext(properties) EX:");
- return Constructor()->NewInstance(1, &properties);
- }
-
- Type(Schema* schema, const Descriptor* descriptor, Handle<Object> self)
- : schema_(schema), descriptor_(descriptor) {
- DBG("Type::Type(schema, descriptor, self) E:");
- // Generate functions for bulk conversion between a JS object
- // and an array in descriptor order:
- // from = function(arr) { this.f0 = arr[0]; this.f1 = arr[1]; ... }
- // to = function() { return [ this.f0, this.f1, ... ] }
- // This is faster than repeatedly calling Get/Set on a v8::Object.
- std::ostringstream from, to;
- from << "(function(arr) { if(arr) {";
- to << "(function() { return [ ";
-
- for (int i = 0; i < descriptor->field_count(); i++) {
- from <<
- "var x = arr[" << i << "]; "
- "if(x !== undefined) this['" <<
- descriptor->field(i)->camelcase_name() <<
- "'] = x; ";
-
- if (i > 0) to << ", ";
- to << "this['" << descriptor->field(i)->camelcase_name() << "']";
- DBG("field name=%s", descriptor->field(i)->name().c_str());
- }
-
- from << " }})";
- to << " ]; })";
-
- // managed type->schema link
- self->SetInternalField(1, schema_->handle_);
-
- Handle<Function> constructor =
- Script::Compile(String::New(from.str().c_str()))->Run().As<Function>();
- constructor->SetHiddenValue(String::New("type"), self);
-
- Handle<Function> bind =
- Script::Compile(String::New(
- "(function(self) {"
- " var f = this;"
- " return function(arg) {"
- " return f.call(self, arg);"
- " };"
- "})"))->Run().As<Function>();
- Handle<Value> arg = self;
- constructor->Set(String::New("parse"), bind->Call(ParseTemplate->GetFunction(), 1, &arg));
- constructor->Set(String::New("serialize"), bind->Call(SerializeTemplate->GetFunction(), 1, &arg));
- self->SetInternalField(2, constructor);
- self->SetInternalField(3, Script::Compile(String::New(to.str().c_str()))->Run());
-
- Wrap(self);
- DBG("Type::Type(schema, descriptor, self) X:");
- }
-
-#define GET(TYPE) \
- (index >= 0 ? \
- reflection->GetRepeated##TYPE(instance, field, index) : \
- reflection->Get##TYPE(instance, field))
-
- static Handle<Value> ToJs(const Message& instance,
- const Reflection* reflection,
- const FieldDescriptor* field,
- const Type* message_type,
- int index) {
- DBG("Type::ToJs(instance, refelction, field, message_type) E:");
- switch (field->cpp_type()) {
- case FieldDescriptor::CPPTYPE_MESSAGE:
- DBG("Type::ToJs CPPTYPE_MESSAGE");
- return message_type->ToJs(GET(Message));
- case FieldDescriptor::CPPTYPE_STRING: {
- DBG("Type::ToJs CPPTYPE_STRING");
- const string& value = GET(String);
- return String::New(value.data(), value.length());
- }
- case FieldDescriptor::CPPTYPE_INT32:
- DBG("Type::ToJs CPPTYPE_INT32");
- return Integer::New(GET(Int32));
- case FieldDescriptor::CPPTYPE_UINT32:
- DBG("Type::ToJs CPPTYPE_UINT32");
- return Integer::NewFromUnsigned(GET(UInt32));
- case FieldDescriptor::CPPTYPE_INT64:
- DBG("Type::ToJs CPPTYPE_INT64");
- return Number::New(GET(Int64));
- case FieldDescriptor::CPPTYPE_UINT64:
- DBG("Type::ToJs CPPTYPE_UINT64");
- return Number::New(GET(UInt64));
- case FieldDescriptor::CPPTYPE_FLOAT:
- DBG("Type::ToJs CPPTYPE_FLOAT");
- return Number::New(GET(Float));
- case FieldDescriptor::CPPTYPE_DOUBLE:
- DBG("Type::ToJs CPPTYPE_DOUBLE");
- return Number::New(GET(Double));
- case FieldDescriptor::CPPTYPE_BOOL:
- DBG("Type::ToJs CPPTYPE_BOOL");
- return Boolean::New(GET(Bool));
- case FieldDescriptor::CPPTYPE_ENUM:
- DBG("Type::ToJs CPPTYPE_ENUM");
- return String::New(GET(Enum)->name().c_str());
- }
-
- return Handle<Value>(); // NOTREACHED
- }
-#undef GET
-
- Handle<Object> ToJs(const Message& instance) const {
- DBG("Type::ToJs(Message) E:");
- const Reflection* reflection = instance.GetReflection();
- const Descriptor* descriptor = instance.GetDescriptor();
-
- Handle<Array> properties = Array::New(descriptor->field_count());
- for (int i = 0; i < descriptor->field_count(); i++) {
- HandleScope scope;
-
- const FieldDescriptor* field = descriptor->field(i);
- bool repeated = field->is_repeated();
- if (repeated && !reflection->FieldSize(instance, field)) {
- DBG("Ignore repeated field with no size in reflection data");
- continue;
- }
- if (!repeated && !reflection->HasField(instance, field)) {
- DBG("Ignore field with no field in relfection data");
- continue;
- }
-
- const Type* child_type =
- (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) ?
- schema_->GetType(field->message_type()) : NULL;
-
- Handle<Value> value;
- if (field->is_repeated()) {
- int size = reflection->FieldSize(instance, field);
- Handle<Array> array = Array::New(size);
- for (int j = 0; j < size; j++) {
- array->Set(j, ToJs(instance, reflection, field, child_type, j));
- }
- value = array;
- } else {
- value = ToJs(instance, reflection, field, child_type, -1);
- }
-
- DBG("Type::ToJs: set property[%d]=%s", i, ToCString(value));
- properties->Set(i, value);
- }
-
- DBG("Type::ToJs(Message) X:");
- return NewObject(properties);
- }
-
- static Handle<Value> Parse(const Arguments& args) {
- DBG("Type::Parse(args) E:");
- Type* type = UnwrapThis<Type>(args);
- Buffer* buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject());
-
- Message* message = type->NewMessage();
- message->ParseFromArray(buf->data(), buf->length());
- Handle<Object> result = type->ToJs(*message);
- delete message;
-
- DBG("Type::Parse(args) X:");
- return result;
- }
-
-#define SET(TYPE, EXPR) \
- if (repeated) reflection->Add##TYPE(instance, field, EXPR); \
- else reflection->Set##TYPE(instance, field, EXPR)
-
- static bool ToProto(Message* instance,
- const FieldDescriptor* field,
- Handle<Value> value,
- const Type* type,
- bool repeated) {
- DBG("Type::ToProto(instance, field, value, type, repeated) E:");
- bool ok = true;
- HandleScope scope;
-
- DBG("Type::ToProto field->name()=%s", field->name().c_str());
- const Reflection* reflection = instance->GetReflection();
- switch (field->cpp_type()) {
- case FieldDescriptor::CPPTYPE_MESSAGE:
- DBG("Type::ToProto CPPTYPE_MESSAGE");
- ok = type->ToProto(repeated ?
- reflection->AddMessage(instance, field) :
- reflection->MutableMessage(instance, field),
- value.As<Object>());
- break;
- case FieldDescriptor::CPPTYPE_STRING: {
- DBG("Type::ToProto CPPTYPE_STRING");
- String::AsciiValue ascii(value);
- SET(String, string(*ascii, ascii.length()));
- break;
- }
- case FieldDescriptor::CPPTYPE_INT32:
- DBG("Type::ToProto CPPTYPE_INT32");
- SET(Int32, value->NumberValue());
- break;
- case FieldDescriptor::CPPTYPE_UINT32:
- DBG("Type::ToProto CPPTYPE_UINT32");
- SET(UInt32, value->NumberValue());
- break;
- case FieldDescriptor::CPPTYPE_INT64:
- DBG("Type::ToProto CPPTYPE_INT64");
- SET(Int64, value->NumberValue());
- break;
- case FieldDescriptor::CPPTYPE_UINT64:
- DBG("Type::ToProto CPPTYPE_UINT64");
- SET(UInt64, value->NumberValue());
- break;
- case FieldDescriptor::CPPTYPE_FLOAT:
- DBG("Type::ToProto CPPTYPE_FLOAT");
- SET(Float, value->NumberValue());
- break;
- case FieldDescriptor::CPPTYPE_DOUBLE:
- DBG("Type::ToProto CPPTYPE_DOUBLE");
- SET(Double, value->NumberValue());
- break;
- case FieldDescriptor::CPPTYPE_BOOL:
- DBG("Type::ToProto CPPTYPE_BOOL");
- SET(Bool, value->BooleanValue());
- break;
- case FieldDescriptor::CPPTYPE_ENUM:
- DBG("Type::ToProto CPPTYPE_ENUM");
-
- // Don't use SET as vd can be NULL
- char error_buff[256];
- const google::protobuf::EnumValueDescriptor* vd;
- int i32_value = 0;
- const char *str_value = NULL;
- const google::protobuf::EnumDescriptor* ed = field->enum_type();
-
- if (value->IsNumber()) {
- i32_value = value->Int32Value();
- vd = ed->FindValueByNumber(i32_value);
- if (vd == NULL) {
- snprintf(error_buff, sizeof(error_buff),
- "Type::ToProto Bad enum value, %d is not a member of enum %s",
- i32_value, ed->full_name().c_str());
- }
- } else {
- str_value = ToCString(value);
- // TODO: Why can str_value be corrupted sometimes?
- ALOGD("str_value=%s", str_value);
- vd = ed->FindValueByName(str_value);
- if (vd == NULL) {
- snprintf(error_buff, sizeof(error_buff),
- "Type::ToProto Bad enum value, %s is not a member of enum %s",
- str_value, ed->full_name().c_str());
- }
- }
- if (vd != NULL) {
- if (repeated) {
- reflection->AddEnum(instance, field, vd);
- } else {
- reflection->SetEnum(instance, field, vd);
- }
- } else {
- v8::ThrowException(String::New(error_buff));
- ok = false;
- }
- break;
- }
- DBG("Type::ToProto(instance, field, value, type, repeated) X: ok=%d", ok);
- return ok;
- }
-#undef SET
-
- bool ToProto(Message* instance, Handle<Object> src) const {
- DBG("ToProto(Message *, Handle<Object>) E:");
-
- Handle<Function> to_array = handle_->GetInternalField(3).As<Function>();
- Handle<Array> properties = to_array->Call(src, 0, NULL).As<Array>();
- bool ok = true;
- for (int i = 0; ok && (i < descriptor_->field_count()); i++) {
- Handle<Value> value = properties->Get(i);
- if (value->IsUndefined()) continue;
-
- const FieldDescriptor* field = descriptor_->field(i);
- const Type* child_type =
- (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) ?
- schema_->GetType(field->message_type()) : NULL;
- if (field->is_repeated()) {
- if(!value->IsArray()) {
- ok = ToProto(instance, field, value, child_type, true);
- } else {
- Handle<Array> array = value.As<Array>();
- int length = array->Length();
- for (int j = 0; ok && (j < length); j++) {
- ok = ToProto(instance, field, array->Get(j), child_type, true);
- }
- }
- } else {
- ok = ToProto(instance, field, value, child_type, false);
- }
- }
- DBG("ToProto(Message *, Handle<Object>) X: ok=%d", ok);
- return ok;
- }
-
- static Handle<Value> Serialize(const Arguments& args) {
- Handle<Value> result;
- DBG("Serialize(Arguments&) E:");
- if (!args[0]->IsObject()) {
- DBG("Serialize(Arguments&) X: not an object");
- return v8::ThrowException(args[0]);
- }
-
- Type* type = UnwrapThis<Type>(args);
- Message* message = type->NewMessage();
- if (type->ToProto(message, args[0].As<Object>())) {
- int length = message->ByteSize();
- Buffer* buffer = Buffer::New(length);
- message->SerializeWithCachedSizesToArray((google::protobuf::uint8*)buffer->data());
- delete message;
-
- result = buffer->handle_;
- } else {
- result = v8::Undefined();
- }
- DBG("Serialize(Arguments&) X");
- return result;
- }
-
- static Handle<Value> ToString(const Arguments& args) {
- return String::New(UnwrapThis<Type>(args)->descriptor_->full_name().c_str());
- }
- };
-
- Message* NewMessage(const Descriptor* descriptor) {
- DBG("Schema::NewMessage(descriptor) EX:");
- return factory_.GetPrototype(descriptor)->New();
- }
-
- Type* GetType(const Descriptor* descriptor) {
- DBG("Schema::GetType(descriptor) E:");
- Type* result = types_[descriptor];
- if (result) return result;
-
- result = types_[descriptor] =
- new Type(this, descriptor, TypeTemplate->GetFunction()->NewInstance());
-
- // managed schema->[type] link
- Handle<Array> types = handle_->GetInternalField(1).As<Array>();
- types->Set(types->Length(), result->handle_);
- DBG("Schema::GetType(descriptor) X:");
- return result;
- }
-
- const DescriptorPool* pool_;
- map<const Descriptor*, Type*> types_;
- DynamicMessageFactory factory_;
-
- static Handle<Value> GetType(const Local<String> name,
- const AccessorInfo& args) {
- DBG("Schema::GetType(name, args) E:");
- Schema* schema = UnwrapThis<Schema>(args);
- const Descriptor* descriptor =
- schema->pool_->FindMessageTypeByName(*String::AsciiValue(name));
-
- DBG("Schema::GetType(name, args) X:");
- return descriptor ?
- schema->GetType(descriptor)->Constructor() :
- Handle<Function>();
- }
-
- static Handle<Value> NewSchema(const Arguments& args) {
- DBG("Schema::NewSchema E: args.Length()=%d", args.Length());
- if (!args.Length()) {
- return (new Schema(args.This(),
- DescriptorPool::generated_pool()))->handle_;
- }
-
- Buffer* buf = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject());
-
- FileDescriptorSet descriptors;
- if (!descriptors.ParseFromArray(buf->data(), buf->length())) {
- DBG("Schema::NewSchema X: bad descriptor");
- return v8::ThrowException(String::New("Malformed descriptor"));
- }
-
- DescriptorPool* pool = new DescriptorPool;
- for (int i = 0; i < descriptors.file_size(); i++) {
- pool->BuildFile(descriptors.file(i));
- }
-
- DBG("Schema::NewSchema X");
- return (new Schema(args.This(), pool))->handle_;
- }
- };
-
- void Init() {
- DBG("Init E:");
- HandleScope handle_scope;
-
- TypeTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New());
- TypeTemplate->SetClassName(String::New("Type"));
- // native self
- // owning schema (so GC can manage our lifecyle)
- // constructor
- // toArray
- TypeTemplate->InstanceTemplate()->SetInternalFieldCount(4);
-
- SchemaTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Schema::NewSchema));
- SchemaTemplate->SetClassName(String::New("Schema"));
- // native self
- // array of types (so GC can manage our lifecyle)
- SchemaTemplate->InstanceTemplate()->SetInternalFieldCount(2);
- SchemaTemplate->InstanceTemplate()->SetNamedPropertyHandler(Schema::GetType);
-
- ParseTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Schema::Type::Parse));
- SerializeTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Schema::Type::Serialize));
-
- DBG("Init X:");
- }
-
-} // namespace protobuf_v8
-
-extern "C" void SchemaObjectTemplateInit(Handle<ObjectTemplate> target) {
- DBG("SchemaObjectTemplateInit(target) EX:");
- target->Set(String::New("Schema"), protobuf_v8::SchemaTemplate);
-}
diff --git a/mock-ril/src/cpp/protobuf_v8.h b/mock-ril/src/cpp/protobuf_v8.h
deleted file mode 100644
index 4244e27..0000000
--- a/mock-ril/src/cpp/protobuf_v8.h
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright 2010 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 <v8.h>
-
-namespace protobuf_v8 {
- extern void Init();
-} // namespace protobuf_v8
-
-// Add Schema to the object template
-extern "C" void SchemaObjectTemplateInit(v8::Handle<v8::ObjectTemplate> target);
diff --git a/mock-ril/src/cpp/requests.cpp b/mock-ril/src/cpp/requests.cpp
deleted file mode 100644
index 72cbd00..0000000
--- a/mock-ril/src/cpp/requests.cpp
+++ /dev/null
@@ -1,525 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 <map>
-
-#include <v8.h>
-#include "ril.h"
-
-
-#include "hardware/ril/mock-ril/src/proto/ril.pb.h"
-
-#include "logging.h"
-#include "js_support.h"
-#include "mock_ril.h"
-#include "node_buffer.h"
-#include "node_object_wrap.h"
-#include "node_util.h"
-#include "protobuf_v8.h"
-#include "status.h"
-#include "util.h"
-#include "worker.h"
-
-#include "requests.h"
-
-//#define REQUESTS_DEBUG
-#ifdef REQUESTS_DEBUG
-
-#define DBG(...) ALOGD(__VA_ARGS__)
-
-#else
-
-#define DBG(...)
-
-#endif
-
-
-/**
- * Request has no data so create an empty Buffer
- */
-int ReqWithNoData(Buffer **pBuffer,
- const void *data, const size_t datalen, const RIL_Token t) {
- int status;
- static Buffer *emptyBuffer = Buffer::New(0L);
-
- DBG("ReqWithNoData E");
- *pBuffer = emptyBuffer;
- status = STATUS_OK;
-
- DBG("ReqWithNoData X status=%d", status);
- return status;
-}
-
-/**
- * request for RIL_REQUEST_ENTER_SIM_PIN // 2
- */
-int ReqEnterSimPin(Buffer **pBuffer,
- const void *data, const size_t datalen, const RIL_Token t) {
- int status;
- Buffer *buffer;
-
- DBG("ReqEnterSimPin E");
- if (datalen < sizeof(int)) {
- ALOGE("ReqEnterSimPin: data to small err size < sizeof int");
- status = STATUS_BAD_DATA;
- } else {
- ril_proto::ReqEnterSimPin *req = new ril_proto::ReqEnterSimPin();
- DBG("ReqEnterSimPin: pin = %s", ((const char **)data)[0]);
- req->set_pin((((char **)data)[0]));
- buffer = Buffer::New(req->ByteSize());
- req->SerializeToArray(buffer->data(), buffer->length());
- delete req;
- *pBuffer = buffer;
- status = STATUS_OK;
- }
- DBG("ReqEnterSimPin X status=%d", status);
- return status;
-}
-
-/**
- * request for RIL_REQUEST_DIAL // 10
- */
-int ReqDial(Buffer **pBuffer,
- const void *data, const size_t datalen, const RIL_Token t) {
- int status;
- Buffer *buffer;
-
- DBG("ReqDial E");
- DBG("data=%p datalen=%d t=%p", data, datalen, t);
-
- if (datalen < sizeof(int)) {
- ALOGE("ReqDial: data to small err size < sizeof int");
- status = STATUS_BAD_DATA;
- } else {
- ril_proto::ReqDial *req = new ril_proto::ReqDial();
-
- // cast the data to RIL_Dial
- RIL_Dial *rilDial = (RIL_Dial *)data;
- DBG("ReqDial: rilDial->address =%s, rilDial->clir=%d", rilDial->address, rilDial->clir);
-
- req->set_address(rilDial->address);
- req->set_clir(rilDial->clir);
- ril_proto::RilUusInfo *uusInfo = (ril_proto::RilUusInfo *)(&(req->uus_info()));
-
- if (rilDial->uusInfo != NULL) {
- DBG("ReqDial: print uusInfo:");
- DBG("rilDial->uusInfo->uusType = %d, "
- "rilDial->uusInfo->uusDcs =%d, "
- "rilDial->uusInfo->uusLength=%d, "
- "rilDial->uusInfo->uusData = %s",
- rilDial->uusInfo->uusType,
- rilDial->uusInfo->uusDcs,
- rilDial->uusInfo->uusLength,
- rilDial->uusInfo->uusData);
-
- uusInfo->set_uus_type((ril_proto::RilUusType)rilDial->uusInfo->uusType);
- uusInfo->set_uus_dcs((ril_proto::RilUusDcs)rilDial->uusInfo->uusDcs);
- uusInfo->set_uus_length(rilDial->uusInfo->uusLength);
- uusInfo->set_uus_data(rilDial->uusInfo->uusData);
- } else {
- DBG("uusInfo is NULL");
- }
-
- DBG("ReqDial: after set the request");
- DBG("req->ByetSize=%d", req->ByteSize());
- buffer = Buffer::New(req->ByteSize());
- DBG("buffer size=%d", buffer->length());
-
- req->SerializeToArray(buffer->data(), buffer->length());
- delete req;
- *pBuffer = buffer;
- status = STATUS_OK;
- DBG("ReqDial X, buffer->length()=%d", buffer->length());
- }
- DBG("ReqDial X status = %d", status);
- return status;
-}
-
-/**
- * request for RIL_REQUEST_HANGUP // 12
- */
-int ReqHangUp(Buffer **pBuffer,
- const void *data, const size_t datalen, const RIL_Token t) {
- int status;
- Buffer *buffer;
-
- DBG("ReqHangUp E");
- if (datalen < sizeof(int)) {
- ALOGE("ReqHangUp: data to small err size < sizeof int");
- status = STATUS_BAD_DATA;
- } else {
- ril_proto::ReqHangUp *req = new ril_proto::ReqHangUp();
- DBG("ReqHangUp: connection_index=%d", ((int *)data)[0]);
- req->set_connection_index(((int *)data)[0]);
- buffer = Buffer::New(req->ByteSize());
- req->SerializeToArray(buffer->data(), buffer->length());
- delete req;
- *pBuffer = buffer;
- status = STATUS_OK;
- }
- DBG("ReqHangUp X status=%d", status);
- return status;
-}
-
-/**
- * request for RIL_REQUEST_SEPARATE_CONNECTION // 52
- */
-int ReqSeparateConnection (Buffer **pBuffer,
- const void *data, const size_t datalen, const RIL_Token t) {
- int status;
- Buffer *buffer;
- v8::HandleScope handle_scope;
-
- DBG("ReqSeparateConnection E");
- if (datalen < sizeof(int)) {
- ALOGE("ReqSetMute: data to small err size < sizeof int");
- status = STATUS_BAD_DATA;
- } else {
- ril_proto::ReqSeparateConnection *req = new ril_proto::ReqSeparateConnection();
- DBG("ReqSeparateConnection: index=%d", ((int *)data)[0]);
- req->set_index(((int *)data)[0]);
- DBG("ReqSeparateConnection: req->ByetSize=%d", req->ByteSize());
- buffer = Buffer::New(req->ByteSize());
- req->SerializeToArray(buffer->data(), buffer->length());
- delete req;
- *pBuffer = buffer;
- status = STATUS_OK;
- }
- DBG("ReqSeparateConnection X status=%d", status);
- return status;
-}
-
-/**
- * request for RIL_REQUEST_SET_MUTE // 53
- */
-int ReqSetMute(Buffer **pBuffer,
- const void *data, const size_t datalen, const RIL_Token t) {
- int status;
- Buffer *buffer;
- v8::HandleScope handle_scope;
-
- DBG("ReqSetMute E");
- if (datalen < sizeof(int)) {
- ALOGE("ReqSetMute: data to small err size < sizeof int");
- status = STATUS_BAD_DATA;
- } else {
- ril_proto::ReqSetMute *req = new ril_proto::ReqSetMute();
- DBG("ReqSetMute: state=%d", ((int *)data)[0]);
- req->set_state(((int *)data)[0]);
- DBG("ReqSetMute: req->ByetSize=%d", req->ByteSize());
- buffer = Buffer::New(req->ByteSize());
- req->SerializeToArray(buffer->data(), buffer->length());
- delete req;
- *pBuffer = buffer;
- status = STATUS_OK;
- }
- DBG("ReqSetMute X status=%d", status);
- return status;
-}
-
-/**
- * request for RIL_REQUEST_SCREEN_STATE // 61
- */
-int ReqScreenState(Buffer **pBuffer,
- const void *data, const size_t datalen, const RIL_Token t) {
- int status;
- Buffer *buffer;
- v8::HandleScope handle_scope;
-
- DBG("ReqScreenState E data=%p datalen=%d t=%p",
- data, datalen, t);
- if (datalen < sizeof(int)) {
- ALOGE("ReqScreenState: data to small err size < sizeof int");
- status = STATUS_BAD_DATA;
- } else {
- ril_proto::ReqScreenState *req = new ril_proto::ReqScreenState();
- DBG("ReqScreenState: state=%d", ((int *)data)[0]);
- req->set_state(((int *)data)[0]);
- DBG("ReqScreenState: req->ByteSize()=%d", req->ByteSize());
- buffer = Buffer::New(req->ByteSize());
- DBG("ReqScreenState: serialize");
- req->SerializeToArray(buffer->data(), buffer->length());
- delete req;
- *pBuffer = buffer;
- status = STATUS_OK;
- }
- DBG("ReqScreenState X status=%d", status);
- return status;
-}
-
-/**
- * Map from indexed by cmd and used to convert Data to Protobuf.
- */
-typedef int (*ReqConversion)(Buffer** pBuffer, const void *data,
- const size_t datalen, const RIL_Token t);
-typedef std::map<int, ReqConversion> ReqConversionMap;
-ReqConversionMap rilReqConversionMap;
-
-int callOnRilRequest(v8::Handle<v8::Context> context, int cmd,
- const void *buffer, RIL_Token t) {
- DBG("callOnRilRequest E: cmd=%d", cmd);
-
- int status;
- v8::HandleScope handle_scope;
- v8::TryCatch try_catch;
-
- // Get the onRilRequest Function
- v8::Handle<v8::String> name = v8::String::New("onRilRequest");
- v8::Handle<v8::Value> onRilRequestFunctionValue = context->Global()->Get(name);
- v8::Handle<v8::Function> onRilRequestFunction =
- v8::Handle<v8::Function>::Cast(onRilRequestFunctionValue);
-
- // Create the cmd and token
- v8::Handle<v8::Value> v8RequestValue = v8::Number::New(cmd);
- v8::Handle<v8::Value> v8TokenValue = v8::Number::New(int64_t(t));
-
- // Invoke onRilRequest
- const int argc = 3;
- v8::Handle<v8::Value> argv[argc] = {
- v8RequestValue, v8TokenValue, ((Buffer *)buffer)->handle_ };
- v8::Handle<v8::Value> result =
- onRilRequestFunction->Call(context->Global(), argc, argv);
- if (try_catch.HasCaught()) {
- ALOGE("callOnRilRequest error");
- ReportException(&try_catch);
- status = STATUS_ERR;
- } else {
- v8::String::Utf8Value result_string(result);
- DBG("callOnRilRequest result=%s", ToCString(result_string));
- status = STATUS_OK;
- }
-
- DBG("callOnRilRequest X: status=%d", status);
- return status;
-}
-
-RilRequestWorkerQueue::RilRequestWorkerQueue(v8::Handle<v8::Context> context) {
- DBG("RilRequestWorkerQueue E:");
-
- context_ = context;
- pthread_mutex_init(&free_list_mutex_, NULL);
-
- DBG("RilRequestWorkerQueue X:");
-}
-
-RilRequestWorkerQueue::~RilRequestWorkerQueue() {
- DBG("~RilRequestWorkerQueue E:");
- Request *req;
- pthread_mutex_lock(&free_list_mutex_);
- while(free_list_.size() != 0) {
- req = free_list_.front();
- delete req;
- free_list_.pop();
- }
- pthread_mutex_unlock(&free_list_mutex_);
- pthread_mutex_destroy(&free_list_mutex_);
- DBG("~RilRequestWorkerQueue X:");
-}
-
-/**
- * Add a request to the processing queue.
- * Data is serialized to a protobuf before adding to the queue.
- */
-void RilRequestWorkerQueue::AddRequest (const int request,
- const void *data, const size_t datalen, const RIL_Token token) {
- DBG("RilRequestWorkerQueue:AddRequest: %d E", request);
-
- v8::Locker locker;
- v8::HandleScope handle_scope;
- v8::Context::Scope context_scope(context_);
-
- int status;
-
- // Convert the data to a protobuf before inserting it into the request queue (serialize data)
- Buffer *buffer = NULL;
- ReqConversionMap::iterator itr;
- itr = rilReqConversionMap.find(request);
- if (itr != rilReqConversionMap.end()) {
- status = itr->second(&buffer, data, datalen, token);
- } else {
- ALOGE("RilRequestWorkerQueue:AddRequest: X unknown request %d", request);
- status = STATUS_UNSUPPORTED_REQUEST;
- }
-
- if (status == STATUS_OK) {
- // Add serialized request to the queue
- Request *req;
- pthread_mutex_lock(&free_list_mutex_);
- DBG("RilRequestWorkerQueue:AddRequest: return ok, buffer = %p, buffer->length()=%d",
- buffer, buffer->length());
- if (free_list_.size() == 0) {
- req = new Request(request, buffer, token);
- pthread_mutex_unlock(&free_list_mutex_);
- } else {
- req = free_list_.front();
- free_list_.pop();
- pthread_mutex_unlock(&free_list_mutex_);
- req->Set(request, buffer, token);
- }
- // add the request
- Add(req);
- } else {
- DBG("RilRequestWorkerQueue:AddRequest: return from the serialization, status is not OK");
- // An error report complete now
- RIL_Errno rilErrCode = (status == STATUS_UNSUPPORTED_REQUEST) ?
- RIL_E_REQUEST_NOT_SUPPORTED : RIL_E_GENERIC_FAILURE;
- s_rilenv->OnRequestComplete(token, rilErrCode, NULL, 0);
- }
-
- DBG("RilRequestWorkerQueue::AddRequest: X"
- " request=%d data=%p datalen=%d token=%p",
- request, data, datalen, token);
-}
-
-void RilRequestWorkerQueue::Process(void *p) {
-
- Request *req = (Request *)p;
- DBG("RilRequestWorkerQueue::Process: E"
- " request=%d buffer=%p, bufferlen=%d t=%p",
- req->request_, req->buffer_, req->buffer_->length(), req->token_);
-
- v8::Locker locker;
- v8::HandleScope handle_scope;
- v8::Context::Scope context_scope(context_);
- callOnRilRequest(context_, req->request_,
- req->buffer_, req->token_);
-
- pthread_mutex_lock(&free_list_mutex_);
- free_list_.push(req);
- pthread_mutex_unlock(&free_list_mutex_);
-}
-
-int requestsInit(v8::Handle<v8::Context> context, RilRequestWorkerQueue **rwq) {
- ALOGD("requestsInit E");
-
- rilReqConversionMap[RIL_REQUEST_GET_SIM_STATUS] = ReqWithNoData; // 1
- rilReqConversionMap[RIL_REQUEST_ENTER_SIM_PIN] = ReqEnterSimPin; // 2
- rilReqConversionMap[RIL_REQUEST_GET_CURRENT_CALLS] = ReqWithNoData; // 9
- rilReqConversionMap[RIL_REQUEST_DIAL] = ReqDial; // 10
- rilReqConversionMap[RIL_REQUEST_GET_IMSI] = ReqWithNoData; // 11
- rilReqConversionMap[RIL_REQUEST_HANGUP] = ReqHangUp; // 12
- rilReqConversionMap[RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND] = ReqWithNoData; // 13
- rilReqConversionMap[RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND] = ReqWithNoData; // 14
- rilReqConversionMap[RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE] = ReqWithNoData; // 15
- rilReqConversionMap[RIL_REQUEST_CONFERENCE] = ReqWithNoData; // 16
- rilReqConversionMap[RIL_REQUEST_LAST_CALL_FAIL_CAUSE] = ReqWithNoData; // 18
- rilReqConversionMap[RIL_REQUEST_SIGNAL_STRENGTH] = ReqWithNoData; // 19
- rilReqConversionMap[RIL_REQUEST_VOICE_REGISTRATION_STATE] = ReqWithNoData; // 20
- rilReqConversionMap[RIL_REQUEST_DATA_REGISTRATION_STATE] = ReqWithNoData; // 21
- rilReqConversionMap[RIL_REQUEST_OPERATOR] = ReqWithNoData; // 22
- rilReqConversionMap[RIL_REQUEST_GET_IMEI] = ReqWithNoData; // 38
- rilReqConversionMap[RIL_REQUEST_GET_IMEISV] = ReqWithNoData; // 39
- rilReqConversionMap[RIL_REQUEST_ANSWER] = ReqWithNoData; // 40
- rilReqConversionMap[RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE] = ReqWithNoData; // 45
- rilReqConversionMap[RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC] = ReqWithNoData; // 46
- rilReqConversionMap[RIL_REQUEST_BASEBAND_VERSION] = ReqWithNoData; // 51
- rilReqConversionMap[RIL_REQUEST_SEPARATE_CONNECTION] = ReqSeparateConnection; // 52
- rilReqConversionMap[RIL_REQUEST_SET_MUTE] = ReqSetMute; // 53
- rilReqConversionMap[RIL_REQUEST_SCREEN_STATE] = ReqScreenState; // 61
-
- *rwq = new RilRequestWorkerQueue(context);
- int status = (*rwq)->Run();
-
- ALOGD("requestsInit X: status=%d", status);
- return status;
-}
-
-/**
- * Subroutine to test a single RIL request
- */
-void testRilRequest(v8::Handle<v8::Context> context, int request, const void *data,
- const size_t datalen, const RIL_Token t) {
- Buffer *buffer = NULL;
- ReqConversionMap::iterator itr;
- int status;
-
- ALOGD("testRilRequest: request=%d", request);
-
- itr = rilReqConversionMap.find(request);
- if (itr != rilReqConversionMap.end()) {
- status = itr->second(&buffer, data, sizeof(data), (void *)0x12345677);
- } else {
- ALOGE("testRequests X unknown request %d", request);
- status = STATUS_UNSUPPORTED_REQUEST;
- }
- if (status == STATUS_OK) {
- callOnRilRequest(context, request, buffer, (void *)0x12345677);
- } else {
- ALOGE("testRilRequest X, serialize error");
- }
-}
-
-void testRequests(v8::Handle<v8::Context> context) {
- ALOGD("testRequests E: ********");
-
- v8::TryCatch try_catch;
-
- char *buffer;
- const char *fileName= "/sdcard/data/mock_ril.js";
- int status = ReadFile(fileName, &buffer);
- if (status == 0) {
- runJs(context, &try_catch, fileName, buffer);
- Buffer *buffer = NULL;
- ReqConversionMap::iterator itr;
- int status;
- int request;
-
- if (!try_catch.HasCaught()) {
- {
- const int data[1] = { 1 };
- testRilRequest(context, RIL_REQUEST_SIGNAL_STRENGTH, data, sizeof(data),
- (void *)0x12345677);
- }
- {
- const char *data[1] = { "winks-pin" };
- testRilRequest(context, RIL_REQUEST_ENTER_SIM_PIN, data, sizeof(data),
- (void *)0x12345677);
- }
- {
- const int data[1] = { 1 };
- testRilRequest(context, RIL_REQUEST_HANGUP, data, sizeof(data),
- (void *)0x12345677);
- }
- {
- const int data[1] = { 1 };
- testRilRequest(context, RIL_REQUEST_SCREEN_STATE, data, sizeof(data),
- (void *)0x12345677);
- }
- {
- const int data[1] = { 1 };
- testRilRequest(context, RIL_REQUEST_GET_SIM_STATUS, data, sizeof(data),
- (void *)0x12345677);
- }
- {
- RilRequestWorkerQueue *rwq = new RilRequestWorkerQueue(context);
- if (rwq->Run() == STATUS_OK) {
- const int data[1] = { 1 };
- rwq->AddRequest(RIL_REQUEST_SCREEN_STATE,
- data, sizeof(data), (void *)0x1234567A);
- rwq->AddRequest(RIL_REQUEST_SIGNAL_STRENGTH,
- data, sizeof(data), (void *)0x1234567A);
- // Sleep to let it be processed
- v8::Unlocker unlocker;
- sleep(3);
- v8::Locker locker;
- }
- delete rwq;
- }
- }
- }
-
- ALOGD("testRequests X: ********\n");
-}
diff --git a/mock-ril/src/cpp/requests.h b/mock-ril/src/cpp/requests.h
deleted file mode 100644
index 6c1b077..0000000
--- a/mock-ril/src/cpp/requests.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 MOCK_RIL_REQUESTS_H_
-#define MOCK_RIL_REQUESTS_H_
-
-#include <queue>
-#include <pthread.h>
-
-#include <v8.h>
-#include "worker.h"
-#include "node_object_wrap.h"
-
-/**
- * A request
- */
-struct Request {
- int request_;
- Buffer *buffer_;
- RIL_Token token_;
-
- Request(const int request, const Buffer *buffer, const RIL_Token token) :
- request_(0),
- buffer_(NULL),
- token_(0) {
- Set(request, buffer, token);
- }
-
- ~Request() {
- delete [] buffer_;
- }
-
- void Set(const int request,
- const Buffer *buffer, const RIL_Token token) {
- request_ = request;
- token_ = token;
- buffer_ = (Buffer *)buffer;
- }
-};
-
-/**
- * Ril request worker queue.
- *
- * Pass requests to mock-ril.js for processing
- */
-class RilRequestWorkerQueue : public WorkerQueue {
- private:
- v8::Handle<v8::Context> context_;
- // TODO: Need a thread-safe queue
- std::queue<Request *> free_list_;
- pthread_mutex_t free_list_mutex_;
-
- public:
- /**
- * Constructor
- */
- RilRequestWorkerQueue(v8::Handle<v8::Context> context);
-
- /**
- * Destructor
- */
- virtual ~RilRequestWorkerQueue();
-
- /**
- * Add a request to the Queue
- */
- void AddRequest(const int request,
- const void *data, const size_t datalen, const RIL_Token token);
-
- /**
- * Processes a request sending it to mock-ril.js
- */
- virtual void Process(void *p);
-};
-
-/**
- * Initialize module
- *
- * @return 0 if no errors
- */
-int requestsInit(v8::Handle<v8::Context> context, RilRequestWorkerQueue **rwq);
-
-/**
- * Run tests
- */
-void testRequests(v8::Handle<v8::Context> context);
-
-#endif // MOCK_RIL_REQUESTS_H_
diff --git a/mock-ril/src/cpp/responses.cpp b/mock-ril/src/cpp/responses.cpp
deleted file mode 100644
index 89ca488..0000000
--- a/mock-ril/src/cpp/responses.cpp
+++ /dev/null
@@ -1,536 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 <map>
-
-#include <v8.h>
-#include "ril.h"
-
-#include "hardware/ril/mock-ril/src/proto/ril.pb.h"
-
-#include "logging.h"
-#include "mock_ril.h"
-#include "node_buffer.h"
-#include "node_object_wrap.h"
-#include "protobuf_v8.h"
-#include "status.h"
-#include "util.h"
-#include "worker.h"
-
-#include "responses.h"
-
-//#define RESPONSES_DEBUG
-#ifdef RESPONSES_DEBUG
-
-#define DBG(...) ALOGD(__VA_ARGS__)
-
-#else
-
-#define DBG(...)
-
-#endif
-
-
-/**
- * The Buffer is assumed to be empty so nothing to convert
- * @return STATUS_OK and *data = NULL *datalen = 0;
- */
-RIL_Errno RspWithNoData(
- int cmd, RIL_Token token, RIL_Errno rilErrno, Buffer *buffer) {
- DBG("RspWithNoData E");
-
- // Complete the request
- s_rilenv->OnRequestComplete(token, rilErrno, NULL, 0);
-
- DBG("RspWithNoData X");
- return rilErrno;
-}
-
-/**
- * Handle response for an array of strings
- *
- * If a string value is "*magic-null*" then that value
- * will be returned as null.
- */
-RIL_Errno RspStrings(
- int cmd, RIL_Token token, RIL_Errno rilErrno, Buffer *buffer) {
- DBG("RspStrings E");
-
- ril_proto::RspStrings *rsp = new ril_proto::RspStrings();
- rsp->ParseFromArray(buffer->data(), buffer->length());
- int result_len = rsp->strings_size() * sizeof(const char *);
- const char **result = (const char **)alloca(result_len);
- for (int i = 0; i < rsp->strings_size(); i++) {
- result[i] = rsp->strings(i).c_str();
- DBG("result[%d]='%s'", i, result[i]);
- if (strcmp("*magic-null*", result[i]) == 0) {
- result[i] = NULL;
- }
- }
-
- // Complete the request
- s_rilenv->OnRequestComplete(token, rilErrno, result, result_len);
-
- DBG("RspStrings X rilErrno=%d", rilErrno);
- return rilErrno;
-}
-
-/**
- * Handle response for a string
- */
-RIL_Errno RspString(
- int cmd, RIL_Token token, RIL_Errno rilErrno, Buffer *buffer) {
- DBG("RspString E");
-
- ril_proto::RspStrings *rsp = new ril_proto::RspStrings();
- rsp->ParseFromArray(buffer->data(), buffer->length());
- const char *result = rsp->strings(0).c_str();
-
- // Complete the request
- s_rilenv->OnRequestComplete(token, rilErrno, (void *)result, strlen(result));
-
- DBG("RspString X rilErrno=%d", rilErrno);
- return rilErrno;
-}
-
-/**
- * Handle response for an array of integers
- */
-RIL_Errno RspIntegers(
- int cmd, RIL_Token token, RIL_Errno rilErrno, Buffer *buffer) {
- DBG("RspIntegers E");
-
- ril_proto::RspIntegers *rsp = new ril_proto::RspIntegers();
- rsp->ParseFromArray(buffer->data(), buffer->length());
- int result_len = rsp->integers_size() * sizeof(const int32_t);
- int32_t *result = (int32_t *)alloca(result_len);
- for (int i = 0; i < rsp->integers_size(); i++) {
- result[i] = rsp->integers(i);
- DBG("result[%d]=%d", i, result[i]);
- }
-
- // Complete the request
- s_rilenv->OnRequestComplete(token, rilErrno, result, result_len);
-
- DBG("RspIntegers X rilErrno=%d", rilErrno);
- return rilErrno;
-}
-
-/**
- * Handle RIL_REQUEST_GET_SIM_STATUS response
- */
-RIL_Errno RspGetSimStatus(
- int cmd, RIL_Token token, RIL_Errno rilErrno, Buffer *buffer) { // 1
- DBG("RspGetSimStatus E");
-
- ril_proto::RspGetSimStatus *rsp = new ril_proto::RspGetSimStatus();
- rsp->ParseFromArray(buffer->data(), buffer->length());
- const ril_proto::RilCardStatus& r = rsp->card_status();
- RIL_CardStatus_v6 cardStatus;
- cardStatus.card_state = RIL_CardState(r.card_state());
- cardStatus.universal_pin_state = RIL_PinState(r.universal_pin_state());
- cardStatus.gsm_umts_subscription_app_index = r.gsm_umts_subscription_app_index();
- cardStatus.ims_subscription_app_index = r.ims_subscription_app_index();
- cardStatus.num_applications = r.num_applications();
- for (int i = 0; i < cardStatus.num_applications; i++) {
- cardStatus.applications[i].app_type = RIL_AppType(r.applications(i).app_type());
- cardStatus.applications[i].app_state = RIL_AppState(r.applications(i).app_state());
- cardStatus.applications[i].perso_substate =
- RIL_PersoSubstate(r.applications(i).perso_substate());
- cardStatus.applications[i].aid_ptr = const_cast<char *>(r.applications(i).aid().c_str());
- cardStatus.applications[i].app_label_ptr =
- const_cast<char *>(r.applications(i).app_label().c_str());
- cardStatus.applications[i].pin1_replaced = r.applications(i).pin1_replaced();
- cardStatus.applications[i].pin1 = RIL_PinState(r.applications(i).pin1());
- cardStatus.applications[i].pin2 = RIL_PinState(r.applications(i).pin2());
- }
-
- // Complete the request
- s_rilenv->OnRequestComplete(token, rilErrno,
- &cardStatus, sizeof(cardStatus));
-
- DBG("RspGetSimStatus X rilErrno=%d", rilErrno);
- return rilErrno;
-}
-
-/**
- * Handle RIL_REQUEST_ENTER_SIM_PIN_DATA response
- */
-RIL_Errno RspEnterSimPinData(
- int cmd, RIL_Token token, RIL_Errno rilErrno, Buffer *buffer) { // 2
- DBG("RspEnterSimPinData E");
-
- ril_proto::RspEnterSimPin *rsp = new ril_proto::RspEnterSimPin();
- rsp->ParseFromArray(buffer->data(), buffer->length());
- DBG("retries_remaining=%d", rsp->retries_remaining());
- int retries_remaining = rsp->retries_remaining();
-
- // Complete the request
- s_rilenv->OnRequestComplete(token, rilErrno,
- &retries_remaining, sizeof(retries_remaining));
-
- DBG("RspEnterSimPinData X rilErrno=%d", rilErrno);
- return rilErrno;
-}
-
-/**
- * Handle RIL_REQUEST_GET_CURRENT_CALLS response // 9
- */
-RIL_Errno RspGetCurrentCalls (
- int cmd, RIL_Token token, RIL_Errno rilErrno, Buffer *buffer) { // 9
- DBG("RspGetCurrentCalls E");
-
- ril_proto::RspGetCurrentCalls *rsp = new ril_proto::RspGetCurrentCalls();
- rsp->ParseFromArray(buffer->data(), buffer->length());
- int result_len = rsp->calls_size() * sizeof(const RIL_Call *);
- DBG("RspGetCurrentCalls rilErrno=%d result_len=%d", rilErrno, result_len);
- RIL_Call **result = (RIL_Call **)alloca(result_len);
- for (int i = 0; i < rsp->calls_size(); i++) {
- const ril_proto::RilCall& srcCall = rsp->calls(i);
- RIL_Call *dstCall = (RIL_Call *)alloca(sizeof(RIL_Call));
-
- result[i] = dstCall;
- dstCall->state = (RIL_CallState)srcCall.state();
- dstCall->index = srcCall.index();
- dstCall->toa = srcCall.toa();
- dstCall->isMpty = (char)srcCall.is_mpty();
- dstCall->isMT = (char)srcCall.is_mt();
- dstCall->als = srcCall.als();
- dstCall->isVoice = (char)srcCall.is_voice();
- dstCall->isVoicePrivacy = (char)srcCall.is_voice_privacy();
- dstCall->number = (char *)srcCall.number().c_str();
- dstCall->numberPresentation = srcCall.number_presentation();
- dstCall->name = (char *)srcCall.name().c_str();
- dstCall->namePresentation = srcCall.name_presentation();
- if (srcCall.has_uus_info()) {
- dstCall->uusInfo =
- (RIL_UUS_Info *)alloca(sizeof(RIL_UUS_Info));
- dstCall->uusInfo->uusType =
- (RIL_UUS_Type)srcCall.uus_info().uus_type();
- dstCall->uusInfo->uusDcs =
- (RIL_UUS_DCS)srcCall.uus_info().uus_dcs();
- dstCall->uusInfo->uusLength =
- srcCall.uus_info().uus_length();
- dstCall->uusInfo->uusData =
- (char *)srcCall.uus_info().uus_data().c_str();
- } else {
- dstCall->uusInfo = NULL;
- }
- }
-
- // Complete the request
- s_rilenv->OnRequestComplete(token, rilErrno, result, result_len);
-
- DBG("RspGetCurrentCalls X rilErrno=%d", rilErrno);
- return rilErrno;
-}
-
-
-void unmarshallRilSignalStrength(Buffer *buffer, RIL_SignalStrength_v6 *pSignalStrength) {
- // Retrieve response from response message
- ril_proto::RspSignalStrength *rsp = new ril_proto::RspSignalStrength();
- rsp->ParseFromArray(buffer->data(), buffer->length());
- const ril_proto::RILGWSignalStrength& gwST = rsp->gw_signalstrength();
- const ril_proto::RILCDMASignalStrength& cdmaST = rsp->cdma_signalstrength();
- const ril_proto::RILEVDOSignalStrength& evdoST = rsp->evdo_signalstrength();
- const ril_proto::RILLTESignalStrength& lteST = rsp->lte_signalstrength();
-
- // Copy the response message from response to format defined in ril.h
- RIL_SignalStrength_v6 curSignalStrength;
-
- curSignalStrength.GW_SignalStrength.signalStrength = gwST.signal_strength();
- curSignalStrength.GW_SignalStrength.bitErrorRate = gwST.bit_error_rate();
- curSignalStrength.CDMA_SignalStrength.dbm = cdmaST.dbm();
- curSignalStrength.CDMA_SignalStrength.ecio = cdmaST.ecio();
- curSignalStrength.EVDO_SignalStrength.dbm = evdoST.dbm();
- curSignalStrength.EVDO_SignalStrength.ecio = evdoST.ecio();
- curSignalStrength.EVDO_SignalStrength.signalNoiseRatio = evdoST.signal_noise_ratio();
- curSignalStrength.LTE_SignalStrength.signalStrength = lteST.signal_strength();
- curSignalStrength.LTE_SignalStrength.rsrp = lteST.rsrp();
- curSignalStrength.LTE_SignalStrength.rsrq = lteST.rsrq();
- curSignalStrength.LTE_SignalStrength.rssnr = lteST.rssnr();
- curSignalStrength.LTE_SignalStrength.cqi = lteST.cqi();
-
- DBG("print response signal strength: ");
- DBG("gw signalstrength = %d", curSignalStrength.GW_SignalStrength.signalStrength);
- DBG("gw_bitErrorRate = %d", curSignalStrength.GW_SignalStrength.bitErrorRate);
- DBG("cdma_dbm = %d", curSignalStrength.CDMA_SignalStrength.dbm);
- DBG("cdma_ecio = %d", curSignalStrength.CDMA_SignalStrength.ecio);
- DBG("evdo_dbm = %d", curSignalStrength.EVDO_SignalStrength.dbm);
- DBG("evdo_ecio = %d", curSignalStrength.EVDO_SignalStrength.ecio);
- DBG("evdo_signalNoiseRatio = %d", curSignalStrength.EVDO_SignalStrength.signalNoiseRatio);
- DBG("lte_signalStrength = %d", curSignalStrength.LTE_SignalStrength.signalStrength);
- DBG("lte_rsrp = %d", curSignalStrength.LTE_SignalStrength.rsrp);
- DBG("lte_rsrq = %d", curSignalStrength.LTE_SignalStrength.rsrq);
- DBG("lte_rssnr = %d", curSignalStrength.LTE_SignalStrength.rssnr);
- DBG("lte_cqi = %d", curSignalStrength.LTE_SignalStrength.cqi);
-}
-
-/**
- * Handle RIL_REQUEST_SIGNAL_STRENGTH response
- */
-RIL_Errno RspSignalStrength(
- int cmd, RIL_Token token, RIL_Errno rilErrno, Buffer *buffer) { // 19
- DBG("RspSignalStrength E");
-
- DBG("cmd = %d, token=%p, rilErrno=%d", cmd, token, rilErrno);
-
- // Retrieve response from response message
- ril_proto::RspSignalStrength *rsp = new ril_proto::RspSignalStrength();
- rsp->ParseFromArray(buffer->data(), buffer->length());
- const ril_proto::RILGWSignalStrength& gwST = rsp->gw_signalstrength();
- const ril_proto::RILCDMASignalStrength& cdmaST = rsp->cdma_signalstrength();
- const ril_proto::RILEVDOSignalStrength& evdoST = rsp->evdo_signalstrength();
- const ril_proto::RILLTESignalStrength& lteST = rsp->lte_signalstrength();
-
- // Copy the response message from response to format defined in ril.h
- RIL_SignalStrength_v6 curSignalStrength;
- unmarshallRilSignalStrength(buffer, &curSignalStrength);
-
- // Complete the request
- s_rilenv->OnRequestComplete(token, rilErrno, &curSignalStrength, sizeof(curSignalStrength));
-
- DBG("RspSignalStrength X rilErrno=%d", rilErrno);
- return rilErrno;
-}
-
-/**
- * Handle RIL_REQUEST_OPERATOR response
- */
-RIL_Errno RspOperator(
- int cmd, RIL_Token token, RIL_Errno rilErrno, Buffer *buffer) { // 22
- int status;
-
- DBG("RspOperator E");
-
- ril_proto::RspOperator *rsp = new ril_proto::RspOperator();
- rsp->ParseFromArray(buffer->data(), buffer->length());
- const char *result[3] = { NULL, NULL, NULL };
- if (rsp->has_long_alpha_ons()) {
- DBG("long_alpha_ons=%s", rsp->long_alpha_ons().c_str());
- result[0] = rsp->long_alpha_ons().c_str();
- }
- if (rsp->has_short_alpha_ons()) {
- DBG("short_alpha_ons=%s", rsp->short_alpha_ons().c_str());
- result[1] = rsp->short_alpha_ons().c_str();
- }
- if (rsp->has_mcc_mnc()) {
- DBG("mcc_mnc=%s", rsp->mcc_mnc().c_str());
- result[2] = rsp->mcc_mnc().c_str();
- }
-
- // Complete the request
- s_rilenv->OnRequestComplete(token, rilErrno, result, sizeof(result));
-
- DBG("RspOperator X rilErrno=%d", rilErrno);
- return rilErrno;
-}
-
-// ----------------- Handle unsolicited response ----------------------------------------
- /**
- * Handle RIL_UNSOL_SIGNAL_STRENGTH response
- */
-void UnsolRspSignalStrength(int cmd, Buffer* buffer) {
-
- DBG("UnsolRspSignalStrength E");
- ALOGE("unsolicited response command: %d", cmd);
- // Retrieve response from response message
- ril_proto::RspSignalStrength *rsp = new ril_proto::RspSignalStrength();
- rsp->ParseFromArray(buffer->data(), buffer->length());
- const ril_proto::RILGWSignalStrength& gwST = rsp->gw_signalstrength();
- const ril_proto::RILCDMASignalStrength& cdmaST = rsp->cdma_signalstrength();
- const ril_proto::RILEVDOSignalStrength& evdoST = rsp->evdo_signalstrength();
-
- // Copy the response message from response to format defined in ril.h
- RIL_SignalStrength_v6 curSignalStrength;
- unmarshallRilSignalStrength(buffer, &curSignalStrength);
-
- s_rilenv->OnUnsolicitedResponse(cmd, &curSignalStrength, sizeof(curSignalStrength));
- DBG("UnsolRspSignalStrength X");
-}
-
-/**
- * Maps for converting request complete and unsoliciated response
- * protobufs to ril data arrays.
- */
-typedef RIL_Errno (*RspConversion)(
- int cmd, RIL_Token token, RIL_Errno rilErrno, Buffer* buffer);
-typedef std::map<int, RspConversion> RspConversionMap;
-RspConversionMap rilRspConversionMap;
-
-typedef void (*UnsolRspConversion)(int cmd, Buffer* buffer);
-typedef std::map<int, UnsolRspConversion> UnsolRspConversionMap;
-UnsolRspConversionMap unsolRilRspConversionMap;
-
-/**
- * Send a ril request complete response.
- */
-v8::Handle<v8::Value> SendRilRequestComplete(const v8::Arguments& args) {
- DBG("SendRilRequestComplete E");
- v8::HandleScope handle_scope;
- v8::Handle<v8::Value> retValue;
-
- int cmd;
- RIL_Errno rilErrno;
- RIL_Token token;
- Buffer* buffer;
-
- /**
- * Get the arguments. There should be at least 3, cmd,
- * ril error code and token. Optionally a Buffer containing
- * the protobuf representation of the data to return.
- */
- if (args.Length() < REQUEST_COMPLETE_REQUIRED_CMDS) {
- // Expecting a cmd, ERROR and token
- ALOGE("SendRilRequestComplete X %d parameters"
- " expecting at least %d: rilErrno, cmd, and token",
- args.Length(), REQUEST_COMPLETE_REQUIRED_CMDS);
- return v8::Undefined();
- }
- v8::Handle<v8::Value> v8RilErrCode(
- args[REQUEST_COMPLETE_RIL_ERR_CODE_INDEX]->ToObject());
- rilErrno = RIL_Errno(v8RilErrCode->NumberValue());
-
- v8::Handle<v8::Value> v8Cmd(
- args[REQUEST_COMPLETE_CMD_INDEX]->ToObject());
- cmd = int(v8Cmd->NumberValue());
-
- v8::Handle<v8::Value> v8Token(
- args[REQUEST_COMPLETE_TOKEN_INDEX]->ToObject());
- token = RIL_Token(int64_t(v8Token->NumberValue()));
-
- if (args.Length() >= (REQUEST_COMPLETE_DATA_INDEX+1)) {
- buffer = ObjectWrap::Unwrap<Buffer>(
- args[REQUEST_COMPLETE_DATA_INDEX]->ToObject());
- } else {
- buffer = NULL;
- }
-
- DBG("SendRilRequestComplete: rilErrno=%d, cmd=%d, token=%p", rilErrno, cmd, token);
- RspConversionMap::iterator itr;
- itr = rilRspConversionMap.find(cmd);
- if (itr != rilRspConversionMap.end()) {
- itr->second(cmd, token, rilErrno, buffer);
- } else {
- if ((buffer == NULL) || (buffer->length() <= 0)) {
- // Nothing to convert
- rilErrno = RIL_E_SUCCESS;
- } else {
- // There was a buffer but we don't support the resonse yet.
- ALOGE("SendRilRequestComplete: No conversion routine for cmd %d,"
- " return RIL_E_REQUEST_NOT_SUPPORTED", cmd);
- rilErrno = RIL_E_REQUEST_NOT_SUPPORTED;
- }
- // Complete the request
- s_rilenv->OnRequestComplete(token, rilErrno, NULL, 0);
- }
-
- DBG("SendRilRequestComplete X rillErrno=%d", rilErrno);
- return v8::Undefined();
-}
-
-/**
- * Send an unsolicited response.
- */
-v8::Handle<v8::Value> SendRilUnsolicitedResponse(const v8::Arguments& args) {
- DBG("SendRilUnsolicitedResponse E");
- v8::HandleScope handle_scope;
- v8::Handle<v8::Value> retValue;
-
- int status;
- void *data;
- size_t datalen;
-
- int cmd;
- Buffer* buffer;
-
- /**
- * Get the cmd number and data arguments
- */
- if (args.Length() < UNSOL_RESPONSE_REQUIRED_CMDS) {
- // Expecting a cmd
- ALOGE("SendRilUnsolicitedResponse X %d parameters"
- " expecting at least a cmd",
- args.Length());
- return v8::Undefined();
- }
- v8::Handle<v8::Value> v8RilErrCode(args[UNSOL_RESPONSE_CMD_INDEX]->ToObject());
- cmd = int(v8RilErrCode->NumberValue());
-
- // data is optional
- if (args.Length() >= (UNSOL_RESPONSE_DATA_INDEX+1)) {
- buffer = ObjectWrap::Unwrap<Buffer>(args[UNSOL_RESPONSE_DATA_INDEX]->ToObject());
- } else {
- buffer = NULL;
- }
-
- UnsolRspConversionMap::iterator itr;
- itr = unsolRilRspConversionMap.find(cmd);
- if (itr != unsolRilRspConversionMap.end()) {
- itr->second(cmd, buffer);
- } else {
- if ((buffer == NULL) || (buffer->length() <= 0)) {
- // Nothing to convert
- data = NULL;
- datalen = 0;
- } else {
- // There was a buffer but we don't support the response yet.
- ALOGE("SendRilUnsolicitedResponse: No conversion routine for cmd %d,"
- " return RIL_E_REQUEST_NOT_SUPPORTED", cmd);
- data = NULL;
- datalen = 0;
- }
- s_rilenv->OnUnsolicitedResponse(cmd, NULL, 0);
- }
-
- DBG("SendRilUnsolicitedResponse X");
- return v8::Undefined();
-}
-
-int responsesInit(v8::Handle<v8::Context> context) {
- ALOGD("responsesInit E");
- int status = STATUS_OK;
-
- rilRspConversionMap[RIL_REQUEST_GET_SIM_STATUS] = RspGetSimStatus; // 1
- rilRspConversionMap[RIL_REQUEST_ENTER_SIM_PIN] = RspEnterSimPinData; // 2
- rilRspConversionMap[RIL_REQUEST_GET_CURRENT_CALLS] = RspGetCurrentCalls; // 9
- rilRspConversionMap[RIL_REQUEST_GET_IMSI] = RspString; // 11
- rilRspConversionMap[RIL_REQUEST_HANGUP] = RspWithNoData; // 12
- rilRspConversionMap[RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND] = RspWithNoData; // 13
- rilRspConversionMap[RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND] = RspWithNoData; // 14
- rilRspConversionMap[RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE] = RspWithNoData; // 15
- rilRspConversionMap[RIL_REQUEST_CONFERENCE] = RspWithNoData; // 16
- rilRspConversionMap[RIL_REQUEST_LAST_CALL_FAIL_CAUSE] = RspIntegers; // 18
- rilRspConversionMap[RIL_REQUEST_SIGNAL_STRENGTH] = RspSignalStrength; // 19
- rilRspConversionMap[RIL_REQUEST_VOICE_REGISTRATION_STATE] = RspStrings; // 20
- rilRspConversionMap[RIL_REQUEST_DATA_REGISTRATION_STATE] = RspStrings; // 21
- rilRspConversionMap[RIL_REQUEST_OPERATOR] = RspOperator; // 22
- rilRspConversionMap[RIL_REQUEST_GET_IMEI] = RspString; // 38
- rilRspConversionMap[RIL_REQUEST_GET_IMEISV] = RspString; // 39
- rilRspConversionMap[RIL_REQUEST_ANSWER] = RspWithNoData; // 39
- rilRspConversionMap[RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE] = RspIntegers; // 45
- rilRspConversionMap[RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC] = RspWithNoData; // 46
- rilRspConversionMap[RIL_REQUEST_BASEBAND_VERSION] = RspString; // 51
- rilRspConversionMap[RIL_REQUEST_SEPARATE_CONNECTION] = RspWithNoData; // 52
- rilRspConversionMap[RIL_REQUEST_SET_MUTE] = RspWithNoData; // 53
- rilRspConversionMap[RIL_REQUEST_SCREEN_STATE] = RspWithNoData; // 61
-
- unsolRilRspConversionMap[RIL_UNSOL_SIGNAL_STRENGTH] = UnsolRspSignalStrength; // 1009
-
-
- ALOGD("responsesInit X: status=%d", status);
- return STATUS_OK;
-}
diff --git a/mock-ril/src/cpp/responses.h b/mock-ril/src/cpp/responses.h
deleted file mode 100644
index e177066..0000000
--- a/mock-ril/src/cpp/responses.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 MOCK_RIL_RESPONSES_H_
-#define MOCK_RIL_RESPONSES_H_
-
-#include <v8.h>
-
-/**
- * Send a ril request complete, data is optional
- *
- * args[0] = rilErrCode
- * args[1] = cmd
- * args[2] = token
- * args[3] = optional data
- */
-#define REQUEST_COMPLETE_REQUIRED_CMDS 3
-#define REQUEST_COMPLETE_RIL_ERR_CODE_INDEX 0
-#define REQUEST_COMPLETE_CMD_INDEX 1
-#define REQUEST_COMPLETE_TOKEN_INDEX 2
-#define REQUEST_COMPLETE_DATA_INDEX 3
-v8::Handle<v8::Value> SendRilRequestComplete(const v8::Arguments& args);
-
-/**
- * Send a ril unsolicited response, buffer is optional
- *
- * args[0] = cmd
- * args[1] = optional data
- */
-#define UNSOL_RESPONSE_REQUIRED_CMDS 1
-#define UNSOL_RESPONSE_CMD_INDEX 0
-#define UNSOL_RESPONSE_DATA_INDEX 1
-v8::Handle<v8::Value> SendRilUnsolicitedResponse(const v8::Arguments& args);
-
-// Initialize module
-int responsesInit(v8::Handle<v8::Context> context);
-
-#endif // MOCK_RIL_RESPONSES_H_
diff --git a/mock-ril/src/cpp/ril.h b/mock-ril/src/cpp/ril.h
deleted file mode 120000
index eb9a122..0000000
--- a/mock-ril/src/cpp/ril.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../include/telephony/ril.h
\ No newline at end of file
diff --git a/mock-ril/src/cpp/status.h b/mock-ril/src/cpp/status.h
deleted file mode 100644
index cbacf22..0000000
--- a/mock-ril/src/cpp/status.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 __STATUS_H_
-#define __STATUS_H_
-
-// Internal STATUS values
-#define STATUS_OK 0
-#define STATUS_ERR 1
-#define STATUS_BAD_DATA 2
-#define STATUS_BAD_PARAMETER 3
-#define STATUS_UNSUPPORTED_REQUEST 4
-#define STATUS_UNSUPPORTED_RESPONSE 5
-#define STATUS_NO_JS_ONREQUEST_FUNCTION 6
-#define STATUS_COULD_NOT_OPEN_FILE 7
-#define STATUS_COULD_NOT_READ_FILE 8
-#define STATUS_CLIENT_CLOSED_CONNECTION 9
-
-
-#endif // __STATUS_H_
diff --git a/mock-ril/src/cpp/util.cpp b/mock-ril/src/cpp/util.cpp
deleted file mode 100644
index 97d9f9a..0000000
--- a/mock-ril/src/cpp/util.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 <v8.h>
-#include <string.h>
-
-#include "logging.h"
-#include "util.h"
-
-// Extracts a C string from a V8 Utf8Value.
-const char* ToCString(const v8::String::Utf8Value& value) {
- return *value ? *value : "<string conversion failed>";
-}
-
-// Extracts a C string from a V8 AsciiValue.
-const char* ToCString(const v8::String::AsciiValue& value) {
- return *value ? *value : "<string conversion failed>";
-}
-
-// Extracts a C string from a v8::Value
-const char* ToCString(v8::Handle<v8::Value> value) {
- v8::String::AsciiValue strAsciiValue(value);
- return ToCString(strAsciiValue);
-}
-
-// Report an exception
-void LogErrorMessage(v8::Handle<v8::Message> message,
- const char *alternate_message) {
- v8::HandleScope handle_scope;
- if (message.IsEmpty()) {
- // V8 didn't provide any extra information about this error; just
- // print the exception.
- if (alternate_message == NULL || strlen(alternate_message) == 0) {
- ALOGD("LogErrorMessage no message");
- } else {
- ALOGD("LogErrorMessage no message: %s", alternate_message);
- }
- } else {
- v8::String::Utf8Value filename(message->GetScriptResourceName());
- const char* filename_string = ToCString(filename);
- int linenum = message->GetLineNumber();
- ALOGD("file:%s line:%i", filename_string, linenum);
-
- // Print line of source code.
- v8::String::Utf8Value sourceline(message->GetSourceLine());
- const char* sourceline_string = ToCString(sourceline);
- ALOGD("%s", sourceline_string);
-
- // Print location information under source line
- int start = message->GetStartColumn();
- int end = message->GetEndColumn();
- int lenErr = end - start;
- int size = end + 1;
- if (lenErr == 0) {
- lenErr += 1;
- size += 1;
- }
- char *error_string = new char[size];
- memset(error_string, ' ', start);
- memset(&error_string[start], '^', lenErr);
- error_string[size-1] = 0;
- ALOGD("%s", error_string);
- ALOGD("%s", ToCString(v8::String::Utf8Value(message->Get())));
- delete [] error_string;
- }
-}
-
-// Report an exception
-void ReportException(v8::TryCatch* try_catch) {
- v8::HandleScope handle_scope;
-
- v8::String::Utf8Value exception(try_catch->Exception());
- v8::Handle<v8::Message> msg = try_catch->Message();
- if (msg.IsEmpty()) {
- // Why is try_catch->Message empty?
- // it is always empty on compile errors
- }
- LogErrorMessage(msg, ToCString(exception));
-}
diff --git a/mock-ril/src/cpp/util.h b/mock-ril/src/cpp/util.h
deleted file mode 100644
index 1e49176..0000000
--- a/mock-ril/src/cpp/util.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 MOCK_RIL_UTIL_H_
-#define MOCK_RIL_UTIL_H_
-
-const char* ToCString(const v8::String::Utf8Value& value);
-
-const char* ToCString(const v8::String::AsciiValue& value);
-
-const char* ToCString(v8::Handle<v8::Value> value);
-
-void LogErrorMessage(v8::Handle<v8::Message> message,
- const char *alternate_message);
-
-void ReportException(v8::TryCatch* try_catch);
-
-
-#endif // MOCK_RIL_UTIL_H_
diff --git a/mock-ril/src/cpp/worker.cpp b/mock-ril/src/cpp/worker.cpp
deleted file mode 100644
index 63eda56..0000000
--- a/mock-ril/src/cpp/worker.cpp
+++ /dev/null
@@ -1,367 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 "logging.h"
-#include "status.h"
-#include "worker.h"
-
-#include <time.h>
-
-//#define WORKER_DEBUG
-#ifdef WORKER_DEBUG
-
-#define DBG(...) ALOGD(__VA_ARGS__)
-
-#else
-
-#define DBG(...)
-
-#endif
-
-void * WorkerThread::Work(void *param) {
- WorkerThread *t = (WorkerThread *)param;
- android_atomic_acquire_store(STATE_RUNNING, &t->state_);
- void * v = t->Worker(t->workerParam_);
- android_atomic_acquire_store(STATE_STOPPED, &t->state_);
- return v;
-}
-
-bool WorkerThread::isRunning() {
- DBG("WorkerThread::isRunning E");
- bool ret_value = android_atomic_acquire_load(&state_) == STATE_RUNNING;
- DBG("WorkerThread::isRunning X ret_value=%d", ret_value);
- return ret_value;
-}
-
-WorkerThread::WorkerThread() {
- DBG("WorkerThread::WorkerThread E");
- state_ = STATE_INITIALIZED;
- pthread_mutex_init(&mutex_, NULL);
- pthread_cond_init(&cond_, NULL);
- DBG("WorkerThread::WorkerThread X");
-}
-
-WorkerThread::~WorkerThread() {
- DBG("WorkerThread::~WorkerThread E");
- Stop();
- pthread_mutex_destroy(&mutex_);
- DBG("WorkerThread::~WorkerThread X");
-}
-
-// Return true if changed from STATE_RUNNING to STATE_STOPPING
-bool WorkerThread::BeginStopping() {
- DBG("WorkerThread::BeginStopping E");
- bool ret_value = (android_atomic_acquire_cas(STATE_RUNNING, STATE_STOPPING, &state_) == 0);
- DBG("WorkerThread::BeginStopping X ret_value=%d", ret_value);
- return ret_value;
-}
-
-// Wait until state is not STATE_STOPPING
-void WorkerThread::WaitUntilStopped() {
- DBG("WorkerThread::WaitUntilStopped E");
- pthread_cond_signal(&cond_);
- while(android_atomic_release_load(&state_) == STATE_STOPPING) {
- usleep(200000);
- }
- DBG("WorkerThread::WaitUntilStopped X");
-}
-
-void WorkerThread::Stop() {
- DBG("WorkerThread::Stop E");
- if (BeginStopping()) {
- WaitUntilStopped();
- }
- DBG("WorkerThread::Stop X");
-}
-
-int WorkerThread::Run(void *workerParam) {
- DBG("WorkerThread::Run E workerParam=%p", workerParam);
- int status;
- int ret;
-
- workerParam_ = workerParam;
-
- ret = pthread_attr_init(&attr_);
- if (ret != 0) {
- ALOGE("RIL_Init X: pthread_attr_init failed err=%s", strerror(ret));
- return STATUS_ERR;
- }
- ret = pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_DETACHED);
- if (ret != 0) {
- ALOGE("RIL_Init X: pthread_attr_setdetachstate failed err=%s",
- strerror(ret));
- return STATUS_ERR;
- }
- ret = pthread_create(&tid_, &attr_,
- (void * (*)(void *))&WorkerThread::Work, this);
- if (ret != 0) {
- ALOGE("RIL_Init X: pthread_create failed err=%s", strerror(ret));
- return STATUS_ERR;
- }
-
- // Wait until worker is running
- while (android_atomic_acquire_load(&state_) == STATE_INITIALIZED) {
- usleep(200000);
- }
-
- DBG("WorkerThread::Run X workerParam=%p", workerParam);
- return STATUS_OK;
-}
-
-
-class WorkerQueueThread : public WorkerThread {
- private:
- friend class WorkerQueue;
-
- public:
- WorkerQueueThread() {
- }
-
- virtual ~WorkerQueueThread() {
- Stop();
- }
-
- void * Worker(void *param) {
- DBG("WorkerQueueThread::Worker E");
- WorkerQueue *wq = (WorkerQueue *)param;
-
- // Do the work until we're told to stop
- while (isRunning()) {
- pthread_mutex_lock(&mutex_);
- while (isRunning() && wq->q_.size() == 0) {
- if (wq->delayed_q_.size() == 0) {
- // Both queue's are empty so wait
- pthread_cond_wait(&cond_, &mutex_);
- } else {
- // delayed_q_ is not empty, move any
- // timed out records to q_.
- int64_t now = android::elapsedRealtime();
- while((wq->delayed_q_.size() != 0) &&
- ((wq->delayed_q_.top()->time - now) <= 0)) {
- struct WorkerQueue::Record *r = wq->delayed_q_.top();
- DBG("WorkerQueueThread::Worker move p=%p time=%lldms",
- r->p, r->time);
- wq->delayed_q_.pop();
- wq->q_.push_back(r);
- }
-
- if ((wq->q_.size() == 0) && (wq->delayed_q_.size() != 0)) {
- // We need to do a timed wait
- struct timeval tv;
- struct timespec ts;
- struct WorkerQueue::Record *r = wq->delayed_q_.top();
- int64_t delay_ms = r->time - now;
- DBG("WorkerQueueThread::Worker wait"
- " p=%p time=%lldms delay_ms=%lldms",
- r->p, r->time, delay_ms);
- gettimeofday(&tv, NULL);
- ts.tv_sec = tv.tv_sec + (delay_ms / 1000);
- ts.tv_nsec = (tv.tv_usec +
- ((delay_ms % 1000) * 1000)) * 1000;
- pthread_cond_timedwait(&cond_, &mutex_, &ts);
- }
- }
- }
- if (isRunning()) {
- struct WorkerQueue::Record *r = wq->q_.front();
- wq->q_.pop_front();
- void *p = r->p;
- wq->release_record(r);
- pthread_mutex_unlock(&mutex_);
- wq->Process(r->p);
- } else {
- pthread_mutex_unlock(&mutex_);
- }
- }
- DBG("WorkerQueueThread::Worker X");
- return NULL;
- }
-};
-
-WorkerQueue::WorkerQueue() {
- DBG("WorkerQueue::WorkerQueue E");
- wqt_ = new WorkerQueueThread();
- DBG("WorkerQueue::WorkerQueue X");
-}
-
-WorkerQueue::~WorkerQueue() {
- DBG("WorkerQueue::~WorkerQueue E");
- Stop();
-
- Record *r;
- pthread_mutex_lock(&wqt_->mutex_);
- while(free_list_.size() != 0) {
- r = free_list_.front();
- free_list_.pop_front();
- DBG("WorkerQueue::~WorkerQueue delete free_list_ r=%p", r);
- delete r;
- }
- while(delayed_q_.size() != 0) {
- r = delayed_q_.top();
- delayed_q_.pop();
- DBG("WorkerQueue::~WorkerQueue delete delayed_q_ r=%p", r);
- delete r;
- }
- pthread_mutex_unlock(&wqt_->mutex_);
-
- delete wqt_;
- DBG("WorkerQueue::~WorkerQueue X");
-}
-
-int WorkerQueue::Run() {
- return wqt_->Run(this);
-}
-
-void WorkerQueue::Stop() {
- wqt_->Stop();
-}
-
-/**
- * Obtain a record from free_list if it is not empty, fill in the record with provided
- * information: *p and delay_in_ms
- */
-struct WorkerQueue::Record *WorkerQueue::obtain_record(void *p, int delay_in_ms) {
- struct Record *r;
- if (free_list_.size() == 0) {
- r = new Record();
- DBG("WorkerQueue::obtain_record new r=%p", r);
- } else {
- r = free_list_.front();
- DBG("WorkerQueue::obtain_record reuse r=%p", r);
- free_list_.pop_front();
- }
- r->p = p;
- if (delay_in_ms != 0) {
- r->time = android::elapsedRealtime() + delay_in_ms;
- } else {
- r->time = 0;
- }
- return r;
-}
-
-/**
- * release a record and insert into the front of the free_list
- */
-void WorkerQueue::release_record(struct Record *r) {
- DBG("WorkerQueue::release_record r=%p", r);
- free_list_.push_front(r);
-}
-
-/**
- * Add a record to processing queue q_
- */
-void WorkerQueue::Add(void *p) {
- DBG("WorkerQueue::Add E:");
- pthread_mutex_lock(&wqt_->mutex_);
- struct Record *r = obtain_record(p, 0);
- q_.push_back(r);
- if (q_.size() == 1) {
- pthread_cond_signal(&wqt_->cond_);
- }
- pthread_mutex_unlock(&wqt_->mutex_);
- DBG("WorkerQueue::Add X:");
-}
-
-void WorkerQueue::AddDelayed(void *p, int delay_in_ms) {
- DBG("WorkerQueue::AddDelayed E:");
- if (delay_in_ms <= 0) {
- Add(p);
- } else {
- pthread_mutex_lock(&wqt_->mutex_);
- struct Record *r = obtain_record(p, delay_in_ms);
- delayed_q_.push(r);
-#ifdef WORKER_DEBUG
- int64_t now = android::elapsedRealtime();
- DBG("WorkerQueue::AddDelayed"
- " p=%p delay_in_ms=%d now=%lldms top->p=%p"
- " top->time=%lldms diff=%lldms",
- p, delay_in_ms, now, delayed_q_.top()->p,
- delayed_q_.top()->time, delayed_q_.top()->time - now);
-#endif
- if ((q_.size() == 0) && (delayed_q_.top() == r)) {
- // q_ is empty and the new record is at delayed_q_.top
- // so we signal the waiting thread so it can readjust
- // the wait time.
- DBG("WorkerQueue::AddDelayed signal");
- pthread_cond_signal(&wqt_->cond_);
- }
- pthread_mutex_unlock(&wqt_->mutex_);
- }
- DBG("WorkerQueue::AddDelayed X:");
-}
-
-
-class TestWorkerQueue : public WorkerQueue {
- virtual void Process(void *p) {
- ALOGD("TestWorkerQueue::Process: EX p=%p", p);
- }
-};
-
-class TesterThread : public WorkerThread {
- public:
- void * Worker(void *param)
- {
- ALOGD("TesterThread::Worker E param=%p", param);
- WorkerQueue *wq = (WorkerQueue *)param;
-
- // Test AddDelayed
- wq->AddDelayed((void *)1000, 1000);
- wq->Add((void *)0);
- wq->Add((void *)0);
- wq->Add((void *)0);
- wq->Add((void *)0);
- wq->AddDelayed((void *)100, 100);
- wq->AddDelayed((void *)2000, 2000);
-
- for (int i = 1; isRunning(); i++) {
- ALOGD("TesterThread: looping %d", i);
- wq->Add((void *)i);
- wq->Add((void *)i);
- wq->Add((void *)i);
- wq->Add((void *)i);
- sleep(1);
- }
-
- ALOGD("TesterThread::Worker X param=%p", param);
-
- return NULL;
- }
-};
-
-void testWorker() {
- ALOGD("testWorker E: ********");
-
- // Test we can create a thread and delete it
- TesterThread *tester = new TesterThread();
- delete tester;
-
- TestWorkerQueue *wq = new TestWorkerQueue();
- if (wq->Run() == STATUS_OK) {
- ALOGD("testWorker WorkerQueue %p running", wq);
-
- // Test we can run a thread, stop it then delete it
- tester = new TesterThread();
- tester->Run(wq);
- ALOGD("testWorker tester %p running", tester);
- sleep(10);
- ALOGD("testWorker tester %p stopping", tester);
- tester->Stop();
- ALOGD("testWorker tester %p stopped", tester);
- wq->Stop();
- ALOGD("testWorker wq %p stopped", wq);
- }
- ALOGD("testWorker X: ********\n");
-}
diff --git a/mock-ril/src/cpp/worker.h b/mock-ril/src/cpp/worker.h
deleted file mode 100644
index 9518fb3..0000000
--- a/mock-ril/src/cpp/worker.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 MOCK_RIL_WORKER_H_
-#define MOCK_RIL_WORKER_H_
-
-#include <queue>
-#include <list>
-#include <vector>
-#include <pthread.h>
-#include <cutils/atomic.h>
-#include <utils/SystemClock.h>
-
-/**
- * A Thread class.
- *
- * 0) Extend WorkerThread creating a Worker method which
- * monitors isRunning(). For example:
- *
- * void * Worker(void *param) {
- * while (isRunning() == 0) {
- * pthread_mutex_lock(&mutex_);
- * while (isRunning() && !SOME-CONDITION) {
- * pthread_cond_wait(&cond_, &mutex_);
- * }
- * if (isRunning()) {
- * DO-WORK
- * } else {
- * pthread_mutex_unlock(&mutex_);
- * }
- * }
- * return NULL;
- * }
- *
- * 1) Create the WorkerThread.
- * 2) Execute Run passing a param which will be passed to Worker.
- * 3) Call Stop() or destroy the thread to stop processing.
- *
- */
-class WorkerThread {
- protected:
- pthread_attr_t attr_;
- pthread_mutex_t mutex_;
- pthread_cond_t cond_;
- pthread_t tid_;
- void *workerParam_;
-
- #define STATE_INITIALIZED 1
- #define STATE_RUNNING 2
- #define STATE_STOPPING 3
- #define STATE_STOPPED 4
- int32_t state_;
-
- static void * Work(void *param);
-
- virtual bool isRunning();
-
- public:
- WorkerThread();
-
- virtual ~WorkerThread();
-
- // Return true if changed from STATE_RUNNING to STATE_STOPPING
- virtual bool BeginStopping();
-
- // Wait until state is not STATE_STOPPING
- virtual void WaitUntilStopped();
-
- virtual void Stop();
-
- virtual int Run(void *workerParam);
-
- /**
- * Method called to do work, see example above.
- * While running isRunning() must be monitored.
- */
- virtual void *Worker(void *) = 0;
-};
-
-
-/**
- * A WorkerQueue.
- *
- * 0) Extend overriding Process
- * 1) Create an instance
- * 2) Call Run.
- * 3) Call Add, passing a pointer which is added to a queue
- * 4) Process will be called with a pointer as work can be done.
- */
-class WorkerQueue {
- private:
- friend class WorkerQueueThread;
-
- struct Record {
- int64_t time;
- void *p;
- };
-
- class record_compare {
- public:
- // To get ascending order return true if lhs > rhs.
- bool operator() (const struct Record* lhs, const struct Record* rhs) const {
- return lhs->time > rhs->time;
- }
- };
-
- std::list<struct Record *> q_; // list of records to be processed
- std::list<struct Record *> free_list_; // list of records that have been released
- std::priority_queue<struct Record *, std::vector<struct Record *>, record_compare> delayed_q_;
- // list of records that are delayed
- class WorkerQueueThread *wqt_;
-
- protected:
- struct Record *obtain_record(void *p, int delay_in_ms);
-
- void release_record(struct Record *r);
-
- public:
- WorkerQueue();
-
- virtual ~WorkerQueue();
-
- int Run();
-
- void Stop();
-
- void Add(void *p);
-
- void AddDelayed(void *p, int delay_in_ms);
-
- virtual void Process(void *) = 0;
-};
-
-extern void testWorker();
-
-#endif // MOCK_RIL_WORKER_H_
diff --git a/mock-ril/src/cpp/worker_v8.cpp b/mock-ril/src/cpp/worker_v8.cpp
deleted file mode 100644
index 0e71b06..0000000
--- a/mock-ril/src/cpp/worker_v8.cpp
+++ /dev/null
@@ -1,224 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 <queue>
-#include <v8.h>
-
-#include "logging.h"
-#include "js_support.h"
-#include "node_object_wrap.h"
-#include "node_util.h"
-#include "util.h"
-#include "worker.h"
-
-#include "worker_v8.h"
-
-
-//#define WORKER_V8_V8_DEBUG
-#ifdef WORKER_V8_V8_DEBUG
-
-#define DBG(...) ALOGD(__VA_ARGS__)
-
-#else
-
-#define DBG(...)
-
-#endif
-
-v8::Persistent<v8::FunctionTemplate> WorkerV8Template;
-
-class WorkerV8 : public ObjectWrap {
- private:
- friend class Handler;
-
-
- struct ArgInfo {
- v8::Persistent<v8::Object> js_this;
- v8::Persistent<v8::Value> value;
- };
-
- pthread_mutex_t ai_free_list_mutex_;
- std::queue<ArgInfo *> ai_free_list_;
-
- ArgInfo *ObtainArgInfo() {
- ArgInfo *ai;
- pthread_mutex_lock(&ai_free_list_mutex_);
- if (ai_free_list_.size() == 0) {
- ai = new ArgInfo();
- } else {
- ai = ai_free_list_.front();
- ai_free_list_.pop();
- }
- pthread_mutex_unlock(&ai_free_list_mutex_);
- return ai;
- }
-
- void ReleaseArgInfo(ArgInfo *ai) {
- pthread_mutex_lock(&ai_free_list_mutex_);
- ai_free_list_.push(ai);
- pthread_mutex_unlock(&ai_free_list_mutex_);
- }
-
- class Handler : public WorkerQueue {
- private:
- v8::Persistent<v8::Value> functionValue_;
- WorkerV8 *worker_;
-
- public:
- Handler(WorkerV8 *worker, v8::Handle<v8::Value> value)
- : worker_(worker) {
- functionValue_ = v8::Persistent<v8::Value>::New(value);
- }
-
- void Process(void *param) {
- DBG("Handler::Process: E");
-
- v8::Locker locker;
- v8::HandleScope handle_scope;
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- ArgInfo *ai = (ArgInfo*)param;
- v8::Handle<v8::Value> args(ai->value);
- v8::Function::Cast(*functionValue_)->Call(ai->js_this, 1, &args);
-
- ai->js_this.Dispose();
- ai->value.Dispose();
-
- worker_->ReleaseArgInfo(ai);
-
- DBG("Handler::Process: X");
- }
- };
-
- Handler *handler_;
-
- public:
- WorkerV8(v8::Handle<v8::Object> self, v8::Handle<v8::Value> functionValue) {
- DBG("WorkerV8::WorkerV8 E:");
- pthread_mutex_init(&ai_free_list_mutex_, NULL);
- handler_ = new Handler(this, functionValue);
- Wrap(self);
- DBG("WorkerV8::WorkerV8 X: this=%p handler_=%p", this, handler_);
- }
-
- virtual ~WorkerV8() {
- DBG("~WorkerV8::WorkerV8 E:");
- DBG("~WorkerV8::WorkerV8 X:");
- }
-
- static v8::Handle<v8::Value> Run(const v8::Arguments& args) {
- WorkerV8 *workerV8 = ObjectWrap::Unwrap<WorkerV8>(args.This());
- DBG("WorkerV8::Run(args) E:");
- workerV8->handler_->Run();
- DBG("WorkerV8::Run(args) X:");
- return v8::Undefined();
- }
-
- static v8::Handle<v8::Value> Add(const v8::Arguments& args) {
- DBG("WorkerV8::Add(args) E:");
- WorkerV8 *workerV8 = ObjectWrap::Unwrap<WorkerV8>(args.This());
-
- // Validate one argument to add
- if (args.Length() != 1) {
- DBG("WorkerV8::Add(args) X: expecting one param");
- return v8::ThrowException(v8::String::New("Add has no parameter"));
- }
- ArgInfo *ai = workerV8->ObtainArgInfo();
- ai->js_this = v8::Persistent<v8::Object>::New( args.This() );
- ai->value = v8::Persistent<v8::Value>::New( args[0] );
-
- workerV8->handler_->Add(ai);
- DBG("WorkerV8::Add(args) X:");
- return v8::Undefined();
- }
-
- static v8::Handle<v8::Value> AddDelayed(const v8::Arguments& args) {
- DBG("WorkerV8::AddDelayed(args) E:");
- WorkerV8 *workerV8 = ObjectWrap::Unwrap<WorkerV8>(args.This());
-
- // Validate two argument to addDelayed
- if (args.Length() != 2) {
- DBG("WorkerV8::AddDelayed(args) X: expecting two params");
- return v8::ThrowException(v8::String::New("AddDelayed expects req delayTime params"));
- }
- ArgInfo *ai = workerV8->ObtainArgInfo();
- ai->js_this = v8::Persistent<v8::Object>::New( args.This() );
- ai->value = v8::Persistent<v8::Value>::New( args[0] );
- v8::Handle<v8::Value> v8DelayMs(args[1]->ToObject());
- int32_t delay_ms = v8DelayMs->Int32Value();
- workerV8->handler_->AddDelayed(ai, delay_ms);
-
- DBG("WorkerV8::AddDelayed(args) X:");
- return v8::Undefined();
- }
-
- static v8::Handle<v8::Value> NewWorkerV8(const v8::Arguments& args) {
- DBG("WorkerV8::NewWorkerV8 E: args.Length()=%d", args.Length());
- WorkerV8 *worker = new WorkerV8(args.This(), args[0]);
- DBG("WorkerV8::NewWorkerV8 X:");
- return worker->handle_;
- }
-};
-
-void WorkerV8Init() {
- DBG("WorkerV8Init E:");
- v8::HandleScope handle_scope;
-
- WorkerV8Template = v8::Persistent<v8::FunctionTemplate>::New(
- v8::FunctionTemplate::New(WorkerV8::NewWorkerV8));
- WorkerV8Template->SetClassName(v8::String::New("Worker"));
- // native self (Field 0 is handle_) field count is at least 1
- WorkerV8Template->InstanceTemplate()->SetInternalFieldCount(1);
-
- // Set prototype methods
- SET_PROTOTYPE_METHOD(WorkerV8Template, "run", WorkerV8::Run);
- SET_PROTOTYPE_METHOD(WorkerV8Template, "add", WorkerV8::Add);
- SET_PROTOTYPE_METHOD(WorkerV8Template, "addDelayed", WorkerV8::AddDelayed);
-
- DBG("WorkerV8Init X:");
-}
-
-void testWorkerV8(v8::Handle<v8::Context> context) {
- ALOGD("testWorkerV8 E: ********");
- v8::HandleScope handle_scope;
-
- v8::TryCatch try_catch;
- try_catch.SetVerbose(true);
-
- ALOGD("testWorkerV8 runJs");
- runJs(context, &try_catch, "local-string",
- "var w1 = new Worker(function (msg) {"
- " print('w1: ' + msg);\n"
- "});\n"
- "w1.run();\n"
- "var w2 = new Worker(function (msg) {"
- " print('w2: ' + msg);\n"
- "});\n"
- "w2.run();\n"
- "w2.addDelayed('three', 1000);\n"
- "w2.add('one');\n"
- "w1.add('two');\n"
- "w1.addDelayed('four', 2000);\n"
- );
- ALOGD("testWorkerV8 X: ********");
-}
-
-extern void WorkerV8ObjectTemplateInit(v8::Handle<v8::ObjectTemplate> target) {
- DBG("WorkerV8ObjectTemplateInit(target) E:");
- target->Set(v8::String::New("Worker"), WorkerV8Template);
- DBG("WorkerV8ObjectTemplateInit(target) X:\n");
-}
diff --git a/mock-ril/src/cpp/worker_v8.h b/mock-ril/src/cpp/worker_v8.h
deleted file mode 100644
index 7c9bb88..0000000
--- a/mock-ril/src/cpp/worker_v8.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 MOCK_RIL_WORKER_V8_H_
-#define MOCK_RIL_WORKER_V8_H_
-
-#include <v8.h>
-
-// Initialize this module
-extern void WorkerV8Init();
-
-// Add Worker to the object template
-extern void WorkerV8ObjectTemplateInit(v8::Handle<v8::ObjectTemplate> target);
-
-extern void testWorkerV8(v8::Handle<v8::Context> context);
-
-#endif // MOCK_RIL_WORKER_V8_H_
diff --git a/mock-ril/src/java/com/android/internal/communication/Msg.java b/mock-ril/src/java/com/android/internal/communication/Msg.java
deleted file mode 100644
index 6046fe7..0000000
--- a/mock-ril/src/java/com/android/internal/communication/Msg.java
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- * Copyright (C) 2010, The Android Open Source Project
- *
- * 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.
- */
-
-package com.android.internal.communication;
-
-import android.util.Log;
-
-import com.android.internal.communication.MsgHeader;
-import com.android.internal.telephony.RilChannel;
-import com.google.protobuf.micro.InvalidProtocolBufferMicroException;
-import com.google.protobuf.micro.MessageMicro;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-/**
- * A message
- */
-public class Msg {
- private MsgHeader mHeader;
- private ByteBuffer mData;
-
- /**
- * Send a message header
- *
- * @param mh is message header to write
- * @throws IOException
- */
- private static void sendHeader(RilChannel rc, MsgHeader mh) throws IOException {
- ByteBuffer lenBuffer = ByteBuffer.allocateDirect(4);
- lenBuffer.order(ByteOrder.LITTLE_ENDIAN);
- lenBuffer.putInt(mh.getSerializedSize());
-
- ByteBuffer mhBuffer = ByteBuffer.allocateDirect(mh.getCachedSize());
- mhBuffer.put(mh.toByteArray());
-
- rc.rewindSendAll(lenBuffer);
- rc.rewindSendAll(mhBuffer);
- }
-
- /**
- * Read a message header
- *
- * @returns message header
- * @throws IOException
- */
- private static MsgHeader recvHeader(RilChannel rc) throws IOException {
- ByteBuffer lenBuffer = ByteBuffer.allocate(4);
- lenBuffer.order(ByteOrder.LITTLE_ENDIAN);
- int lenRead = rc.recvAllRewind(lenBuffer);
- int lenHeader = lenBuffer.getInt();
-
- ByteBuffer mhBuffer = ByteBuffer.allocate(lenHeader);
- lenRead = rc.recvAllRewind(mhBuffer);
- MsgHeader mh = MsgHeader.parseFrom(mhBuffer.array());
- return mh;
- }
-
- /**
- * Msg Constructor
- */
- private Msg() {
- }
-
- /**
- * Get a message
- */
- public static Msg obtain() {
- // TODO: Get from a free list
- return new Msg();
- }
-
- /**
- * Release a message
- */
- public void release() {
- // TODO: place back on free list
- }
-
- /**
- * Send a message header followed by the data if present
- *
- * The length data field will be filled in as appropriate
- * @param mh header
- * @param data if not null and length > 0 sent after header
- * @throws IOException
- */
- public static final void send(RilChannel rc, MsgHeader mh, ByteBuffer data)
- throws IOException {
- int lenData;
-
- if (data == null) {
- lenData = 0;
- } else {
- data.rewind();
- lenData = data.remaining();
- }
- mh.setLengthData(lenData);
- sendHeader(rc, mh);
- if (lenData > 0) {
- rc.sendAll(data);
- }
- }
-
- /**
- * Send a message with cmd, token, status followed by the data.
- *
- * The length data field will be filled in as appropriate
- * @param cmd for the header
- * @param token for the header
- * @param status for the header
- * @param pb is the protobuf to send
- * @throws IOException
- */
- public static final void send(RilChannel rc, int cmd, long token, int status, MessageMicro pb)
- throws IOException {
- MsgHeader mh = new MsgHeader();
- mh.setCmd(cmd);
- mh.setToken(token);
- mh.setStatus(status);
-
- ByteBuffer data;
- if (pb != null) {
- data = ByteBuffer.wrap(pb.toByteArray());
- } else {
- data = null;
- }
- send(rc, mh, data);
- }
-
- /**
- * Send a message with cmd, token, status followed by the data.
- *
- * The length data field will be filled in as appropriate
- * @param cmd for the header
- * @param token for the header
- * @param pb is the protobuf to send
- * @throws IOException
- */
- public static final void send(RilChannel rc, int cmd, long token, MessageMicro pb)
- throws IOException {
- send(rc, cmd, token, 0, pb);
- }
-
- /**
- * Send a message with cmd followed by the data.
- *
- * The length data field will be filled in as appropriate
- * @param cmd for the header
- * @param pb is the protobuf to send
- * @throws IOException
- */
- public static final void send(RilChannel rc, int cmd, MessageMicro pb) throws IOException {
- send(rc, cmd, 0, 0, pb);
- }
-
- /**
- * Send a message with cmd, token and status but no data
- *
- * The length data field will be filled in as appropriate
- * @param cmd for the header
- * @param token for the header
- * @param status for the header
- * @throws IOException
- */
- public static final void send(RilChannel rc, int cmd, long token, int status)
- throws IOException {
- send(rc, cmd, token, status, null);
- }
-
- /**
- * Send a message with cmd and token but no data
- *
- * The length data field will be filled in as appropriate
- * @param cmd for the header
- * @param token for the header
- * @throws IOException
- */
- public static final void send(RilChannel rc, int cmd, long token) throws IOException {
- send(rc, cmd, token, 0, null);
- }
-
- /**
- * Send a message with cmd but no data
- *
- * The length data field will be filled in as appropriate
- * @param cmd for the header
- * @throws IOException
- */
- public static final void send(RilChannel rc, int cmd) throws IOException {
- send(rc, cmd, 0, 0, null);
- }
-
- /**
- * Read a message
- *
- * @return Msg
- * @throws IOException
- */
- public static final Msg recv(RilChannel rc) throws IOException {
- Msg msg = Msg.obtain();
- msg.read(rc);
- return msg;
- }
-
- /**
- * Read a message header and data.
- *
- * @throws IOException
- */
- public void read(RilChannel rc) throws IOException {
- mHeader = recvHeader(rc);
- if (mHeader.getLengthData() > 0) {
- ByteBuffer bb = ByteBuffer.allocate(mHeader.getLengthData());
- rc.recvAllRewind(bb);
- mData = bb;
- }
- }
-
- /**
- * Print the message header.
- *
- * @param tag for the header
- */
- public void printHeader(String tag) {
- Log.d(tag, " cmd=" + mHeader.getCmd() + " token=" + mHeader.getToken() + " status="
- + mHeader.getStatus() + " lengthData=" + mHeader.getLengthData());
- }
-
- /**
- * Set data (for testing purposes only).
- */
- public void setData(ByteBuffer data) {
- mData = data;
- }
-
- /**
- * Set header (for testing purposes only).
- */
- public void setHeader(MsgHeader header) {
- mHeader = header;
- }
-
- /**
- * @return cmd
- */
- public int getCmd() {
- return mHeader.getCmd();
- }
-
- /**
- * @return token
- */
- public long getToken() {
- return mHeader.getToken();
- }
-
- /**
- * @return status
- */
- public int getStatus() {
- return mHeader.getStatus();
- }
-
- /**
- * @return data ByteBuffer
- */
- public ByteBuffer getData() {
- return mData;
- }
-
- /**
- * @return data at index
- */
- public byte getData(int index) {
- return mData.get(index);
- }
-
- /**
- * Return data as a Class<T>.
- *
- * @param <T> a class that extends MessageMicro.
- * @param c the T.class to create from the data.
- * @param data is the MessageMicro protobuf to be converted.
- * @return null if an error occurs.
- */
- @SuppressWarnings("unchecked")
- public static final <T extends MessageMicro> T getAs(Class<T> c, byte[] data) {
- Object o = null;
- if ((data != null) && (data.length > 0)) {
- try {
- o = c.newInstance().mergeFrom(data);
- } catch (InvalidProtocolBufferMicroException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- return (T)o;
- }
-
- /**
- * Return data as a Class<T>.
- *
- * @param <T> a class that extends MessageMicro.
- * @param c the T.class to create from data.
- * @return null if an error occurs
- */
- @SuppressWarnings("unchecked")
- public <T extends MessageMicro> T getDataAs(Class<T> c) {
- Object o;
-
- if ((mData != null) && (mData.remaining() > 0)) {
- o = getAs(c, mData.array());
- } else {
- o = null;
- }
- return (T)o;
- }
-}
diff --git a/mock-ril/src/java/com/android/internal/telephony/RilChannel.java b/mock-ril/src/java/com/android/internal/telephony/RilChannel.java
deleted file mode 100644
index abe32c7..0000000
--- a/mock-ril/src/java/com/android/internal/telephony/RilChannel.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (C) 2010, The Android Open Source Project
- *
- * 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.
- */
-
-package com.android.internal.telephony;
-
-import android.util.Log;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.nio.channels.SocketChannel;
-import java.nio.ByteBuffer;
-
-public class RilChannel {
- private static final boolean DBG = false;
-
- private static final String MOCKRIL_ADDR_STR = "127.0.0.1";
- private static final int MOCKRIL_PORT = 54312;
- private SocketChannel mChannel = null;
-
- /**
- * Constructor
- */
- private RilChannel() {
- if (DBG) log("ctor EX");
- }
-
- /**
- * Open the channel
- *
- * @throws IOException
- */
- private void open() throws IOException {
- InetSocketAddress mockRilAddr = new InetSocketAddress(MOCKRIL_ADDR_STR, MOCKRIL_PORT);
- mChannel= SocketChannel.open(mockRilAddr);
- }
-
- /**
- * Make the channel
- *
- * @return the channel
- * @throws IOException
- */
- public static RilChannel makeRilChannel() throws IOException {
- if (DBG) log("makeMockRilChannel E");
- RilChannel sm = new RilChannel();
- sm.open();
- if (DBG) log("makeMockRilChannel X");
- return sm;
- }
-
- /**
- * Close an open channel
- */
- public void close() {
- try {
- if (mChannel != null) {
- mChannel.close();
- if (DBG) log("DefaultState.enter closed socket");
- }
- } catch (IOException e) {
- log("Could not close conection to mock-ril");
- e.printStackTrace();
- }
- }
-
- /**
- * @return the channel
- */
- public SocketChannel getChannel() {
- return mChannel;
- }
-
- /**
- * write the bb contents to sc
- *
- * @param bb is the ByteBuffer to write
- * @return number of bytes written
- * @throws IOException
- */
- public final int sendAll(ByteBuffer bb) throws IOException {
- int count = 0;
- while (bb.remaining() != 0) {
- count += mChannel.write(bb);
- }
- return count;
- }
-
- /**
- * read from sc until bb is filled then rewind bb
- *
- * @param bb is the ByteBuffer to fill
- * @return number of bytes read
- * @throws IOException
- */
- public final int recvAll(ByteBuffer bb) throws IOException {
- int count = 0;
- while (bb.remaining() != 0) {
- count += mChannel.read(bb);
- }
- return count;
- }
-
- /**
- * Rewind bb then write the contents to sc
- *
- * @param bb is the ByteBuffer to write
- * @return number of bytes written
- * @throws IOException
- */
- public final int rewindSendAll(ByteBuffer bb) throws IOException {
- bb.rewind();
- return sendAll(bb);
- }
-
- /**
- * read from sc until bb is filled then rewind bb
- *
- * @param bb is the ByteBuffer to fill
- * @return number of bytes read
- * @throws IOException
- */
- public final int recvAllRewind(ByteBuffer bb) throws IOException {
- int count = recvAll(bb);
- bb.rewind();
- return count;
- }
-
- /**
- * Write to log.
- *
- * @param s
- */
- static void log(String s) {
- Log.v("MockRilChannel", s);
- }
-}
diff --git a/mock-ril/src/js/ctrl_server.js b/mock-ril/src/js/ctrl_server.js
deleted file mode 100644
index e64b96c..0000000
--- a/mock-ril/src/js/ctrl_server.js
+++ /dev/null
@@ -1,188 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 Server
- */
-function CtrlServer() {
- // The result returned by the request handlers
- var result = new Object();
-
- this.ctrlGetRadioState = function(req) {
- print('ctrlGetRadioState');
-
- var rsp = new Object();
- rsp.state = gRadioState;
- result.responseProtobuf = ctrlSchema['ril_proto.CtrlRspRadioState'].serialize(rsp);
-
- return result;
- }
-
- this.ctrlSetRadioState = function(req) {
- print('ctrlSetRadioState');
-
- var radioReq = new Object();
-
- // Parse the request protobuf to an object, the returned value is a
- // string that represents the variable name
- radioReq = ctrlSchema['ril_proto.CtrlReqRadioState'].parse(req.protobuf);
-
- setRadioState(radioReq.state);
-
- // Prepare the response, return the current radio state
- var rsp = new Object();
- rsp.state = gRadioState;
- result.responseProtobuf = ctrlSchema['ril_proto.CtrlRspRadioState'].serialize(rsp);
- print('gRadioState after setting: ' + gRadioState);
- return result;
- }
-
- /**
- * Process the request
- */
- this.process = function(req) {
- try {
- print('CtrlServer E: req.cmd=' + req.cmd + ' req.token=' + req.token);
-
- // Assume the result will be true, successful and nothing to return
- result.sendResponse = true;
- result.ctrlStatus = CTRL_STATUS_OK;
- result.responseProtobuf = emptyProtobuf;
-
- // Default result will be success with no response protobuf
- try {
- result = (this.ctrlDispatchTable[req.cmd]).call(this, req);
- } catch (err) {
- print('ctrlServer: Unknown cmd=' + req.cmd);
- result.ctrlStatus = 1; //ril_proto.CTRL_STATUS_ERR;
- }
-
- if (result.sendResponse) {
- sendCtrlRequestComplete(result.ctrlStatus, req.cmd,
- req.token, result.responseProtobuf);
- }
-
- print('CtrlServer X: req.cmd=' + req.cmd + ' req.token=' + req.token);
- } catch (err) {
- print('CtrlServer X: Exception req.cmd=' +
- req.cmd + ' req.token=' + req.token + ' err=' + err);
- }
- }
-
- print('CtrlServer() ctor E');
- this.ctrlDispatchTable = new Array();
- this.ctrlDispatchTable[CTRL_CMD_GET_RADIO_STATE] = this.ctrlGetRadioState;
- this.ctrlDispatchTable[CTRL_CMD_SET_RADIO_STATE] = this.ctrlSetRadioState;
- print('CtrlServer() ctor X');
-}
-
-// The control server instance and its associated Worker
-var ctrlServer = new CtrlServer();
-var ctrlWorker = new Worker(function (req) {
- ctrlServer.process(req);
-});
-ctrlWorker.run();
-
-/**
- * Add the request to the ctrlServer Worker.
- */
-function onCtrlServerCmd(cmd, token, protobuf) {
- try {
- print('onCtrlServerCmd E cmd=' + cmd + ' token=' + token);
-
- print('onCtrlServerCmd add the request:');
-
-
- if (!isCtrlServerDispatchCommand(cmd)) {
- var ctrlServerReq = new Object();
- ctrlServerReq.cmd = cmd;
- ctrlServerReq.token = token;
- ctrlServerReq.protobuf = protobuf;
- print('onCtrlServerCmd: command to control server, add to the worker queue');
- // If it is a command to the control server, add to the control server worker queue
- ctrlWorker.add(ctrlServerReq);
- } else {
- // For other commands, we need to dispatch to the corresponding components
- try {
- print('onCtrlServerCmd: get entry from dispatchTable cmd:' + cmd );
- entry = ctrlServerDispatchTable[cmd];
- if (typeof entry == 'undefined') {
- throw ('entry = dispatchTable[' + cmd + '] was undefined');
- } else {
- var req = new Request(cmd, token, protobuf, ctrlSchema, entry.schemaName);
- for(i = 0; i < entry.components.length; i++) {
- entry.components[i].add(req);
- }
- }
- } catch (err) {
- print('onCtrlServerCmd: Unknown cmd=' + cmd + ' err=' + err);
- sendCtrlRequestComplete(RIL_E_REQUEST_NOT_SUPPORTED, cmd, token);
- }
- }
- print('onCtrlServerCmd X cmd=' + cmd + ' token=' + token);
- } catch (err) {
- print('onCtrlServerCmd X Exception err=' + err);
- }
-}
-
-function isCtrlServerDispatchCommand(cmd) {
- return (cmd > CTRL_CMD_DISPATH_BASE)
-}
-
-/**
- * Dispatch table for request, the control server will send those requests to
- * the corresponding components.
- *
- * Each table entry is index by the CTRL_CMD_xxxx
- * and contains an array of components this request
- * is to be sent to and the name of the schema
- * that converts the incoming protobuf to the
- * appropriate request data.
- *
- * ctrlServerDispatchTable[CTRL_CMD_xxx].components = Array of components
- * ctrlServerDisptachTable[CTRL_CMD_xxx].Entry.schemaName = 'Name-of-schema';
- */
-var ctrlServerDispatchTable = new Array();
-
-ctrlServerDispatchTable[CTRL_CMD_SET_MT_CALL] = { // 1001
- 'components' : [simulatedRadioWorker],
- 'schemaName' : 'CtrlReqSetMTCall',
-};
-ctrlServerDispatchTable[CTRL_CMD_HANGUP_CONN_REMOTE] = { // 1002
- 'components' : [simulatedRadioWorker],
- 'schemaName' : 'CtrlHangupConnRemote',
-};
-ctrlServerDispatchTable[CTRL_CMD_SET_CALL_TRANSITION_FLAG] = { // 1003
- 'components' : [simulatedRadioWorker],
- 'schemaName' : 'CtrlSetCallTransitionFlag',
-};
-ctrlServerDispatchTable[CTRL_CMD_SET_CALL_ALERT] = { // 1004
- 'components' : [simulatedRadioWorker],
-};
-ctrlServerDispatchTable[CTRL_CMD_SET_CALL_ACTIVE] = { // 1005
- 'components' : [simulatedRadioWorker],
-};
-ctrlServerDispatchTable[CTRL_CMD_ADD_DIALING_CALL] = { // 1006
- 'components' : [simulatedRadioWorker],
- 'schemaName' : 'CtrlReqAddDialingCall',
-};
-
-/**
- * Optional tests
- */
-if (false) {
- include("ctrl_server_tests.js");
-}
diff --git a/mock-ril/src/js/ctrl_server_tests.js b/mock-ril/src/js/ctrl_server_tests.js
deleted file mode 100644
index 0ef7615..0000000
--- a/mock-ril/src/js/ctrl_server_tests.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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.
- */
-
-// TOOD: Add tests
diff --git a/mock-ril/src/js/mock_ril.js b/mock-ril/src/js/mock_ril.js
deleted file mode 100644
index 8485358..0000000
--- a/mock-ril/src/js/mock_ril.js
+++ /dev/null
@@ -1,320 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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.
- */
-
-/**
- * @fileoverview Mock Radio Interface Layer (RIL) used for testing
- *
- * The following routines are defined in c++:
- *
- * Print a string to android log
- * print(string)
- *
- * Read a file to a string.
- * String readFileToString(String fileName)
- *
- * Read a file to a Buffer.
- * Buffer readFileToBuffer(String fileName)
- *
- * Send an response unsolicited response to the framework.
- * sendRilUnsolicitedResponse(Number responseNum, Buffer responseProtobuf)
- *
- * Send a completion request to the framework.
- * sendRilRequestComplete(Number rilErrCode, Number reqNum,
- * String token, Buffer responseProtobuf)
- *
- * Send a complete request to the controller.
- * sendCtrlRequestComplete(Number ctrlStatus, Number reqNum,
- * String token, Buffer responseProtobuf)
- *
- * Include the javascript file.
- * include(string)
- *
- * The following objects are defined in c++
- *
- * Buffer is defined in node_buffer and provides a wrapper
- * for a buffer that can be shared between c++ and js.
- * Buffer(length)
- * Buffer::length()
- * Buffer::data()
- *
- * Schema is defined in protobuf_v8 and converts between
- * a buffer and an object. A protobuf descriptor, ril.desc
- * and ctrl.desc, is used to drive the conversation.
- * Object Schema::parse(Buffer protobuf)
- * Buffer Schema::serialize(object)
- *
- * Worker is a thread which receives messages to be handled.
- * It is passed a function which is called once for each
- * message as it arrives. Call the add method to queue up
- * requests for the worker function to process.
- * Object Worker(function (req))
- * Worker::add(req);
- */
-
-/**
- * Globals
- */
-
-include("ril_vars.js");
-
-var NULL_RESPONSE_STRING = '*magic-null*';
-
-// The state of the radio, needed by currentState()
-var gRadioState = RADIOSTATE_UNAVAILABLE;
-
-// The state of the screen
-var gScreenState = 0;
-
-// The base band version
-var gBaseBandVersion = 'mock-ril 0.1';
-
-// define a global variable to access the global object
-var globals = this;
-
-// Empty Protobuf, defined here so we don't have
-// to recreate an empty Buffer frequently
-var emptyProtobuf = new Buffer();
-
-// Get the ril description file and create a schema
-var packageNameAndSeperator = 'ril_proto.';
-var rilSchema = new Schema(readFileToBuffer('ril.desc'));
-var ctrlSchema = new Schema(readFileToBuffer('ctrl.desc'));
-
-/**
- * Print properties of an object
- */
-function printProperties(obj, maxDepth, depth) {
- if (typeof maxDepth == 'undefined') {
- maxDepth = 1;
- }
- if (typeof depth == 'undefined') {
- depth = 1;
- }
- if (depth == 1) {
- print('printProperties:');
- }
- for (var property in obj) {
- try {
- if ((typeof obj[property] == 'object')
- && (depth < maxDepth)) {
- printProperties(obj[property], maxDepth, depth+1);
- } else {
- print(depth + ': ' + property + '=' + obj[property] +
- ' type=' + typeof obj[property]);
- }
- } catch (err) {
- print('err=' + err)
- }
- }
-}
-
-// Test printProperties
-if (false) {
- var myObject = { 'field1' : '1', 'field2' : '2', 'hello' : [ 'hi', 'there' ] };
- printProperties(myObject, 3);
-}
-
-/**
- * Include the components
- */
-
-include("simulated_radio.js");
-include("simulated_icc.js");
-include("ctrl_server.js");
-
-/**
- * Construct a new request which is passed to the
- * Worker handler method.
- */
-function Request(reqNum, token, protobuf, schema, schemaName) {
- this.reqNum = reqNum;
- this.token = token;
- try {
- this.data = schema[packageNameAndSeperator + schemaName].parse(protobuf);
- } catch (err) {
- // not a valid protobuf in the request
- this.data = null;
- }
-}
-
-/**
- * Dispatch incoming requests from RIL to the appropriate component.
- */
-function onRilRequest(reqNum, token, requestProtobuf) {
- try {
- //print('onRilRequest E: reqNum=' + reqNum + ' token=' + token);
-
- /**
- * Validate parameters
- */
- rilErrCode = RIL_E_SUCCESS;
- if (typeof reqNum != 'number') {
- print('onRilRequest: reqNum is not a number');
- rilErrCode = RIL_E_GENERIC_FAILURE;
- }
- if (typeof token != 'number') {
- print('onRilRequest: token is not a number');
- rilErrCode = RIL_E_GENERIC_FAILURE;
- }
- if (typeof requestProtobuf != 'object') {
- print('onRilRequest: requestProtobuf is not an object');
- rilErrCode = RIL_E_GENERIC_FAILURE;
- }
- if (rilErrCode != RIL_E_SUCCESS) {
- sendRilRequestComplete(rilErrCode, reqNum, token);
- return 'onRilRequest X: invalid parameter';
- }
-
- try {
- //print('onRilRequest: get entry from dispatchTable reqNum=' + reqNum);
- entry = dispatchTable[reqNum];
- if (typeof entry == 'undefined') {
- throw ('entry = dispatchTable[' + reqNum + '] was undefined');
- } else {
- req = new Request(reqNum, token, requestProtobuf, rilSchema, entry.schemaName);
- for(i = 0; i < entry.components.length; i++) {
- entry.components[i].add(req);
- }
- }
- } catch (err) {
- print('onRilRequest: Unknown reqNum=' + reqNum + ' err=' + err);
- sendRilRequestComplete(RIL_E_REQUEST_NOT_SUPPORTED, reqNum, token);
- }
- // print('onRilRequest X: reqNum=' + reqNum + ' token=' + token);
- } catch (err) {
- print('onRilRequest X: Exception err=' + err);
- return('onRilRequest X: Exception err=' + err);
- }
- return 'onRilRequest X';
-}
-
-function onUnsolicitedTick(tick) {
- print('onUnsolicitedTick EX tick=' + tick);
- return 3;
-}
-
-/**
- * Dispatch table for requests
- *
- * Each table entry is index by the RIL_REQUEST_xxxx
- * and contains an array of components this request
- * is to be sent to and the name of the schema
- * that converts the incoming protobuf to the
- * appropriate request data.
- *
- * DispatchTable[RIL_REQUEST_xxx].components = Array of components
- * DisptachTable[RIL_REQUEST_xxx].Entry.schemaName = 'Name-of-schema';
- */
-var dispatchTable = new Array();
-
-dispatchTable[RIL_REQUEST_GET_SIM_STATUS] = { // 1
- 'components' : [simulatedIccWorker],
- 'schemaName' : 'ReqGetSimStatus',
-};
-dispatchTable[RIL_REQUEST_ENTER_SIM_PIN] = { // 2
- 'components' : [simulatedIccWorker],
- 'schemaName' : 'ReqEnterSimPin',
-};
-dispatchTable[RIL_REQUEST_GET_CURRENT_CALLS] = { // 9
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_DIAL] = { // 10
- 'components' : [simulatedRadioWorker],
- 'schemaName' : 'ReqDial',
-};
-dispatchTable[RIL_REQUEST_GET_IMSI] = { // 11
- 'components' : [simulatedIccWorker],
-};
-dispatchTable[RIL_REQUEST_HANGUP] = { // 12
- 'components' : [simulatedRadioWorker],
- 'schemaName' : 'ReqHangUp',
-};
-dispatchTable[RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND] = { // 13
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND] = { // 14
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE] = { // 15
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_CONFERENCE] = { // 16
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_LAST_CALL_FAIL_CAUSE] = { // 18
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_SIGNAL_STRENGTH] = { // 19
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_VOICE_REGISTRATION_STATE] = { // 20
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_DATA_REGISTRATION_STATE] = { // 21
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_OPERATOR] = { // 22
- 'components' : [simulatedIccWorker],
-};
-dispatchTable[RIL_REQUEST_GET_IMEI] = { // 38
- 'components' : [simulatedIccWorker],
-};
-dispatchTable[RIL_REQUEST_GET_IMEISV] = { // 39
- 'components' : [simulatedIccWorker],
-};
-dispatchTable[RIL_REQUEST_ANSWER] = { // 40
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE] = { // 45
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC] = { // 46
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_BASEBAND_VERSION] = { // 51
- 'components' : [simulatedRadioWorker],
-};
-dispatchTable[RIL_REQUEST_SEPARATE_CONNECTION] = { // 52
- 'components' : [simulatedRadioWorker],
- 'schemaName' : 'ReqSeparateConnection',
-};
-dispatchTable[RIL_REQUEST_SET_MUTE ] = { // 53
- 'components' : [simulatedRadioWorker],
- 'schemaName' : 'ReqSetMute',
-};
-dispatchTable[RIL_REQUEST_SCREEN_STATE] = { // 61
- 'components' : [simulatedRadioWorker],
- 'schemaName' : 'ReqScreenState',
-};
-
-/**
- * Start the mock rill after loading
- */
-function startMockRil() {
- print("startMockRil E:");
- setRadioState(RADIOSTATE_SIM_READY);
- // send the signal strength after 5 seconds, wait until mock ril is started
- simulatedRadioWorker.addDelayed({
- 'reqNum' : CMD_UNSOL_SIGNAL_STRENGTH}, 5000);
- print("startMockRil X:");
-}
-
-/**
- * Optional tests
- */
-if (false) {
- include("mock_ril_tests.js");
-}
diff --git a/mock-ril/src/js/mock_ril_tests.js b/mock-ril/src/js/mock_ril_tests.js
deleted file mode 100644
index 0ef7615..0000000
--- a/mock-ril/src/js/mock_ril_tests.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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.
- */
-
-// TOOD: Add tests
diff --git a/mock-ril/src/js/ril_vars.js b/mock-ril/src/js/ril_vars.js
deleted file mode 100644
index aadc35a..0000000
--- a/mock-ril/src/js/ril_vars.js
+++ /dev/null
@@ -1,346 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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.
- */
-
-/**
- * variables from ril.h
- */
-
-/**
- * RIL Error codes
- */
-var RIL_E_SUCCESS = 0;
-var RIL_E_RADIO_NOT_AVAILABLE = 1; /* If radio did not start or is resetting */
-var RIL_E_GENERIC_FAILURE = 2;
-var RIL_E_PASSWORD_INCORRECT = 3; /* for PIN/PIN2 methods only! */
-var RIL_E_SIM_PIN2 = 4; /* Operation requires SIM PIN2 to be entered */
-var RIL_E_SIM_PUK2 = 5; /* Operation requires SIM PIN2 to be entered */
-var RIL_E_REQUEST_NOT_SUPPORTED = 6;
-var RIL_E_CANCELLED = 7;
-var RIL_E_OP_NOT_ALLOWED_DURING_VOICE_CALL = 8; /* data ops are not allowed during voice
- call on a Class C GPRS device */
-var RIL_E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW = 9; /* data ops are not allowed before device
- registers in network */
-var RIL_E_SMS_SEND_FAIL_RETRY = 10; /* fail to send sms and need retry */
-var RIL_E_SIM_ABSENT = 11; /* fail to set the location where CDMA subscription
- shall be retrieved because of SIM or RUIM
- card absent */
-var RIL_E_SUBSCRIPTION_NOT_AVAILABLE = 12; /* fail to find CDMA subscription from specified
- location */
-var RIL_E_MODE_NOT_SUPPORTED = 13; /* HW does not support preferred network type */
-var RIL_E_FDN_CHECK_FAILURE = 14; /* command failed because recipient is not on FDN
- list */
-var RIL_E_ILLEGAL_SIM_OR_ME = 15; /* network selection failed due to */
-
-var CARD_MAX_APPS = 8;
-
-/**
- * Icc card state
- */
-var CARDSTATE_ABSENT = 0;
-var CARDSTATE_PRESENT = 1;
-var CARDSTATE_ERROR = 2;
-
-/**
- * RIL_PersoSubState
- */
-var PERSOSUBSTATE_UNKNOWN = 0; /* initial state */
-var PERSOSUBSTATE_IN_PROGRESS = 1; /* in between each lock transition */
-var PERSOSUBSTATE_READY = 2; /* when either SIM or RUIM Perso is finished
- since each app can only have 1 active perso
- involved */
-var PERSOSUBSTATE_SIM_NETWORK = 3;
-var PERSOSUBSTATE_SIM_NETWORK_SUBSET = 4;
-var PERSOSUBSTATE_SIM_CORPORATE = 5;
-var PERSOSUBSTATE_SIM_SERVICE_PROVIDER = 6;
-var PERSOSUBSTATE_SIM_SIM = 7;
-var PERSOSUBSTATE_SIM_NETWORK_PUK = 8; /* The corresponding perso lock is blocked */
-var PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK = 9;
-var PERSOSUBSTATE_SIM_CORPORATE_PUK = 10;
-var PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK = 11;
-var PERSOSUBSTATE_SIM_SIM_PUK = 12;
-var PERSOSUBSTATE_RUIM_NETWORK1 = 13;
-var PERSOSUBSTATE_RUIM_NETWORK2 = 14;
-var PERSOSUBSTATE_RUIM_HRPD = 15;
-var PERSOSUBSTATE_RUIM_CORPORATE = 16;
-var PERSOSUBSTATE_RUIM_SERVICE_PROVIDER = 17;
-var PERSOSUBSTATE_RUIM_RUIM = 18;
-var PERSOSUBSTATE_RUIM_NETWORK1_PUK = 19; /* The corresponding perso lock is blocked */
-var PERSOSUBSTATE_RUIM_NETWORK2_PUK = 20;
-var PERSOSUBSTATE_RUIM_HRPD_PUK = 21;
-var PERSOSUBSTATE_RUIM_CORPORATE_PUK = 22;
-var PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK = 23;
-var PERSOSUBSTATE_RUIM_RUIM_PUK = 24;
-
-/**
- * RIL_AppState
- */
-var APPSTATE_UNKNOWN = 0;
-var APPSTATE_DETECTED = 1;
-var APPSTATE_PIN = 2; /* If PIN1 or UPin is required */
-var APPSTATE_PUK = 3; /* If PUK1 or Puk for UPin is required */
-var APPSTATE_SUBSCRIPTION_PERSO = 4; /* perso_substate should be look at
- when app_state is assigned to this value */
-var APPSTATE_READY = 5;
-
-/**
- * RIL_PinState
- */
-var PINSTATE_UNKNOWN = 0;
-var PINSTATE_ENABLED_NOT_VERIFIED = 1;
-var PINSTATE_ENABLED_VERIFIED = 2;
-var PINSTATE_DISABLED = 3;
-var PINSTATE_ENABLED_BLOCKED = 4;
-var PINSTATE_ENABLED_PERM_BLOCKED = 5;
-
-/**
- * RIL_AppType
- */
-var APPTYPE_UNKNOWN = 0;
-var APPTYPE_SIM = 1;
-var APPTYPE_USIM = 2;
-var APPTYPE_RUIM = 3;
-var APPTYPE_CSIM = 4;
-
-/**
- * RIL_CallState
- */
-var CALLSTATE_ACTIVE = 0;
-var CALLSTATE_HOLDING = 1;
-var CALLSTATE_DIALING = 2; /* MO call only */
-var CALLSTATE_ALERTING = 3; /* MO call only */
-var CALLSTATE_INCOMING = 4; /* MT call only */
-var CALLSTATE_WAITING = 5; /* MT call only */
-
-/**
- * RIL_RadioState
- */
-var RADIOSTATE_OFF = 0; /* Radio explictly powered off (eg CFUN=0) */
-var RADIOSTATE_UNAVAILABLE = 1; /* Radio unavailable (eg, resetting or not booted) */
-var RADIOSTATE_SIM_NOT_READY = 2; /* Radio is on, but the SIM interface is not ready */
-var RADIOSTATE_SIM_LOCKED_OR_ABSENT = 3; /* SIM PIN locked, PUK required, network
- personalization locked; or SIM absent */
-var RADIOSTATE_SIM_READY = 4; /* Radio is on and SIM interface is available */
-var RADIOSTATE_RUIM_NOT_READY = 5; /* Radio is on, but the RUIM interface is not ready */
-var RADIOSTATE_RUIM_READY = 6; /* Radio is on and the RUIM interface is available */
-var RADIOSTATE_RUIM_LOCKED_OR_ABSENT = 7; /* RUIM PIN locked, PUK required, network
- personalization locked; or RUIM absent */
-var RADIOSTATE_NV_NOT_READY = 8; /* Radio is on, but the NV interface is not available */
-var RADIOSTATE_NV_READY = 9; /* Radio is on and the NV interface is available */
-
-/**
- * Last call fail cause
- */
-var CALL_FAIL_UNOBTAINABLE_NUMBER = 1;
-var CALL_FAIL_NORMAL = 16;
-var CALL_FAIL_BUSY = 17;
-var CALL_FAIL_CONGESTION = 34;
-var CALL_FAIL_ACM_LIMIT_EXCEEDED = 68;
-var CALL_FAIL_CALL_BARRED = 240;
-var CALL_FAIL_FDN_BLOCKED = 241;
-var CALL_FAIL_IMSI_UNKNOWN_IN_VLR = 242;
-var CALL_FAIL_IMEI_NOT_ACCEPTED = 243;
-var CALL_FAIL_CDMA_LOCKED_UNTIL_POWER_CYCLE = 1000;
-var CALL_FAIL_CDMA_DROP = 1001;
-var CALL_FAIL_CDMA_INTERCEPT = 1002;
-var CALL_FAIL_CDMA_REORDER = 1003;
-var CALL_FAIL_CDMA_SO_REJECT = 1004;
-var CALL_FAIL_CDMA_RETRY_ORDER = 1005;
-var CALL_FAIL_CDMA_ACCESS_FAILURE = 1006;
-var CALL_FAIL_CDMA_PREEMPTED = 1007;
-var CALL_FAIL_CDMA_NOT_EMERGENCY = 1008; /* For non-emergency number dialed during emergency callback mode */
-var CALL_FAIL_CDMA_ACCESS_BLOCKED = 1009; /* CDMA network access probes blocked */
-var CALL_FAIL_ERROR_UNSPECIFIED = 0xffff;
-
-/**
- * RIL requests
- */
-var RIL_REQUEST_GET_SIM_STATUS = 1
-var RIL_REQUEST_ENTER_SIM_PIN = 2
-var RIL_REQUEST_ENTER_SIM_PUK = 3
-var RIL_REQUEST_ENTER_SIM_PIN2 = 4
-var RIL_REQUEST_ENTER_SIM_PUK2 = 5
-var RIL_REQUEST_CHANGE_SIM_PIN = 6
-var RIL_REQUEST_CHANGE_SIM_PIN2 = 7
-var RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION = 8
-var RIL_REQUEST_GET_CURRENT_CALLS = 9
-var RIL_REQUEST_DIAL = 10
-var RIL_REQUEST_GET_IMSI = 11
-var RIL_REQUEST_HANGUP = 12
-var RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND = 13
-var RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND = 14
-var RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE = 15
-var RIL_REQUEST_SWITCH_HOLDING_AND_ACTIVE = 15
-var RIL_REQUEST_CONFERENCE = 16
-var RIL_REQUEST_UDUB = 17
-var RIL_REQUEST_LAST_CALL_FAIL_CAUSE = 18
-var RIL_REQUEST_SIGNAL_STRENGTH = 19
-var RIL_REQUEST_VOICE_REGISTRATION_STATE = 20
-var RIL_REQUEST_DATA_REGISTRATION_STATE = 21
-var RIL_REQUEST_OPERATOR = 22
-var RIL_REQUEST_RADIO_POWER = 23
-var RIL_REQUEST_DTMF = 24
-var RIL_REQUEST_SEND_SMS = 25
-var RIL_REQUEST_SEND_SMS_EXPECT_MORE = 26
-var RIL_REQUEST_SETUP_DATA_CALL = 27
-var RIL_REQUEST_SIM_IO = 28
-var RIL_REQUEST_SEND_USSD = 29
-var RIL_REQUEST_CANCEL_USSD = 30
-var RIL_REQUEST_GET_CLIR = 31
-var RIL_REQUEST_SET_CLIR = 32
-var RIL_REQUEST_QUERY_CALL_FORWARD_STATUS = 33
-var RIL_REQUEST_SET_CALL_FORWARD = 34
-var RIL_REQUEST_QUERY_CALL_WAITING = 35
-var RIL_REQUEST_SET_CALL_WAITING = 36
-var RIL_REQUEST_SMS_ACKNOWLEDGE = 37
-var RIL_REQUEST_GET_IMEI = 38
-var RIL_REQUEST_GET_IMEISV = 39
-var RIL_REQUEST_ANSWER = 40
-var RIL_REQUEST_DEACTIVATE_DATA_CALL = 41
-var RIL_REQUEST_QUERY_FACILITY_LOCK = 42
-var RIL_REQUEST_SET_FACILITY_LOCK = 43
-var RIL_REQUEST_CHANGE_BARRING_PASSWORD = 44
-var RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE = 45
-var RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC = 46
-var RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL = 47
-var RIL_REQUEST_QUERY_AVAILABLE_NETWORKS = 48
-var RIL_REQUEST_DTMF_START = 49
-var RIL_REQUEST_DTMF_STOP = 50
-var RIL_REQUEST_BASEBAND_VERSION = 51
-var RIL_REQUEST_SEPARATE_CONNECTION = 52
-var RIL_REQUEST_SET_MUTE = 53
-var RIL_REQUEST_GET_MUTE = 54
-var RIL_REQUEST_QUERY_CLIP = 55
-var RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE = 56
-var RIL_REQUEST_DATA_CALL_LIST = 57
-var RIL_REQUEST_RESET_RADIO = 58
-var RIL_REQUEST_OEM_HOOK_RAW = 59
-var RIL_REQUEST_OEM_HOOK_STRINGS = 60
-var RIL_REQUEST_SCREEN_STATE = 61
-var RIL_REQUEST_SET_SUPP_SVC_NOTIFICATION = 62
-var RIL_REQUEST_WRITE_SMS_TO_SIM = 63
-var RIL_REQUEST_DELETE_SMS_ON_SIM = 64
-var RIL_REQUEST_SET_BAND_MODE = 65
-var RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE = 66
-var RIL_REQUEST_STK_GET_PROFILE = 67
-var RIL_REQUEST_STK_SET_PROFILE = 68
-var RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND = 69
-var RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE = 70
-var RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM = 71
-var RIL_REQUEST_EXPLICIT_CALL_TRANSFER = 72
-var RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE = 73
-var RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE = 74
-var RIL_REQUEST_GET_NEIGHBORING_CELL_IDS = 75
-var RIL_REQUEST_SET_LOCATION_UPDATES = 76
-var RIL_REQUEST_CDMA_SET_SUBSCRIPTION = 77
-var RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE = 78
-var RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE = 79
-var RIL_REQUEST_SET_TTY_MODE = 80
-var RIL_REQUEST_QUERY_TTY_MODE = 81
-var RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE = 82
-var RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE = 83
-var RIL_REQUEST_CDMA_FLASH = 84
-var RIL_REQUEST_CDMA_BURST_DTMF = 85
-var RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY = 86
-var RIL_REQUEST_CDMA_SEND_SMS = 87
-var RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE = 88
-var RIL_REQUEST_GSM_GET_BROADCAST_SMS_CONFIG = 89
-var RIL_REQUEST_GSM_SET_BROADCAST_SMS_CONFIG = 90
-var RIL_REQUEST_GSM_SMS_BROADCAST_ACTIVATION = 91
-var RIL_REQUEST_CDMA_GET_BROADCAST_SMS_CONFIG = 92
-var RIL_REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG = 93
-var RIL_REQUEST_CDMA_SMS_BROADCAST_ACTIVATION = 94
-var RIL_REQUEST_CDMA_SUBSCRIPTION = 95
-var RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM = 96
-var RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM = 97
-var RIL_REQUEST_DEVICE_IDENTITY = 98
-var RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE = 99
-var RIL_REQUEST_GET_SMSC_ADDRESS = 100
-var RIL_REQUEST_SET_SMSC_ADDRESS = 101
-var RIL_REQUEST_REPORT_SMS_MEMORY_STATUS = 102
-var RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING = 103
-
-/**
- * RIL unsolicited requests
- */
-var RIL_UNSOL_RESPONSE_BASE = 1000
-var RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED = 1000
-var RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED = 1001
-var RIL_UNSOL_RESPONSE_NETWORK_STATE_CHANGED = 1002
-var RIL_UNSOL_RESPONSE_NEW_SMS = 1003
-var RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT = 1004
-var RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM = 1005
-var RIL_UNSOL_ON_USSD = 1006
-var RIL_UNSOL_ON_USSD_REQUEST = 1007
-var RIL_UNSOL_NITZ_TIME_RECEIVED = 1008
-var RIL_UNSOL_SIGNAL_STRENGTH = 1009
-var RIL_UNSOL_DATA_CALL_LIST_CHANGED = 1010
-var RIL_UNSOL_SUPP_SVC_NOTIFICATION = 1011
-var RIL_UNSOL_STK_SESSION_END = 1012
-var RIL_UNSOL_STK_PROACTIVE_COMMAND = 1013
-var RIL_UNSOL_STK_EVENT_NOTIFY = 1014
-var RIL_UNSOL_STK_CALL_SETUP = 1015
-var RIL_UNSOL_SIM_SMS_STORAGE_FULL = 1016
-var RIL_UNSOL_SIM_REFRESH = 1017
-var RIL_UNSOL_CALL_RING = 1018
-var RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED = 1019
-var RIL_UNSOL_RESPONSE_CDMA_NEW_SMS = 1020
-var RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS = 1021
-var RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL = 1022
-var RIL_UNSOL_RESTRICTED_STATE_CHANGED = 1023
-var RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE = 1024
-var RIL_UNSOL_CDMA_CALL_WAITING = 1025
-var RIL_UNSOL_CDMA_OTA_PROVISION_STATUS = 1026
-var RIL_UNSOL_CDMA_INFO_REC = 1027
-var RIL_UNSOL_OEM_HOOK_RAW = 1028
-var RIL_UNSOL_RINGBACK_TONE = 1029
-var RIL_UNSOL_RESEND_INCALL_MUTE = 1030
-
-/**
- * Control commands in ctrl.proto for control server
- */
-var CTRL_CMD_GET_RADIO_STATE = 1
-var CTRL_CMD_SET_RADIO_STATE = 2
-
-/**
- * Control commands in ctrl.proto that will be dispatched to
- * simulatedRadio or simulatedIcc
- */
-var CTRL_CMD_DISPATH_BASE = 1000
-var CTRL_CMD_SET_MT_CALL = 1001
-var CTRL_CMD_HANGUP_CONN_REMOTE = 1002
-var CTRL_CMD_SET_CALL_TRANSITION_FLAG = 1003
-var CTRL_CMD_SET_CALL_ALERT = 1004
-var CTRL_CMD_SET_CALL_ACTIVE = 1005
-var CTRL_CMD_ADD_DIALING_CALL = 1006
-
-/* status for control commands, defined in ctrl.proto */
-var CTRL_STATUS_OK = 0
-var CTRL_STATUS_ERR = 1
-
-/**
- * Local requests from simulated_radio or simulated_icc
- */
-var CMD_DELAY_TEST = 2000
-var CMD_UNSOL_SIGNAL_STRENGTH = 2001
-var CMD_UNSOL_CALL_STATE_CHANGED = 2002 // Send RIL_UNSOL_CALL_STATE_CHANGED
-var CMD_CALL_STATE_CHANGE = 2003 // call state change: dialing->alert->active
-var CMD_UNSOL_CALL_RING = 2004
-
-/**
- * Other variables
- */
-var OUTGOING = 0; /* outgoing call */
-var INCOMING = 1; /* incoming call */
diff --git a/mock-ril/src/js/simulated_icc.js b/mock-ril/src/js/simulated_icc.js
deleted file mode 100644
index 959031f..0000000
--- a/mock-ril/src/js/simulated_icc.js
+++ /dev/null
@@ -1,186 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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.
- */
-
-/**
- * Simulated Icc
- */
-function Icc() {
-
- var MCC = '310';
- var MNC = '260';
- var MSN = '123456789';
- var IMEI = '123456789012345';
- var IMEISV = '00';
-
- function RilAppStatus(type, state, persoState, aidPtr, appLabelPtr, pin1R, curPin1, curPin2) {
- this.appType = type;
- this.appState = state;
- this.persoSubstate = persoState;
- this.aid = aidPtr;
- this.appLabel = appLabelPtr;
- this.pin1Replaced = pin1R;
- this.pin1 = curPin1;
- this.pint2 = curPin2;
- }
-
- function RilCardStatus() {
- this.cardState = CARDSTATE_PRESENT;
- this.universalPinState = PINSTATE_UNKNOWN;
- this.gsmUmtsSubscriptionAppIndex = 0;
- this.cdmaSubscriptionAppIndex = CARD_MAX_APPS;
- this.imsSubscriptionAppIndex = CARD_MAX_APPS;
- this.numApplications = 1;
- this.applications = new Array(CARD_MAX_APPS);
-
- // Initialize application status
- for (i = 0; i < CARD_MAX_APPS; i++) {
- var app = new RilAppStatus(APPTYPE_UNKNOWN, APPSTATE_UNKNOWN, PERSOSUBSTATE_UNKNOWN,
- null, null, 0, PINSTATE_UNKNOWN, PINSTATE_UNKNOWN);
- this.applications[i] = app;
- }
-
- // set gsm application status.
- var gsmApp = new RilAppStatus(APPTYPE_SIM, APPSTATE_READY, PERSOSUBSTATE_READY, null, null,
- 0, PINSTATE_UNKNOWN, PINSTATE_UNKNOWN);
- this.applications[this.gsmUmtsSubscriptionAppIndex] = gsmApp;
- }
-
- var cardStatus = new RilCardStatus();
-
- // The result returned by the request handlers
- var result = new Object();
-
- this.rilRequestGetSimStatus = function(req) { // 1
- print('Icc: rilRequestGetSimStatus');
-
- var rsp = new Object();
- rsp.cardStatus = cardStatus;
-
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspGetSimStatus'].serialize(rsp);
- return result;
- }
-
- this.rilRequestEnterSimPin = function(req) { // 2
- print('Icc: rilRequestEnterSimPin req.data.pin=' + req.data.pin);
-
- var rsp = new Object();
- rsp.retriesRemaining = 3;
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspEnterSimPin'].serialize(rsp);
- return result;
- }
-
- this.rilRequestGetImsi = function(req) { // 11
- print('Icc: rilRequestGetImsi');
-
- var rsp = new Object();
- rsp.strings = new Array();
- rsp.strings[0] = MCC + MNC + MSN;
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspStrings'].serialize(rsp);
- return result;
- }
-
- this.rilRequestOperator = function(req) { // 22
- print('Icc: rilRequestOperator');
-
- var rsp = new Object();
- rsp.longAlphaOns = 'Mock-Ril long Alpha Ons';
- rsp.shortAlphaOns = 'Mock-Ril';
- rsp.mccMnc = MCC + MNC;
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspOperator'].serialize(rsp);
- return result;
- }
-
- this.rilRequestGetImei = function(req) { // 38
- print('Icc: rilRequestGetImei');
-
- var rsp = new Object();
- rsp.strings = new Array();
- rsp.strings[0] = IMEI;
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspStrings'].serialize(rsp);
- return result;
- }
-
- this.rilRequestGetImeisv = function(req) { // 39
- print('Icc: rilRequestGetImeisv');
-
- var rsp = new Object();
- rsp.strings = new Array();
- rsp.strings[0] = IMEISV;
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspStrings'].serialize(rsp);
- return result;
- }
-
- /**
- * Process the request
- */
- this.process = function(req) {
- try {
- // print('Icc E: req.reqNum=' + req.reqNum + ' req.token=' + req.token);
-
- // Assume the result will be true, successful and nothing to return
- result.sendResponse = true;
- result.rilErrCode = RIL_E_SUCCESS;
- result.responseProtobuf = emptyProtobuf;
-
- try {
- result = (this.simDispatchTable[req.reqNum]).call(this, req);
- } catch (err) {
- print('Icc: Unknown reqNum=' + req.reqNum);
- result.rilErrCode = RIL_E_REQUEST_NOT_SUPPORTED;
- }
-
- if (result.sendResponse) {
- sendRilRequestComplete(result.rilErrCode, req.reqNum,
- req.token, result.responseProtobuf);
- }
-
- // print('Icc X: req.reqNum=' + req.reqNum + ' req.token=' + req.token);
- } catch (err) {
- print('Icc X: Exception req.reqNum=' +
- req.reqNum + ' req.token=' + req.token + ' err=' + err);
- }
- }
-
- print('Icc: constructor E');
- this.simDispatchTable = new Array();
- this.simDispatchTable[RIL_REQUEST_GET_SIM_STATUS] = this.rilRequestGetSimStatus; // 1
- this.simDispatchTable[RIL_REQUEST_ENTER_SIM_PIN] = this.rilRequestEnterSimPin; // 2
- this.simDispatchTable[RIL_REQUEST_GET_IMSI] = this.rilRequestGetImsi; // 11
- this.simDispatchTable[RIL_REQUEST_OPERATOR] = this.rilRequestOperator; // 22
- this.simDispatchTable[RIL_REQUEST_GET_IMEI] = this.rilRequestGetImei; // 38
- this.simDispatchTable[RIL_REQUEST_GET_IMEISV] = this.rilRequestGetImeisv; // 39
- print('Icc: constructor X');
-}
-
-// The simulated sim instance and its associated Worker
-var simulatedIcc = new Icc();
-var simulatedIccWorker = new Worker(function (req) {
- simulatedIcc.process(req);
-});
-simulatedIccWorker.run();
-
-/**
- * Optional tests
- */
-if (false) {
- include("simulated_icc_tests.js");
-}
diff --git a/mock-ril/src/js/simulated_icc_tests.js b/mock-ril/src/js/simulated_icc_tests.js
deleted file mode 100644
index ca685fc..0000000
--- a/mock-ril/src/js/simulated_icc_tests.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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.
- */
-
-// TODO: Add tests
diff --git a/mock-ril/src/js/simulated_radio.js b/mock-ril/src/js/simulated_radio.js
deleted file mode 100644
index 9153694..0000000
--- a/mock-ril/src/js/simulated_radio.js
+++ /dev/null
@@ -1,1269 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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.
- */
-
-/**
- * The Radio object contains a set of methods and objects to handle ril request
- * which is passed from simulatedRadioWorker queue. The global object initialize
- * an instance of Radio object by calling "new Radio". For each ril request,
- * rilDispatchTable gets searched and the corresponding method is called.
- * Extra requests are also defined to process unsolicited rerequests.
- *
- * The rilDispatchTable is an array indexed by RIL_REQUEST_* or REQUEST_UNSOL_*,
- * in which each request corresponds to a functions defined in the Radio object.
- * We need to pay attention when using "this" within those functions. When they are
- * called in "this.process" using
- * result = this.radioDispatchTable[req.reqNum])(req);
- * this scope of "this" within those functions are the radioDispatchTable, not the
- * object that "this.process" belongs to. Using "this." to access other
- * functions in the object may cause trouble.
- * To avoid that, the object is passed in when those functions are called as
- * shown in the following:
- * result = (this.radioDispatchTable[req.reqNum]).call(this, req);
- */
-
-/**
- * Set radio state
- */
-function setRadioState(newState) {
- newRadioState = newState;
- if (typeof newState == 'string') {
- newRadioState = globals[newState];
- if (typeof newRadioState == 'undefined') {
- throw('setRadioState: Unknow string: ' + newState);
- }
- }
- if ((newRadioState < RADIOSTATE_OFF) || (newRadioState > RADIOSTATE_NV_READY)) {
- throw('setRadioState: newRadioState: ' + newRadioState + ' is invalid');
- }
- gRadioState = newRadioState;
- sendRilUnsolicitedResponse(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED);
-}
-
-/**
- * Create a call.
- *
- * @return a RilCall
- */
-function RilCall(state, phoneNumber, callerName) {
- this.state = state;
- this.index = 0;
- this.toa = 0;
- this.isMpty = false;
- this.isMt = false;
- this.als = 0;
- this.isVoice = true;
- this.isVoicePrivacy = false;
- this.number = phoneNumber;
- this.numberPresentation = 0;
- this.name = callerName;
-}
-
-/**
- * Simulated Radio
- */
-function Radio() {
- var registrationState = '1';
- var lac = '0';
- var cid = '0';
- var radioTechnology = '3';
- var baseStationId = NULL_RESPONSE_STRING;
- var baseStationLatitude = NULL_RESPONSE_STRING;
- var baseStationLongitude = NULL_RESPONSE_STRING;
- var concurrentServices = NULL_RESPONSE_STRING;
- var systemId = NULL_RESPONSE_STRING;
- var networkId = NULL_RESPONSE_STRING;
- var roamingIndicator = NULL_RESPONSE_STRING;
- var prlActive = NULL_RESPONSE_STRING;
- var defaultRoamingIndicator = NULL_RESPONSE_STRING;
- var registrationDeniedReason = NULL_RESPONSE_STRING;
- var primaryScrambingCode = NULL_RESPONSE_STRING;
-
- var NETWORK_SELECTION_MODE_AUTOMATIC = 0;
- var NETWORK_SELECTION_MODE_MANUAL = 1;
- var networkSelectionMode = NETWORK_SELECTION_MODE_AUTOMATIC;
-
- var muteState = 0; // disable mute
-
- // Number of active calls in calls
- var numberActiveCalls = 0;
-
- // Maximum number of active calls
- var maxNumberActiveCalls = 7;
- var maxConnectionsPerCall = 5; // only 5 connections allowed per call
-
- // Flag to denote whether an incoming/waiting call is answered
- var incomingCallIsProcessed = false;
-
- // Call transition flag
- var callTransitionFlag = false; // default to auto-transition
-
- var lastCallFailCause = 0;
-
- // Array of "active" calls
- var calls = Array(maxNumberActiveCalls + 1);
-
- // The result returned by the request handlers
- var result = new Object();
-
- function GWSignalStrength() {
- this.signalStrength = 10; // 10 * 2 + (-113) = -93dBm, make it three bars
- this.bitErrorRate = 0;
- }
-
- function CDMASignalStrength() {
- this.dbm = -1;
- this.ecio = -1;
- }
-
- function EVDOSignalStrength() {
- this.dbm = -1;
- this.ecio = -1;
- this.signalNoiseRatio = 0;
- }
-
- function LTESignalStrength() {
- this.signalStrength = -1;
- this.rsrp = 0;
- this.rsrq = 0;
- this.rssnr = 0;
- this.cqi = 0;
- }
-
- var gwSignalStrength = new GWSignalStrength;
- var cdmaSignalStrength = new CDMASignalStrength();
- var evdoSignalStrength = new EVDOSignalStrength();
- var lteSignalStrength = new LTESignalStrength();
-
- /**
- * The the array of calls, this is a sparse
- * array and some elements maybe 'undefined'.
- *
- * @return Array of RilCall's
- */
- this.getCalls = function() {
- return calls;
- }
-
- /**
- * @return the RilCall at calls[index] or null if undefined.
- */
- this.getCall = function(index) {
- var c = null;
- try {
- c = calls[index];
- if (typeof c == 'undefined') {
- c = null;
- }
- } catch (err) {
- c = null;
- }
- return c;
- }
-
- /**
- * @return the first call that is in the given state
- */
- this.getCallIdByState = function(callState) {
- if ((callState < CALLSTATE_ACTIVE) || (callState > CALLSTATE_WAITING)) {
- return null;
- }
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- if (calls[i].state == callState) {
- return i;
- }
- }
- }
- return null;
- }
-
- /** Add an active call
- *
- * @return a RilCall or null if too many active calls.
- */
- this.addCall = function(state, phoneNumber, callerName) {
- print('Radio: addCall');
- var c = null;
- if (numberActiveCalls < maxNumberActiveCalls) {
- numberActiveCalls += 1;
- c = new RilCall(state, phoneNumber, callerName);
- // call index should fall in the closure of [1, 7]
- // Search for an "undefined" element in the array and insert the call
- for (var i = 1; i < (maxNumberActiveCalls + 1); i++) {
- print('Radio: addCall, i=' + i);
- if (typeof calls[i] == 'undefined') {
- print('Radio: addCall, calls[' + i + '] is undefined');
- c.index = i;
- calls[i] = c;
- break;
- }
- }
- this.printCalls(calls);
- }
- return c;
- }
-
- /**
- * Remove the call, does nothing if the call is undefined.
- *
- * @param index into calls to remove.
- * @return the call removed or null if did not exist
- */
- this.removeCall = function(index) {
- var c = null;
- if ((numberActiveCalls > 0)
- && (index < calls.length)
- && (typeof calls[index] != 'undefined')) {
- c = calls[index];
- delete calls[index];
- numberActiveCalls -= 1;
- if (numberActiveCalls == 0) {
- calls = new Array();
- }
- } else {
- c = null;
- }
- return c;
- }
-
- /**
- * Print the call
- *
- * @param c is the RilCall to print
- */
- this.printCall = function(c) {
- if ((c != null) && (typeof c != 'undefined')) {
- print('c[' + c.index + ']: index=' + c.index + ' state=' + c.state +
- ' number=' + c.number + ' name=' + c.name);
- }
- }
-
- /**
- * Print all the calls.
- *
- * @param callArray is an Array of RilCall's
- */
- this.printCalls = function(callArray) {
- if (typeof callArray == 'undefined') {
- callArray = calls;
- }
- print('callArray.length=' + callArray.length);
- for (var i = 0; i < callArray.length; i++) {
- if ((callArray[i] == null) || (typeof callArray[i] == 'undefined')) {
- print('c[' + i + ']: undefined');
- } else {
- this.printCall(callArray[i]);
- }
- }
- }
-
- /**
- * Count number of calls in the given state
- *
- * @param callState is the give state
- */
- this.countCallsInState = function(callState) {
- var count = 0;
- if ((callState < CALLSTATE_ACTIVE) || (callState > CALLSTATE_WAITING)) {
- // not a valid call state
- return null;
- }
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- if (calls[i].state == callState) {
- count++;
- }
- }
- }
- return count;
- }
-
- /**
- * Print signal strength
- */
- this.printSignalStrength = function() {
- print('rssi: ' + gwSignalStrength.signalStrength);
- print('bitErrorRate: ' + gwSignalStrength.bitErrorRate);
- print('cdmaDbm: ' + cdmaSignalStrength.dbm);
- print('cdmaEcio: ' + cdmaSignalStrength.ecio);
- print('evdoRssi: ' + evdoSignalStrength.dbm);
- print('evdoEcio: ' + evdoSignalStrength.ecio);
- print('evdoSnr: ' + evdoSignalStrength.signalNoiseRatio);
- print('lteRssi: ' + lteSignalStrength.signalStrength);
- print('lteRsrp: ' + lteSignalStrength.rsrp);
- print('lteRsrq: ' + lteSignalStrength.rsrq);
- print('lteRssnr: ' + lteSignalStrength.rssnr);
- print('lteCqi: ' + lteSignalStrength.cqi);
- }
-
- /**
- * set signal strength
- *
- * @param rssi and bitErrorRate are signal strength parameters for GSM
- * cdmaDbm, cdmaEcio, evdoRssi, evdoEcio, evdoSnr are parameters for CDMA & EVDO
- */
- this.setSignalStrength = function(rssi, bitErrorRate, cdmaDbm, cdmaEcio, evdoRssi,
- evdoEcio, evdoSnr, lteSigStrength, lteRsrp,
- lteRsrq, lteRssnr, lteCqi) {
- print('setSignalStrength E');
-
- if (rssi != 99) {
- if ((rssi < 0) || (rssi > 31)) {
- throw ('not a valid signal strength');
- }
- }
- // update signal strength
- gwSignalStrength.signalStrength = rssi;
- gwSignalStrength.bitErrorRate = bitErrorRate;
- cdmaSignalStrength.dbm = cdmaDbm;
- cdmaSignalStrength.ecio = cdmaEcio;
- evdoSignalStrength.dbm = evdoRssi;
- evdoSignalStrength.ecio = evdoEcio;
- evdoSignalStrength.signalNoiseRatio = evdoSnr;
- lteSignalStrength.signalStrength = lteSigStrength;
- lteSignalStrength.rsrp = lteRsrp;
- lteSignalStrength.rsrq = lteRsrq;
- lteSignalStrength.rssnr = lteRssnr;
- lteSignalStrength.cqi = lteCqi;
-
- // pack the signal strength into RspSignalStrength and send a unsolicited response
- var rsp = new Object();
-
- rsp.gwSignalstrength = gwSignalStrength;
- rsp.cdmSignalstrength = cdmaSignalStrength;
- rsp.evdoSignalstrength = evdoSignalStrength;
- rsp.lteSignalstrength = lteSignalStrength;
-
- var response = rilSchema[packageNameAndSeperator +
- 'RspSignalStrength'].serialize(rsp);
-
- sendRilUnsolicitedResponse(RIL_UNSOL_SIGNAL_STRENGTH, response);
-
- // send the unsolicited signal strength every 1 minute.
- simulatedRadioWorker.addDelayed(
- {'reqNum' : CMD_UNSOL_SIGNAL_STRENGTH}, 60000);
- print('setSignalStrength X');
- }
-
- /**
- * Handle RIL_REQUEST_GET_CURRENT_CALL
- *
- * @param req is the Request
- */
- this.rilRequestGetCurrentCalls = function(req) { // 9
- print('Radio: rilRequestGetCurrentCalls E');
- var rsp = new Object();
-
- // pack calls into rsp.calls
- rsp.calls = new Array();
- var i;
- var j;
- for (i = 0, j = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- rsp.calls[j++] = calls[i];
- }
- }
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspGetCurrentCalls'].serialize(rsp);
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_DIAL
- *
- * @param req is the Request
- */
- this.rilRequestDial = function(req) { // 10
- print('Radio: rilRequestDial E');
- var newCall = new Object();
- newCall = this.addCall(CALLSTATE_DIALING, req.data.address, '');
- if (newCall == null) {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- return result;
- }
- this.printCalls(calls);
-
- print('after add the call');
- // Set call state to dialing
- simulatedRadioWorker.add(
- {'reqNum' : CMD_CALL_STATE_CHANGE,
- 'callType' : OUTGOING,
- 'callIndex' : newCall.index,
- 'nextState' : CALLSTATE_DIALING});
- if (!callTransitionFlag) {
- // for auto transition
- // Update call state to alerting after 1 second
- simulatedRadioWorker.addDelayed(
- {'reqNum' : CMD_CALL_STATE_CHANGE,
- 'callType' : OUTGOING,
- 'callIndex' : newCall.index,
- 'nextState' : CALLSTATE_ALERTING}, 1000);
- // Update call state to active after 2 seconds
- simulatedRadioWorker.addDelayed(
- {'reqNum' : CMD_CALL_STATE_CHANGE,
- 'callType' : OUTGOING,
- 'callIndex': newCall.index,
- 'nextState' : CALLSTATE_ACTIVE}, 2000);
- }
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_HANG_UP
- *
- * @param req is the Request
- */
- this.rilRequestHangUp = function(req) { // 12
- print('Radio: rilRequestHangUp data.connection_index=' + req.data.connectionIndex);
- if (this.removeCall(req.data.connectionIndex) == null) {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- print('no connection to hangup');
- }
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND
- * Hang up waiting or held
- *
- * @param req is the Request
- */
- this.rilRequestHangupWaitingOrBackground = function(req) { // 13
- print('Radio: rilRequestHangupWaitingOrBackground');
- if (numberActiveCalls <= 0) {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- } else {
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- switch (calls[i].state) {
- case CALLSTATE_HOLDING:
- case CALLSTATE_WAITING:
- case CALLSTATE_INCOMING:
- this.removeCall(i);
- incomingCallIsProcessed = true;
- break;
- default:
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- break;
- }
- this.printCalls(calls);
- if(result.rilErrCode == RIL_E_GENERIC_FAILURE) {
- return result;
- }
- } // end of processing call[i]
- } // end of for
- }
- // Send out RIL_UNSOL_CALL_STATE_CHANGED after the request is returned
- simulatedRadioWorker.add(
- {'reqNum' : CMD_UNSOL_CALL_STATE_CHANGED});
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND
- * release all active calls (if any exist) and resume held or waiting calls.
- * @param req is the Request
- */
- this.rilRequestHangUpForegroundResumeBackground = function(req) { //14
- print('Radio: rilRequestHangUpForegroundResumeBackground');
- if (numberActiveCalls <= 0) {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- } else {
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- switch (calls[i].state) {
- case CALLSTATE_ACTIVE:
- this.removeCall(i);
- break;
- case CALLSTATE_HOLDING:
- case CALLSTATE_WAITING:
- calls[i].state = CALLSTATE_ACTIVE;
- break;
- default:
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- break;
- }
- this.printCalls(calls);
- if(result.rilErrCode == RIL_E_GENERIC_FAILURE) {
- return result;
- }
- } // end of processing call[i]
- }
- }
- // Send out RIL_UNSOL_CALL_STATE_CHANGED after the request is returned
- simulatedRadioWorker.add(
- {'reqNum' : CMD_UNSOL_CALL_STATE_CHANGED});
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE
- *
- * BEFORE AFTER
- * Call 1 Call 2 Call 1 Call 2
- * ACTIVE HOLDING HOLDING ACTIVE
- * ACTIVE WAITING HOLDING ACTIVE
- * HOLDING WAITING HOLDING ACTIVE
- * ACTIVE IDLE HOLDING IDLE
- * IDLE IDLE IDLE IDLE
- *
- * @param req is the Request
- */
- this.rilRequestSwitchWaitingOrHoldingAndActive = function(req) { // 15
- print('Radio: rilRequestSwitchWaitingOrHoldingAndActive');
- print('Radio: lastReq = ' + lastReq);
- print('Radio: req.reqNum = ' + req.reqNum);
- if (lastReq == req.reqNum) {
- print('Radio: called twice');
- return result;
- }
-
- if (numberActiveCalls <= 0) {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- } else {
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- switch (calls[i].state) {
- case CALLSTATE_ACTIVE:
- calls[i].state = CALLSTATE_HOLDING;
- break;
- case CALLSTATE_HOLDING:
- case CALLSTATE_WAITING:
- calls[i].state = CALLSTATE_ACTIVE;
- break;
- default:
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- break;
- }
- this.printCalls(calls);
- if(result.rilErrCode == RIL_E_GENERIC_FAILURE) {
- return result;
- }
- } // end of processing call[i]
- } // end of for
- }
- // Send out RIL_UNSOL_CALL_STATE_CHANGED after the request is returned
- simulatedRadioWorker.add(
- {'reqNum' : CMD_UNSOL_CALL_STATE_CHANGED});
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_CONFERENCE
- * Conference holding and active
- *
- * @param req is the Request
- */
- this.rilRequestConference = function(req) { // 16
- print('Radio: rilRequestConference E');
- if ((numberActiveCalls <= 0) || (numberActiveCalls > maxConnectionsPerCall)) {
- // The maximum number of connections within a call is 5
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- return result;
- } else {
- var numCallsInBadState = 0;
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- if ((calls[i].state != CALLSTATE_ACTIVE) &&
- (calls[i].state != CALLSTATE_HOLDING)) {
- numCallsInBadState++;
- }
- }
- }
-
- // if there are calls not in ACITVE or HOLDING state, return error
- if (numCallsInBadState > 0) {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- return result;
- } else { // conference ACTIVE and HOLDING calls
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- switch (calls[i].state) {
- case CALLSTATE_ACTIVE:
- break;
- case CALLSTATE_HOLDING:
- calls[i].state = CALLSTATE_ACTIVE;
- break;
- default:
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- break;
- }
- }
- this.printCalls(calls);
- if(result.rilErrCode == RIL_E_GENERIC_FAILURE) {
- return result;
- }
- }
- }
- }
-
- // Only if conferencing is successful,
- // Send out RIL_UNSOL_CALL_STATE_CHANGED after the request is returned
- simulatedRadioWorker.add(
- {'reqNum' : CMD_UNSOL_CALL_STATE_CHANGED});
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_LAST_CALL_FAIL_CAUSE
- *
- * @param req is the request
- */
- this.rilRequestLastCallFailCause = function(req) {
- print('Radio: rilRequestLastCallFailCause E');
-
- var rsp = new Object();
- rsp.integers = new Array();
- rsp.integers[0] = lastCallFailCause;
-
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspIntegers'].serialize(rsp);
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_SIGNAL_STRENGTH
- *
- * @param req is the Request
- */
- this.rilRequestSignalStrength = function(req) { // 19
- print('Radio: rilRequestSignalStrength E');
- var rsp = new Object();
-
- // pack the signal strength into RspSignalStrength
- rsp.gwSignalstrength = gwSignalStrength;
- rsp.cdmaSignalstrength = cdmaSignalStrength;
- rsp.evdoSignalstrength = evdoSignalStrength;
-
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspSignalStrength'].serialize(rsp);
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_VOICE_REGISTRATION_STATE
- *
- * @param req is the Request
- */
- this.rilRequestVoiceRegistrationState = function(req) { // 20
- print('Radio: rilRequestVoiceRegistrationState');
-
- var rsp = new Object();
- rsp.strings = Array();
- rsp.strings[0] = registrationState;
- rsp.strings[1] = lac;
- rsp.strings[2] = cid;
- rsp.strings[3] = radioTechnology;
- rsp.strings[4] = baseStationId;
- rsp.strings[5] = baseStationLatitude;
- rsp.strings[6] = baseStationLongitude;
- rsp.strings[7] = concurrentServices;
- rsp.strings[8] = systemId;
- rsp.strings[9] = networkId;
- rsp.strings[10] = roamingIndicator;
- rsp.strings[11] = prlActive;
- rsp.strings[12] = defaultRoamingIndicator;
- rsp.strings[13] = registrationDeniedReason;
- rsp.strings[14] = primaryScrambingCode;
-
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspStrings'].serialize(rsp);
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_DATA_REGISTRATION_STATE
- *
- * @param req is the Request
- */
- this.rilRequestDataRegistrationState = function(req) { // 21
- print('Radio: rilRequestDataRegistrationState');
-
- var rsp = new Object();
- rsp.strings = Array();
- rsp.strings[0] = registrationState;
- rsp.strings[1] = lac;
- rsp.strings[2] = cid;
- rsp.strings[3] = radioTechnology;
-
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspStrings'].serialize(rsp);
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_ANSWER
- *
- * @param req is the Request
- */
- this.rilRequestAnswer = function(req) { // 40
- print('Radio: rilRequestAnswer');
-
- if (numberActiveCalls != 1) {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- return result;
- } else {
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- if (calls[i].state == CALLSTATE_INCOMING) {
- calls[i].state = CALLSTATE_ACTIVE;
- break;
- } else {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- this.removeCall(i);
- return result;
- }
- } // end of processing call[i]
- } // end of for
- }
- incomingCallIsProcessed = true;
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE
- *
- * @param req is the Request
- */
- this.rilRequestQueryNeworkSelectionMode = function(req) { // 45
- print('Radio: rilRequestQueryNeworkSelectionMode');
-
- var rsp = new Object();
- rsp.integers = Array();
- rsp.integers[0] = networkSelectionMode;
-
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspIntegers'].serialize(rsp);
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC
- *
- * @param req is the Request
- */
- this.rilRequestSetNeworkSelectionAutomatic = function(req) { // 46
- print('Radio: rilRequestSetNeworkSelectionAutomatic');
-
- networkSelectionMode = NETWORK_SELECTION_MODE_AUTOMATIC;
-
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_BASE_BAND_VERSION
- *
- * @param req is the Request
- */
- this.rilRequestBaseBandVersion = function(req) { // 51
- print('Radio: rilRequestBaseBandVersion');
- var rsp = new Object();
- rsp.strings = Array();
- rsp.strings[0] = gBaseBandVersion;
-
- result.responseProtobuf = rilSchema[packageNameAndSeperator +
- 'RspStrings'].serialize(rsp);
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_SEPRATE_CONNECTION
- * Separate a party from a multiparty call placing the multiparty call
- * (less the specified party) on hold and leaving the specified party
- * as the only other member of the current (active) call
- *
- * See TS 22.084 1.3.8.2 (iii)
- *
- * @param req is the Request
- */
- this.rilReqestSeparateConnection = function(req) { // 52
- print('Radio: rilReqestSeparateConnection');
- var index = req.data.index;
-
- if (numberActiveCalls <= 0) {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- return result;
- } else {
- // get the connection to separate
- var separateConn = this.getCall(req.data.index);
- if (separateConn == null) {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- return result;
- } else {
- if (separateConn.state != CALLSTATE_ACTIVE) {
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- return result;
- }
- // Put all other connections in hold.
- for (var i = 0; i < calls.length; i++) {
- if (index != i) {
- // put all the active call to hold
- if (typeof calls[i] != 'undefined') {
- switch (calls[i].state) {
- case CALLSTATE_ACTIVE:
- calls[i].state = CALLSTATE_HOLDING;
- break;
- default:
- result.rilErrCode = RIL_E_GENERIC_FAILURE;
- break;
- }
- this.printCalls(calls);
- if(result.rilErrCode == RIL_E_GENERIC_FAILURE) {
- return result;
- }
- } // end of processing call[i]
- }
- } // end of for
- }
- }
-
- // Send out RIL_UNSOL_CALL_STATE_CHANGED after the request is returned
- simulatedRadioWorker.add(
- {'reqNum' : CMD_UNSOL_CALL_STATE_CHANGED});
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_SET_MUTE
- */
- this.rilRequestSetMute = function(req) { // 53
- print('Radio: rilRequestSetMute: req.data.state=' + req.data.state);
- muteState = req.data.state;
- if (gRadioState == RADIOSTATE_UNAVAILABLE) {
- result.rilErrCode = RIL_E_RADIO_NOT_AVAILABLE;
- }
- return result;
- }
-
- /**
- * Handle RIL_REQUEST_SCREEN_STATE
- *
- * @param req is the Request
- */
- this.rilRequestScreenState = function(req) { // 61
- print('Radio: rilRequestScreenState: req.data.state=' + req.data.state);
- screenState = req.data.state;
- return result;
- }
-
- /**
- * Delay test
- */
- this.cmdDelayTest = function(req) { // 2000
- print('cmdDelayTest: req.hello=' + req.hello);
- result.sendResponse = false;
- return result;
- }
-
- /**
- * Delay for RIL_UNSOL_SIGNAL_STRENGTH
- * TODO: Simulate signal strength changes:
- * Method 1: provide an array for signal strength, and send the unsolicited
- * reponse periodically (the period can also be simulated)
- * Method 2: Simulate signal strength randomly (within a certain range) and
- * send the response periodically.
- */
- this.cmdUnsolSignalStrength = function(req) { // 2001
- print('cmdUnsolSignalStrength: req.reqNum=' + req.reqNum);
- var rsp = new Object();
-
- // pack the signal strength into RspSignalStrength
- rsp.gwSignalstrength = gwSignalStrength;
- rsp.cdmaSignalstrength = cdmaSignalStrength;
- rsp.evdoSignalstrength = evdoSignalStrength;
-
- response = rilSchema[packageNameAndSeperator +
- 'RspSignalStrength'].serialize(rsp);
-
- // upldate signal strength
- sendRilUnsolicitedResponse(RIL_UNSOL_SIGNAL_STRENGTH, response);
-
- // Send the unsolicited signal strength every 1 minute.
- simulatedRadioWorker.addDelayed(
- {'reqNum' : CMD_UNSOL_SIGNAL_STRENGTH}, 60000);
-
- // this is not a request, no response is needed
- result.sendResponse = false;
- return result;
- }
-
- /**
- * Send RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED
- */
- this.cmdUnsolCallStateChanged = function(req) { // 2002
- print('cmdUnsolCallStateChanged: req.reqNum=' + req.reqNum);
- sendRilUnsolicitedResponse(RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED);
- result.sendResponse = false;
- return result;
- }
-
- /**
- * Simulate call state change
- */
- this.cmdCallStateChange = function(req) { // 2003
- print('cmdCallStateChange: req.reqNum=' + req.reqNum);
- print('cmdCallStateChange: req.callType=' + req.callType);
- print('cmdCallStateChange: req.callIndex=' + req.callIndex);
- print('cmdCallStateChange: req.nextState=' + req.nextState);
-
- // if it is an outgoing call, update the call state of the call
- // Send out call state changed flag
- var curCall = this.getCall(req.callIndex);
- this.printCall(curCall);
-
- if (curCall != null) {
- curCall.state = req.nextState;
- } else {
- this.removeCall(req.callIndex);
- }
-
- // TODO: if it is an incoming call, update the call state of the call
- // Send out call state change flag
- // Send out RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED
- simulatedRadioWorker.add(
- {'reqNum' : CMD_UNSOL_CALL_STATE_CHANGED});
- result.sendResponse = false;
- return result;
- }
-
- /**
- * send UNSOL_CALL_STATE_CHANGED and UNSOL_CALL_RING
- */
- this.cmdUnsolCallRing = function(req) { // 2004
- print('cmdUnsolCallRing: req.reqNum=' + req.reqNum);
- if(!incomingCallIsProcessed) {
- sendRilUnsolicitedResponse(RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED);
- sendRilUnsolicitedResponse(RIL_UNSOL_CALL_RING);
-
- // Send the next alert in 3 seconds. [refer to ril.h definition]
- simulatedRadioWorker.addDelayed(
- {'reqNum' : CMD_UNSOL_CALL_RING}, 3000);
- }
- result.sendResponse = false;
- return result;
- }
-
- /**
- * Create an incoming call for the giving number
- * return CTRL_STATUS_ERR if there is already a call in any of the states of
- * dialing, alerting, incoming, waiting [TS 22 030 6.5] , else
- * return CTRL_STATUS_OK and update the call state
- */
- this.ctrlServerCmdStartInComingCall = function(req) { // 1001
- print('ctrlServerCmdStartInComingCall: req.reqNum:' + req.reqNum);
- print('ctrlServerCmdStartInComingCall: req.data.phonenumber:' + req.data.phoneNumber);
-
- var phoneNumber = req.data.phoneNumber;
- var state;
-
- if (numberActiveCalls <= 0) {
- // If there is no connection in use, the call state is INCOMING
- state = CALLSTATE_INCOMING;
- } else {
- // If there is call in any of the states of dialing, alerting, incoming
- // waiting, this MT call can not be set
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- if ( (calls[i].state == CALLSTATE_DIALING) ||
- (calls[i].state == CALLSTATE_ALERTING) ||
- (calls[i].state == CALLSTATE_INCOMING) ||
- (calls[i].state == CALLSTATE_WAITING))
- {
- result.rilErrCode = CTRL_STATUS_ERR;
- return result;
- }
- }
- }
- // If the incoming call is a second call, the state is WAITING
- state = CALLSTATE_WAITING;
- }
-
- // Add call to the call array
- this.addCall(state, phoneNumber, '');
-
- // set the incomingCallIsProcessed flag to be false
- incomingCallIsProcessed = false;
-
- simulatedRadioWorker.add(
- {'reqNum' : CMD_UNSOL_CALL_RING});
-
- result.rilErrCode = CTRL_STATUS_OK;
- return result;
- }
-
- /**
- * Handle control command CTRL_CMD_HANGUP_CONN_REMOTE
- * hangup the connection for the given failure cause
- *
- *@param req is the control request
- */
- this.ctrlServerCmdHangupConnRemote = function(req) { // 1002
- print('ctrlServerCmdHangupConnRemote: req.data.connectionId=' + req.data.connectionId +
- ' req.data.callFailCause' + req.data.callFailCause);
-
- var connection = req.data.connectionId;
- var failureCause = req.data.callFailCause;
-
- this.printCalls(calls);
- var hangupCall = this.removeCall(connection);
- if (hangupCall == null) {
- print('ctrlServerCmdHangupConnRemote: connection id is required.');
- result.rilErrCode = CTRL_STATUS_ERR;
- return result;
- } else {
- // for incoming call, stop sending call ring
- if ((hangupCall.state == CALLSTATE_INCOMING) ||
- (hangupCall.state == CALLSTATE_WAITING)) {
- incomingCallIsProcessed = true;
- }
- }
- this.printCalls(calls);
- lastCallFailCause = failureCause;
-
- // send out call state changed response
- simulatedRadioWorker.add(
- {'reqNum' : CMD_UNSOL_CALL_STATE_CHANGED});
-
- result.rilErrCode = CTRL_STATUS_OK;
- return result;
- }
-
- /**
- * Set call transition flag
- */
- this.ctrlServerCmdSetCallTransitionFlag = function(req) { // 1003
- print('ctrlServerCmdSetCallTransitionFlag: flag=' + req.data.flag);
-
- callTransitionFlag = req.data.flag;
- result.rilErrCode = CTRL_STATUS_OK;
- return result;
- }
-
- /**
- * Set the dialing call to alert
- */
- this.ctrlServerCmdSetCallAlert = function(req) { // 1004
- print('ctrlServerCmdSetCallAlert: E');
-
- if (callTransitionFlag == false) {
- print('ctrlServerCmdSetCallAlert: need to set the flag first');
- result.rilErrCode = CTRL_STATUS_ERR;
- return result;
- }
- if (numberActiveCalls <= 0) {
- print('ctrlServerCmdSetCallAlert: no active calls');
- result.rilErrCode = CTRL_STATUS_ERR;
- return result;
- }
- var dialingCalls = this.countCallsInState(CALLSTATE_DIALING);
- var index = this.getCallIdByState(CALLSTATE_DIALING);
- if ((dialingCalls == 1) && (index != null)) {
- calls[index].state = CALLSTATE_ALERTING;
- } else {
- // if there 0 or more than one call in dialing state, return error
- print('ctrlServerCmdSetCallAlert: no valid calls in dialing state');
- result.rilErrCode = CTRL_STATUS_ERR;
- return result;
- }
- // send unsolicited call state change response
- simulatedRadioWorker.add(
- {'reqNum' : CMD_UNSOL_CALL_STATE_CHANGED});
-
- result.rilErrCode = CTRL_STATUS_OK;
- return result;
- }
-
- /**
- * Set the alserting call to active
- */
- this.ctrlServerCmdSetCallActive = function(req) { // 1005
- print('ctrlServerCmdSetCallActive: E');
-
- if (callTransitionFlag == false) {
- print('ctrlServerCmdSetCallActive: need to set the flag firt');
- result.rilErrCode = CTRL_STATUS_ERR;
- return result;
- }
- if (numberActiveCalls <= 0) {
- print('ctrlServerCmdSetCallActive: no active calls');
- result.rilErrCode = CTRL_STATUS_ERR;
- return result;
- }
- var alertingCalls = this.countCallsInState(CALLSTATE_ALERTING);
- var index = this.getCallIdByState(CALLSTATE_ALERTING);
- if ((alertingCalls == 1) && (index != null)) {
- calls[index].state = CALLSTATE_ACTIVE;
- } else {
- print('ctrlServerCmdSetCallActive: no valid calls in alert state');
- result.rilErrCode = CTRL_STATUS_ERR;
- return result;
- }
- // send out unsolicited call state change response
- simulatedRadioWorker.add(
- {'reqNum' : CMD_UNSOL_CALL_STATE_CHANGED});
-
- result.rilErrCode = CTRL_STATUS_OK;
- return result;
- }
-
- /**
- * Add a dialing call
- */
- this.ctrlServerCmdAddDialingCall = function(req) { // 1006
- print('ctrlServerCmdAddDialingCall: E');
-
- var phoneNumber = req.data.phoneNumber;
- var dialingCalls = this.countCallsInState(CALLSTATE_DIALING);
- if (dialingCalls == 0) {
- this.addCall(CALLSTATE_DIALING, phoneNumber, '');
- result.rilErrCode = CTRL_STATUS_OK;
- } else {
- print('ctrlServerCmdAddDialingCall: add dialing call failed');
- result.rilErrCode = CTRL_STATUS_ERR;
- }
- return result;
- }
-
- /**
- * Process the request by dispatching to the request handlers
- */
- this.process = function(req) {
- try {
- print('Radio E: req.reqNum=' + req.reqNum + ' req.token=' + req.token);
-
- // Assume the result will be true, successful and nothing to return
- result.sendResponse = true;
- result.rilErrCode = RIL_E_SUCCESS;
- result.responseProtobuf = emptyProtobuf;
-
- try {
- // Pass "this" object to each ril request call such that
- // they have the same scope
- result = (this.radioDispatchTable[req.reqNum]).call(this, req);
- } catch (err) {
- print('Radio:process err = ' + err);
- print('Radio: Unknown reqNum=' + req.reqNum);
- result.rilErrCode = RIL_E_REQUEST_NOT_SUPPORTED;
- }
-
- if (req.reqNum < 200) {
- lastReq = req.reqNum;
- }
- if (result.sendResponse) {
- if (isCtrlServerDispatchCommand(req.reqNum)) {
- //print('Command ' + req.reqNum + ' is a control server command');
- sendCtrlRequestComplete(result.rilErrCode, req.reqNum,
- req.token, result.responseProtobuf);
- } else {
- //print('Request ' + req.reqNum + ' is a ril request');
- sendRilRequestComplete(result.rilErrCode, req.reqNum,
- req.token, result.responseProtobuf);
- }
- }
- //print('Radio X: req.reqNum=' + req.reqNum + ' req.token=' + req.token);
- } catch (err) {
- print('Radio: Exception req.reqNum=' +
- req.reqNum + ' req.token=' + req.token + ' err=' + err);
- }
- }
-
- /**
- * Construct the simulated radio
- */
- print('Radio: constructor E');
- this.radioDispatchTable = new Array();
- this.radioDispatchTable[RIL_REQUEST_GET_CURRENT_CALLS] = // 9
- this.rilRequestGetCurrentCalls;
- this.radioDispatchTable[RIL_REQUEST_DIAL] = // 10
- this.rilRequestDial;
- this.radioDispatchTable[RIL_REQUEST_HANGUP] = // 12
- this.rilRequestHangUp;
- this.radioDispatchTable[RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND] = // 13
- this.rilRequestHangupWaitingOrBackground;
- this.radioDispatchTable[RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND] = // 14
- this.rilRequestHangUpForegroundResumeBackground;
- this.radioDispatchTable[RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE] = // 15
- this.rilRequestSwitchWaitingOrHoldingAndActive;
- this.radioDispatchTable[RIL_REQUEST_CONFERENCE] = // 16
- this.rilRequestConference;
- this.radioDispatchTable[RIL_REQUEST_LAST_CALL_FAIL_CAUSE] = // 18
- this.rilRequestLastCallFailCause;
- this.radioDispatchTable[RIL_REQUEST_SIGNAL_STRENGTH] = // 19
- this.rilRequestSignalStrength;
- this.radioDispatchTable[RIL_REQUEST_VOICE_REGISTRATION_STATE] = // 20
- this.rilRequestVoiceRegistrationState;
- this.radioDispatchTable[RIL_REQUEST_DATA_REGISTRATION_STATE] = // 21
- this.rilRequestDataRegistrationState;
- this.radioDispatchTable[RIL_REQUEST_ANSWER] = // 40
- this.rilRequestAnswer;
- this.radioDispatchTable[RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE] = // 45
- this.rilRequestQueryNeworkSelectionMode;
- this.radioDispatchTable[RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC] = // 46
- this.rilRequestSetNeworkSelectionAutomatic;
- this.radioDispatchTable[RIL_REQUEST_BASEBAND_VERSION] = // 51
- this.rilRequestBaseBandVersion;
- this.radioDispatchTable[RIL_REQUEST_SEPARATE_CONNECTION] = // 52
- this.rilReqestSeparateConnection;
- this.radioDispatchTable[RIL_REQUEST_SET_MUTE] = // 53
- this.rilRequestSetMute;
- this.radioDispatchTable[RIL_REQUEST_SCREEN_STATE] = // 61
- this.rilRequestScreenState;
-
- this.radioDispatchTable[CTRL_CMD_SET_MT_CALL] = //1001
- this.ctrlServerCmdStartInComingCall;
- this.radioDispatchTable[CTRL_CMD_HANGUP_CONN_REMOTE] = //1002
- this.ctrlServerCmdHangupConnRemote;
- this.radioDispatchTable[CTRL_CMD_SET_CALL_TRANSITION_FLAG] = //1003
- this.ctrlServerCmdSetCallTransitionFlag;
- this.radioDispatchTable[CTRL_CMD_SET_CALL_ALERT] = // 1004
- this.ctrlServerCmdSetCallAlert;
- this.radioDispatchTable[CTRL_CMD_SET_CALL_ACTIVE] = // 1005
- this.ctrlServerCmdSetCallActive;
- this.radioDispatchTable[CTRL_CMD_ADD_DIALING_CALL] = // 1006
- this.ctrlServerCmdAddDialingCall;
-
- this.radioDispatchTable[CMD_DELAY_TEST] = // 2000
- this.cmdDelayTest;
- this.radioDispatchTable[CMD_UNSOL_SIGNAL_STRENGTH] = // 2001
- this.cmdUnsolSignalStrength;
- this.radioDispatchTable[CMD_UNSOL_CALL_STATE_CHANGED] = // 2002
- this.cmdUnsolCallStateChanged;
- this.radioDispatchTable[CMD_CALL_STATE_CHANGE] = //2003
- this.cmdCallStateChange;
- this.radioDispatchTable[CMD_UNSOL_CALL_RING] = //2004
- this.cmdUnsolCallRing;
-
- print('Radio: constructor X');
-}
-
-// The simulated radio instance and its associated Worker
-var simulatedRadio = new Radio();
-var simulatedRadioWorker = new Worker(function (req) {
- simulatedRadio.process(req);
-});
-simulatedRadioWorker.run();
-
-// TODO: this is a workaround for bug http://b/issue?id=3001613
-// When adding a new all, two RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE
-// will be sent from the framework.
-var lastReq = 0;
-
-/**
- * Optional tests
- */
-if (false) {
- include("simulated_radio_tests.js");
-}
diff --git a/mock-ril/src/js/simulated_radio_tests.js b/mock-ril/src/js/simulated_radio_tests.js
deleted file mode 100644
index 497767b..0000000
--- a/mock-ril/src/js/simulated_radio_tests.js
+++ /dev/null
@@ -1,425 +0,0 @@
-/**
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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.
- */
-
-/**
- * TODO:update tests in the format of test incoming call
- * Have a global counter to count passes and failures
- */
-/**
- * A test to test set signal strength
- */
-if (false) {
- function testSetSignalStrength() {
- print('testSetSignalStrength E:');
- simulatedRadio.printSignalStrength();
- try {
- simulatedRadio.setSignalStrength(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
- } catch (err) {
- print('test failed');
- }
- simulatedRadio.printSignalStrength();
- try {
- simulatedRadio.setSignalStrength(60, 30, 29 , 28, 27, 26, 25, 24, 23, 22, 21, 20);
- } catch (err) {
- print('test success: ' + err);
- }
- simulatedRadio.printSignalStrength();
- }
- testSetSignalStrength();
-}
-
-/**
- * TODO: A test for RIL_REQUEST_GET_CURRENT_CALLS,
- * remove when satisfied all is well.
- */
-if (false) {
- var calls = simulatedRadio.getCalls();
-
- function testCalls() {
- print('testCalls E:');
- var c0 = simulatedRadio.addCall(CALLSTATE_ACTIVE, '16502859848', 'w');
- simulatedRadio.printCalls();
- var c1 = simulatedRadio.addCall(CALLSTATE_ACTIVE, '16502583456', 'm');
- simulatedRadio.printCalls();
- var c2 = simulatedRadio.addCall(CALLSTATE_ACTIVE, '16502345678', 'x');
- simulatedRadio.printCalls();
- var c3 = simulatedRadio.addCall(CALLSTATE_ACTIVE, '16502349876', 'y');
- simulatedRadio.printCalls();
-
- simulatedRadio.removeCall(c0.index);
- simulatedRadio.printCalls();
- simulatedRadio.removeCall(c1.index);
- simulatedRadio.printCalls();
- simulatedRadio.removeCall(c2.index);
- simulatedRadio.printCalls();
-
- result = simulatedRadio.rilRequestGetCurrentCalls();
- newCalls = rilSchema[packageNameAndSeperator +
- 'RspGetCurrentCalls'].parse(result.responseProtobuf);
- simulatedRadio.printCalls(newCalls.calls);
-
- // Set to false to test RIL_REQUEST_GET_CURRENT_CALLS as there will
- // be on call still active on the first RIL_REQUEST_GET_CURRENT_CALLS
- // request.
- if (false) {
- simulatedRadio.removeCall(c3.index);
- simulatedRadio.printCalls();
- }
- print('testCalls X:');
- }
-
- testCalls();
-}
-
-/**
- * A test for creating incoming call
- */
-if (false) {
- /* Only one incoming call is in the call list */
- function verifyIncomingCall() {
- var calls = simulatedRadio.getCalls();
- var numIncomingCalls = 0;
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- if (calls[i].state == CALLSTATE_INCOMING) {
- numIncomingCalls++;
- }
- }
- }
- return (numIncomingCalls == 1);
- }
-
- function testStartIncomingCall() {
- print('testCreateIncomingCall E:');
-
- var req = new Object();
- req.reqNum = CTRL_CMD_SET_MT_CALL;
- req.data = new Object();
- req.data.phoneNumber = '6502249208';
-
- var numberTestPass = 0;
- var numberTestFail = 0;
-
- // case 1: incoming call is the only active call
- var result = new Object();
- result = simulatedRadio.ctrlServerCmdStartInComingCall(req);
- if ( (result.rilErrCode == CTRL_STATUS_OK) && verifyIncomingCall()) {
- numberTestPass++;
- } else {
- numberTestFail++;
- print('testStartIncomingCall: TEST CASE 1 FAIL');
- }
-
- // case 2: one incoming call, add another incoming call will fail
- req.data.phoneNumber = '6502223456';
- result = simulatedRadio.ctrlServerCmdStartInComingCall(req);
- if ((result.rilErrCode == CTRL_STATUS_ERR) && verifyIncomingCall()) {
- numberTestPass++;
- } else {
- numberTestFail++;
- print('testStartIncomingCall: TEST CASE 2 FAIL');
- }
-
- // case 3: one dialing call, add another incoming call will fail
- // Make the first call in dialing state
- var calls = simulatedRadio.getCalls();
- for (var i = 0; i < calls.length; i++) {
- if (typeof calls[i] != 'undefined') {
- if (calls[i].state == CALLSTATE_INCOMING) {
- calls[i].state = CALLSTATE_DIALING;
- break;
- }
- }
- }
- result = simulatedRadio.ctrlServerCmdStartInComingCall(req);
- if (result.rilErrCode == CTRL_STATUS_ERR) {
- numberTestPass++;
- } else {
- numberTestFail++;
- print('testStartIncomingCall: TEST CASE 3 FAIL');
- }
-
- // case 4: one dialing call, adding another incoming call will fail
- calls[i].state = CALLSTATE_ALERTING;
- result = simulatedRadio.ctrlServerCmdStartInComingCall(req);
- if (result.rilErrCode == CTRL_STATUS_ERR) {
- numberTestPass++;
- } else {
- numberTestFail++;
- print('testStartIncomingCall: TEST CASE 4 FAIL');
- }
-
- // case 5: one active call, adding another incoming call will succeed
- calls[i].state = CALLSTATE_ACTIVE;
- result = simulatedRadio.ctrlServerCmdStartInComingCall(req);
- if (result.rilErrCode == CTRL_STATUS_OK) {
- numberTestPass++;
- } else {
- numberTestFail++;
- print('testStartIncomingCall: TEST CASE 5 FAIL');
- }
-
- print('*************TEST RESULT ****************');
- print('Number of Test Passed: ' + numberTestPass);
- print('Number of Test Failed: ' + numberTestFail);
- print('************ End **********************');
- // after the test, remove any calls
- for (i = 0; i < calls.length; i++) {
- simulatedRadio.removeCall(i);
- }
- print('testStartIncomingCall X:');
- }
-
- testStartIncomingCall();
-}
-
-/**
- * A test for RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND
- */
-if (false) {
- var calls = simulatedRadio.getCalls();
-
- function testHangUpForegroundResumeBackground() {
- print('testHangUpForegroundResumeBackground E:');
- var testOutput = false;
- for (var state = CALLSTATE_ACTIVE; state <= CALLSTATE_WAITING; state++) {
- var c0 = simulatedRadio.addCall(state, '16502849230', 'smith');
- var req = new Object();
- req.reqNum = RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND;
- var testResult = simulatedRadio.rilRequestHangUpForegroundResumeBackground(req);
- if (state == CALLSTATE_ACTIVE) {
- var testCalls = simulatedRadio.getCalls();
- if (testCalls.length == 0) {
- testOutput = true;
- } else {
- testOutput = false;
- }
- } else if (state == CALLSTATE_WAITING) {
- if (c0.state == CALLSTATE_ACTIVE) {
- testOutput = true;
- } else {
- testOutput = false;
- }
- } else if (state == CALLSTATE_HOLDING) {
- if (c0.state == CALLSTATE_ACTIVE) {
- testOutput = true;
- } else {
- testOutput = false;
- }
- } else {
- if (testResult.rilErrCode == RIL_E_GENERIC_FAILURE) {
- testOutput = true;
- } else {
- testOutput = false;
- }
- }
- if (testOutput == true) {
- print('testHangUpForegroundResumeBackground, call ' + state + ' PASS \n');
- } else {
- print('testHangUpForegroundResumeBackground, call ' + state + ' FAIL \n');
- }
- simulatedRadio.removeCall(c0.index);
- simulatedRadio.printCalls();
- }
- }
-
- testHangUpForegroundResumeBackground();
-}
-
-/**
- * Test RIL_REQUEST_CONFERENCE
- */
-if(false) {
- var calls = simulatedRadio.getCalls();
-
- function testConference() {
- print('testConference E');
-
- // test case 1: one holding, one dialing
- var c0 = simulatedRadio.addCall(CALLSTATE_HOLDING, '16502859848', 'w');
- simulatedRadio.printCalls();
- var c1 = simulatedRadio.addCall(CALLSTATE_DIALING, '16502583456', 'm');
- simulatedRadio.printCalls();
-
- var req = new Object();
- req.reqNum = RIL_REQUEST_CONFERENCE;
- var testResult = new Object();
- testResult.rilErrCode = RIL_E_SUCCESS;
- testResult = simulatedRadio.rilRequestConference(req);
- if (testResult.rilErrCode == RIL_E_GENERIC_FAILURE) {
- print('testConference: holding & dialing: pass');
- } else {
- print('testConference: holding & dialing: fail');
- }
-
- // test case 2: one holding, one alerting
- c1.state = CALLSTATE_ALERTING;
- testResult.rilErrCode = RIL_E_SUCCESS;
- testResult = simulatedRadio.rilRequestConference(req);
- if (testResult.rilErrCode == RIL_E_GENERIC_FAILURE) {
- print('testConference: holding & alerting: pass');
- } else {
- print('testConference: holding & alerting: fail');
- }
-
- // test case 3: one holding, one active
- c1.state = CALLSTATE_ACTIVE;
- testResult.rilErrCode = RIL_E_SUCCESS;
- testResult = simulatedRadio.rilRequestConference(req);
- if (testResult.rilErrCode == RIL_E_SUCCESS) {
- print('testConference: holding & active: pass');
- } else {
- print('testConference: holding & active: fail');
- }
-
- // test case 4: one holding, one incoming
- c1.state = CALLSTATE_INCOMING;
- testResult.rilErrCode = RIL_E_SUCCESS;
- testResult = simulatedRadio.rilRequestConference(req);
- if (testResult.rilErrCode == RIL_E_GENERIC_FAILURE) {
- print('testConference: holding & incoming: pass');
- } else {
- print('testConference: holding & incoming: fail');
- }
-
- // test case 5: one holding, one waiting
- c1.state = CALLSTATE_WAITING;
- testResult.rilErrCode = RIL_E_SUCCESS;
- testResult = simulatedRadio.rilRequestConference(req);
- if (testResult.rilErrCode == RIL_E_GENERIC_FAILURE) {
- print('testConference: holding & waiting: pass');
- } else {
- print('testConference: holding & waiting: fail');
- }
-
- simulatedRadio.removeCall(c0.index);
- simulatedRadio.removeCall(c1.index);
- print('testConference: X');
- }
-
- testConference();
-}
-/**
- * Test serialization of bad numeric enum
- */
-if (false) {
- var c = new RilCall(1000, '11234567890', 'me');
- rsp = new Object();
- rsp.calls = [ c ];
- try {
- rilSchema[packageNameAndSeperator + 'RspGetCurrentCalls'].serialize(rsp);
- print('test-enum a bad numeric enum value, FAILURE exception expected');
- } catch (err) {
- print('test-enum a bad numeric enum value, SUCCESS exception expected: ' + err);
- }
-}
-
-/**
- * Test serialization of bad string enum
- */
-if (false) {
- // The state parameter 'NOT_CALLSTATE_ACTIVE' can get corrupted in ToProto?
- var c = new RilCall('NOT_CALLSTATE_ACTIVE', '11234567890', 'me');
- rsp = new Object();
- rsp.calls = [ c ];
- try {
- rilSchema[packageNameAndSeperator + 'RspGetCurrentCalls'].serialize(rsp);
- print('test-enum a bad string enum value, FAILURE exception expected');
- } catch (err) {
- print('test-enum a bad string enum value, SUCCESS exception expected: ' + err);
- }
-}
-
-/**
- * Test addDelayed
- */
-if (false) {
- print("test addDelayed E");
- simulatedRadioWorker.add( {
- 'reqNum' : CMD_DELAY_TEST,
- 'hello' : 'hi no delay' });
- simulatedRadioWorker.addDelayed( {
- 'reqNum' : CMD_DELAY_TEST,
- 'hello' : 'hi not-a-number is 0 delay' }, "not-a-number");
- simulatedRadioWorker.addDelayed( {
- 'reqNum' : CMD_DELAY_TEST,
- 'hello' : 'hi negative delay is 0 delay' }, -1000);
- simulatedRadioWorker.addDelayed( {
- 'reqNum' : CMD_DELAY_TEST,
- 'hello' : 'hi delayed 2 seconds' }, 2000);
- print("test addDelayed X");
-}
-
-/**
- * A test for setRadioState, verify it can handle valid string variable,
- * undefined varilabe, and invalid radio state correctly.
- */
-if (false) {
- function testSetRadioState() {
- print('testSetRadioState E:');
- // defined string variable
- newState = 'RADIOSTATE_UNAVAILABLE';
- try {
- setRadioState(newState);
- } catch (err) {
- print('test failed');
- }
- print('Expecting gRadioState to be ' + RADIOSTATE_UNAVAILABLE +
- ', gRadioState is: ' + gRadioState);
-
- // undefined string variable, expecting exception
- try {
- setRadioState('RADIOSTATE_UNDEFINED');
- } catch (err) {
- if (err.indexOf('Unknow string') >= 0) {
- print('test success');
- print('err: ' + err);
- } else {
- print('test failed');
- }
- }
-
- // valid radio state
- try {
- setRadioState(RADIOSTATE_NV_READY);
- } catch (err) {
- print('test failed');
- }
- print('Expecting gRadioState to be ' + RADIOSTATE_NV_READY +
- ', gRadioState is: ' + gRadioState);
-
- // invalid radio state
- try {
- setRadioState(-1);
- } catch (err) {
- if (err.indexOf('invalid') >= 0) {
- print('test success');
- print('err: ' + err);
- } else {
- print('test failed, err: ' + err);
- }
- }
- print('gRadioState should not be set: ' + gRadioState);
-
- // set radio state to be SIM_READY
- setRadioState(RADIOSTATE_SIM_READY);
- print('Expecting gRadioState to be ' + RADIOSTATE_SIM_READY +
- ', gRadioState is: ' + gRadioState);
- print('testSetRadioState X:');
- }
-
- testSetRadioState();
-}
diff --git a/mock-ril/src/proto/ctrl.proto b/mock-ril/src/proto/ctrl.proto
deleted file mode 100644
index 0705386..0000000
--- a/mock-ril/src/proto/ctrl.proto
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved.
-// Author: wink@google.com (Wink Saville)
-
-package ril_proto;
-
-option java_package='com.android.internal.telephony.ril_proto';
-option java_outer_classname='RilCtrlCmds';
-
-import "hardware/ril/mock-ril/src/proto/ril.proto";
-
-enum CtrlCmd {
- CTRL_CMD_ECHO = 0;
- CTRL_CMD_GET_RADIO_STATE = 1;
- CTRL_CMD_SET_RADIO_STATE = 2;
- CTRL_CMD_SET_MT_CALL = 1001;
- CTRL_CMD_HANGUP_CONN_REMOTE = 1002;
- CTRL_CMD_SET_CALL_TRANSITION_FLAG = 1003;
- CTRL_CMD_SET_CALL_ALERT = 1004;
- CTRL_CMD_SET_CALL_ACTIVE = 1005;
- CTRL_CMD_ADD_DIALING_CALL = 1006; // this command is for testing
-}
-
-enum CtrlStatus {
- CTRL_STATUS_OK = 0;
- CTRL_STATUS_ERR = 1;
-}
-
-// request of setting radio state
-message CtrlReqRadioState {
- required ril_proto.RadioState state = 1;
-}
-
-// response of set/get radio state
-message CtrlRspRadioState {
- required ril_proto.RadioState state = 1;
-}
-
-// 1001: request of creating an incoming call
-message CtrlReqSetMTCall {
- required string phone_number = 1; // Phone number to display
-}
-
-// 1002: request of hangup a connection for the given disconnection cause
-message CtrlHangupConnRemote {
- required int32 connection_id = 1; // connection id
- required int32 call_fail_cause = 2; // call failure cause
-}
-
-// 1003: set call transition flag: true for controlled transition
-// false for auto-transition
-message CtrlSetCallTransitionFlag {
- required bool flag = 1;
-}
-
-// 1006: Add a dialing call
-message CtrlReqAddDialingCall {
- required string phone_number = 1; // phone number
-}
diff --git a/mock-ril/src/proto/msgheader.proto b/mock-ril/src/proto/msgheader.proto
deleted file mode 100644
index 0886de9..0000000
--- a/mock-ril/src/proto/msgheader.proto
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved.
-// Author: wink@google.com (Wink Saville)
-
-package communication;
-
-option java_package='com.android.internal.communication';
-
-message MsgHeader {
- required uint32 cmd = 1;
- required uint32 length_data = 2;
- optional uint32 status = 3;
- optional uint64 token = 4;
-}
diff --git a/mock-ril/src/proto/ril.proto b/mock-ril/src/proto/ril.proto
deleted file mode 100644
index f7c2e73..0000000
--- a/mock-ril/src/proto/ril.proto
+++ /dev/null
@@ -1,298 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved.
-// Author: wink@google.com (Wink Saville)
-
-package ril_proto;
-
-option java_package='com.android.internal.telephony.ril_proto';
-option java_outer_classname='RilCmds';
-
-enum RadioState {
- RADIOSTATE_OFF = 0; /* Radio explictly powered off (eg CFUN=0) */
- RADIOSTATE_UNAVAILABLE = 1; /* Radio unavailable (eg, resetting or not booted) */
- RADIOSTATE_SIM_NOT_READY = 2; /* Radio is on, but the SIM interface is not ready */
- RADIOSTATE_SIM_LOCKED_OR_ABSENT = 3; /* SIM PIN locked, PUK required, network
- personalization locked, or SIM absent */
- RADIOSTATE_SIM_READY = 4; /* Radio is on and SIM interface is available */
- RADIOSTATE_RUIM_NOT_READY = 5; /* Radio is on, but the RUIM interface is not ready */
- RADIOSTATE_RUIM_READY = 6; /* Radio is on and the RUIM interface is available */
- RADIOSTATE_RUIM_LOCKED_OR_ABSENT = 7; /* RUIM PIN locked, PUK required, network
- personalization locked, or RUIM absent */
- RADIOSTATE_NV_NOT_READY = 8; /* Radio is on, but the NV interface is not available */
- RADIOSTATE_NV_READY = 9; /* Radio is on and the NV interface is available */
-}
-
-enum RilCardState {
- CARDSTATE_ABSENT = 0;
- CARDSTATE_PRESENT = 1;
- CARDSTATE_ERROR = 2;
-}
-
-enum RilPersoSubstate {
- PERSOSUBSTATE_UNKNOWN = 0; /* initial state */
- PERSOSUBSTATE_IN_PROGRESS = 1; /* in between each lock transition */
- PERSOSUBSTATE_READY = 2; /* when either SIM or RUIM Perso is finished
- since each app can only have 1 active perso
- involved */
- PERSOSUBSTATE_SIM_NETWORK = 3;
- PERSOSUBSTATE_SIM_NETWORK_SUBSET = 4;
- PERSOSUBSTATE_SIM_CORPORATE = 5;
- PERSOSUBSTATE_SIM_SERVICE_PROVIDER = 6;
- PERSOSUBSTATE_SIM_SIM = 7;
- PERSOSUBSTATE_SIM_NETWORK_PUK = 8; /* The corresponding perso lock is blocked */
- PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK = 9;
- PERSOSUBSTATE_SIM_CORPORATE_PUK = 10;
- PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK = 11;
- PERSOSUBSTATE_SIM_SIM_PUK = 12;
- PERSOSUBSTATE_RUIM_NETWORK1 = 13;
- PERSOSUBSTATE_RUIM_NETWORK2 = 14;
- PERSOSUBSTATE_RUIM_HRPD = 15;
- PERSOSUBSTATE_RUIM_CORPORATE = 16;
- PERSOSUBSTATE_RUIM_SERVICE_PROVIDER = 17;
- PERSOSUBSTATE_RUIM_RUIM = 18;
- PERSOSUBSTATE_RUIM_NETWORK1_PUK = 19; /* The corresponding perso lock is blocked */
- PERSOSUBSTATE_RUIM_NETWORK2_PUK = 20;
- PERSOSUBSTATE_RUIM_HRPD_PUK = 21;
- PERSOSUBSTATE_RUIM_CORPORATE_PUK = 22;
- PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK = 23;
- PERSOSUBSTATE_RUIM_RUIM_PUK = 24;
-}
-
-enum RilAppState {
- APPSTATE_UNKNOWN = 0;
- APPSTATE_DETECTED = 1;
- APPSTATE_PIN = 2; /* If PIN1 or UPin is required */
- APPSTATE_PUK = 3; /* If PUK1 or Puk for UPin is required */
- APPSTATE_SUBSCRIPTION_PERSO = 4; /* perso_substate should be look at
- when app_state is assigned to this value */
- APPSTATE_READY = 5;
-}
-
-enum RilPinState {
- PINSTATE_UNKNOWN = 0;
- PINSTATE_ENABLED_NOT_VERIFIED = 1;
- PINSTATE_ENABLED_VERIFIED = 2;
- PINSTATE_DISABLED = 3;
- PINSTATE_ENABLED_BLOCKED = 4;
- PINSTATE_ENABLED_PERM_BLOCKED = 5;
-}
-
-enum RilAppType {
- APPTYPE_UNKNOWN = 0;
- APPTYPE_SIM = 1;
- APPTYPE_USIM = 2;
- APPTYPE_RUIM = 3;
- APPTYPE_CSIM = 4;
-}
-
-message RilAppStatus {
- optional RilAppType app_type = 1;
- optional RilAppState app_state = 2;
- optional RilPersoSubstate perso_substate = 3; /* applicable only if app_state ==
- APPSTATE_SUBSCRIPTION_PERSO */
- optional string aid = 4; /* null terminated string, e.g., from 0xA0, 0x00 -> 0x41,
- 0x30, 0x30, 0x30 */
- optional string app_label = 5; /* null terminated string */
- optional int32 pin1_replaced = 6; /* applicable to USIM and CSIM */
- optional RilPinState pin1 = 7;
- optional RilPinState pin2 = 8;
-}
-
-
-message RilCardStatus {
- optional RilCardState card_state = 1; /* current state */
- optional RilPinState universal_pin_state = 2; /* applicable to USIM and CSIM: PINSTATE_xxx */
- optional int32 gsm_umts_subscription_app_index = 3; /* value < CARD_MAX_APPS */
- optional int32 cdma_subscription_app_index = 4; /* value < CARD_MAX_APPS */
- optional int32 ims_subscription_app_index = 5; /* value < CARD_MAX_APPS */
- optional int32 num_applications = 6; /* value <= CARD_MAX_APPS */
- repeated RilAppStatus applications = 7; /* CARD_MAX_APPS == 8 */
-}
-
-/* User-to-User signaling Info activation types derived from 3GPP 23.087 v8.0 */
-enum RilUusType {
- RILUUSTYPE1_IMPLICIT = 0;
- RILUUSTYPE1_REQUIRED = 1;
- RILUUSTYPE1_NOT_REQUIRED = 2;
- RILUUSTYPE2_REQUIRED = 3;
- RILUUSTYPE2_NOT_REQUIRED = 4;
- RILUUSTYPE3_REQUIRED = 5;
- RILUUSTYPE3_NOT_REQUIRED = 6;
-};
-
-/* User-to-User Signaling Information data coding schemes. Possible values for
- * Octet 3 (Protocol Discriminator field) in the UUIE. The values have been
- * specified in section 10.5.4.25 of 3GPP TS 24.008 */
-enum RilUusDcs {
- RILUUSDCS_USP = 0; /* User specified protocol */
- RILUUSDCS_OSIHLP = 1; /* OSI higher layer protocol */
- RILUUSDCS_X244 = 2; /* X.244 */
- RILUUSDCS_RMCF = 3; /* Reserved for system mangement
- convergence function */
- RILUUSDCS_IA5c = 4; /* IA5 characters */
-}
-
-/* User-to-User Signaling Information defined in 3GPP 23.087 v8.0
- * This data is passed in RIL_ExtensionRecord and rec contains this
- * structure when type is RIL_UUS_INFO_EXT_REC */
-message RilUusInfo {
- optional RilUusType uus_type = 1; /* UUS Type */
- optional RilUusDcs uus_dcs = 2; /* UUS Data Coding Scheme */
- optional int32 uus_length = 3; /* Length of UUS Data */
- optional string uus_data = 4; /* UUS Data */
-}
-
-enum RilCallState {
- CALLSTATE_ACTIVE = 0;
- CALLSTATE_HOLDING = 1;
- CALLSTATE_DIALING = 2; /* MO call only */
- CALLSTATE_ALERTING = 3; /* MO call only */
- CALLSTATE_INCOMING = 4; /* MT call only */
- CALLSTATE_WAITING = 5; /* MT call only */
-}
-
-message RilCall {
- optional RilCallState state = 1; /* State of the call */
- optional int32 index = 2; /* Connection Index for use with,
- eg, AT+CHLD */
- optional int32 toa = 3; /* type of address, eg 145 = intl */
- optional bool is_mpty = 4; /* true if is mpty call */
- optional bool is_mt = 5; /* true if call is mobile terminated */
- optional int32 als = 6; /* ALS line indicator if available
- (0 = line 1) */
- optional bool is_voice = 7; /* true if this is is a voice call */
- optional bool is_voice_privacy = 8; /* true if CDMA voice privacy mode
- is active */
- optional string number = 9; /* Remote party number */
- optional int32 number_presentation = 10; /* 0=Allowed, 1=Restricted,
- 2=Not Specified/Unknown 3=Payphone */
- optional string name = 11; /* Remote party name */
- optional int32 name_presentation = 12; /* 0=Allowed, 1=Restricted,
- 2=Not Specified/Unknown 3=Payphone */
- optional RilUusInfo uus_info = 13; /* NULL or Pointer to User-User Signaling
- Information */
-}
-
-message RILGWSignalStrength {
- optional int32 signal_strength = 1; /* Valid values are (0-31, 99) as defined
- in TS 27.007 8.5 */
- optional int32 bit_error_rate = 2; /* bit error rate (0-7, 99) as defined
- in TS 27.007 8.5 */
-}
-
-message RILCDMASignalStrength {
- optional int32 dbm = 1; /* Valid values are positive integers. This value is the actual RSSI
- value multiplied by -1. Example: If the actual RSSI is -75, then
- this response value will be 75. */
- optional int32 ecio = 2; /* Valid values are positive integers. This value is the actual Ec/Io
- multiplied by -10. Example: If the actual Ec/Io is -12.5 dB, then
- this response value will be 125. */
-}
-
-message RILEVDOSignalStrength {
- optional int32 dbm = 1; /* Valid values are positive integers. This value is the actual RSSI
- value multiplied by -1. Example: If the actual RSSI is -75, then
- this response value will be 75. */
- optional int32 ecio = 2; /* Valid values are positive integers. This value is the actual
- Ec/Io multiplied by -10. Example: If the actual Ec/Io is -12.5 dB,
- then this response value will be 125. */
- optional int32 signal_noise_ratio = 3; /* Valid values are 0-8.
- 8 is the highest signal to noise ratio. */
-}
-
-message RILLTESignalStrength {
- optional int32 signal_strength = 1; /* Valid values are (0-31, 99)
- * as defined in TS 27.007 8.5 */
- optional int32 rsrp = 2; /* The current Reference Signal Receive Power in dBm
- * multipled by -1. Range: 44 to 140 dBm,
- * TODO: doc reference */
- optional int32 rsrq = 3; /* The current Reference Signal Receive Quality in dB
- * multiplied by -1. Range: 20 to 3 dB.
- * TODO: doc reference */
- optional int32 rssnr = 4; /* TODO: Need documentation and doc reference */
- optional int32 cqi = 5; /* TODO: Need documentation and doc reference */
-}
-
-// Response is an array of strings.
-//
-// If a strings(i) is "*magic-null*" then that value will be returned as null.
-message RspStrings{
- repeated string strings = 1;
-}
-
-// Response is an array of integers
-message RspIntegers{
- repeated int32 integers = 1;
-}
-
-// 1 RIL_REQUEST_GET_SIM_STATUS
-message RspGetSimStatus {
- required RilCardStatus card_status = 1;
-}
-
-// 2 RIL_REQUEST_ENTER_SIM_PIN
-message ReqEnterSimPin {
- required string pin = 1;
-}
-// RIL_REQUEST_ENTER_SIM_PIN response
-message RspEnterSimPin {
- required int32 retries_remaining = 1;
-}
-
-// 9 RIL_GET_CURRENT_CALLS response
-message RspGetCurrentCalls {
- repeated RilCall calls = 1;
-}
-
-// 10 RIL_REQUEST_DIAL
-message ReqDial {
- optional string address = 1;
- optional int32 clir = 2;
- /* (same as 'n' paremeter in TS 27.007 7.7 "+CLIR"
- * clir == 0 on "use subscription default value"
- * clir == 1 on "CLIR invocation" (restrict CLI presentation)
- * clir == 2 on "CLIR suppression" (allow CLI presentation)
- */
- optional RilUusInfo uus_info = 3; /* NULL or Pointer to User-User Signaling Information */
-}
-
-// 12 RIL_REQUEST_HANG_UP
-message ReqHangUp {
- required int32 connection_index = 1;
-}
-
-// 18 response for RIL_REQUEST_LAST_CALL_FAIL_CAUSE
-message RspLastCallFailCause {
- required int32 last_call_fail_cause = 1;
-}
-
-// 19 RIL_REQUEST_SIGNAL_STRENGTH response
-message RspSignalStrength {
- optional RILGWSignalStrength gw_signalstrength = 1;
- optional RILCDMASignalStrength cdma_signalstrength = 2;
- optional RILEVDOSignalStrength evdo_signalstrength = 3;
- optional RILLTESignalStrength lte_signalstrength = 4;
-}
-
-// 22 RIL_REQUEST_OPERATOR response
-message RspOperator{
- optional string long_alpha_ons = 1; // The long alpha ons or eons
- optional string short_alpha_ons = 2; // The short alpha ons or eons
- optional string mcc_mnc = 3; // The 5 or 6 digit mcc + mnc
-}
-
-// 52 RIL_REQUEST_SEPARATE_CONNECTION
-message ReqSeparateConnection{
- required int32 index = 1; // Connection index to separate
- // from multiparty call
-}
-
-// 53 RIL_REQUEST_SET_MUTE
-message ReqSetMute{
- required bool state = 1; // true to "enable mute", false to "disable mute"
-}
-
-// 61 RIL_REQUEST_SCREEN_STATE
-message ReqScreenState {
- required bool state = 1; // true screen is on, false screen is off
-}
-
diff --git a/mock-ril/src/python/tcs.py b/mock-ril/src/python/tcs.py
deleted file mode 100755
index 0b56301..0000000
--- a/mock-ril/src/python/tcs.py
+++ /dev/null
@@ -1,247 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright (C) 2010 The Android Open Source Project
-#
-# 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.
-#
-
-"""Test server
-
-A detailed description of tms.
-"""
-
-__author__ = 'wink@google.com (Wink Saville)'
-
-import socket
-import struct
-import sys
-import time
-
-import ctrl_pb2
-import ril_pb2
-import msgheader_pb2
-
-def recvall(s, count):
- """Receive all of the data otherwise return none.
-
- Args:
- s: socket
- count: number of bytes
-
- Returns:
- data received
- None if no data is received
- """
- all_data = []
- while (count > 0):
- data = s.recv(count)
- if (len(data) == 0):
- return None
- count -= len(data)
- all_data.append(data)
- result = ''.join(all_data);
- return result
-
-def sendall(s, data):
- """Send all of the data
-
- Args:
- s: socket
- count: number of bytes
-
- Returns:
- Nothing
- """
- s.sendall(data)
-
-class MsgHeader:
- """A fixed length message header; cmd, token, status and length of protobuf."""
- def __init__(self):
- self.cmd = 0
- self.token = 0
- self.status = 0
- self.length_protobuf = 0
-
- def sendHeader(self, s):
- """Send the header to the socket
-
- Args:
- s: socket
-
- Returns
- nothing
- """
- mh = msgheader_pb2.MsgHeader()
- mh.cmd = self.cmd
- mh.token = self.token
- mh.status = self.status
- mh.length_data = self.length_protobuf
- mhser = mh.SerializeToString()
- len_msg_header_raw = struct.pack('<i', len(mhser))
- sendall(s, len_msg_header_raw)
- sendall(s, mhser)
-
- def recvHeader(self, s):
- """Receive the header from the socket"""
- len_msg_header_raw = recvall(s, 4)
- len_msg_hdr = struct.unpack('<i', len_msg_header_raw)
- mh = msgheader_pb2.MsgHeader()
- mh_raw = recvall(s, len_msg_hdr[0])
- mh.ParseFromString(mh_raw)
- self.cmd = mh.cmd
- self.token = mh.token
- self.status = mh.status
- self.length_protobuf = mh.length_data;
-
-class Msg:
- """A message consists of a fixed length MsgHeader followed by a protobuf.
-
- This class sends and receives messages, when sending the status
- will be zero and when receiving the protobuf field will be an
- empty string if there was no protobuf.
- """
- def __init__(self):
- """Initialize the protobuf to None and header to an empty"""
- self.protobuf = None
- self.header = MsgHeader()
-
- # Keep a local copy of header for convenience
- self.cmd = 0
- self.token = 0
- self.status = 0
-
- def sendMsg(self, s, cmd, token, protobuf=''):
- """Send a message to a socket
-
- Args:
- s: socket
- cmd: command to send
- token: token to send, will be returned unmodified
- protobuf: optional protobuf to send
-
- Returns
- nothing
- """
- self.cmd = cmd
- self.token = token
- self.status = 0
- self.protobuf = protobuf
-
- self.header.cmd = self.cmd
- self.header.token = self.token
- self.header.status = self.status
- if (len(protobuf) > 0):
- self.header.length_protobuf = len(protobuf)
- else:
- self.header.length_protobuf = 0
- self.protobuf = ''
- self.header.sendHeader(s)
- if (self.header.length_protobuf > 0):
- sendall(s, self.protobuf)
-
- def recvMsg(self, s):
- """Receive a message from a socket
-
- Args:
- s: socket
-
- Returns:
- nothing
- """
- self.header.recvHeader(s)
- self.cmd = self.header.cmd
- self.token = self.header.token
- self.status = self.header.status
- if (self.header.length_protobuf > 0):
- self.protobuf = recvall(s, self.header.length_protobuf)
- else:
- self.protobuf = ''
-
-def main(argv):
- """Create a socket and connect.
-
- Before using you'll need to forward the port
- used by mock_ril, 54312 to a port on the PC.
- The following worked for me:
-
- adb forward tcp:11111 tcp:54312.
-
- Then you can execute this test using:
-
- tms.py 127.0.0.1 11111
- """
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- host = sys.argv[1] # server address
- print "host=%s" % host
- port = int(sys.argv[2]) # server port
- print "port=%d" % port
- s.connect((host, port))
-
- # Create an object which is serializable to a protobuf
- rrs = ctrl_pb2.CtrlRspRadioState()
- rrs.state = ril_pb2.RADIOSTATE_UNAVAILABLE
- print "rrs.state=%d" % (rrs.state)
-
- # Serialize
- rrs_ser = rrs.SerializeToString()
- print "len(rrs_ser)=%d" % (len(rrs_ser))
-
- # Deserialize
- rrs_new = ctrl_pb2.CtrlRspRadioState()
- rrs_new.ParseFromString(rrs_ser)
- print "rrs_new.state=%d" % (rrs_new.state)
-
-
- # Do an echo test
- req = Msg()
- req.sendMsg(s, 0, 1234567890123, rrs_ser)
- resp = Msg()
- resp.recvMsg(s)
- response = ctrl_pb2.CtrlRspRadioState()
- response.ParseFromString(resp.protobuf)
-
- print "cmd=%d" % (resp.cmd)
- print "token=%d" % (resp.token)
- print "status=%d" % (resp.status)
- print "len(protobuf)=%d" % (len(resp.protobuf))
- print "response.state=%d" % (response.state)
- if ((resp.cmd == 0) & (resp.token == 1234567890123) &
- (resp.status == 0) & (response.state == 1)):
- print "SUCCESS: echo ok"
- else:
- print "ERROR: expecting cmd=0 token=1234567890123 status=0 state=1"
-
- # Test CTRL_GET_RADIO_STATE
- req.sendMsg(s, ctrl_pb2.CTRL_CMD_GET_RADIO_STATE, 4)
- resp = Msg()
- resp.recvMsg(s)
-
- print "cmd=%d" % (resp.cmd)
- print "token=%d" % (resp.token)
- print "status=%d" % (resp.status)
- print "length_protobuf=%d" % (len(resp.protobuf))
-
- if (resp.cmd == ctrl_pb2.CTRL_CMD_GET_RADIO_STATE):
- response = ctrl_pb2.CtrlRspRadioState()
- response.ParseFromString(resp.protobuf)
- print "SUCCESS: response.state=%d" % (response.state)
- else:
- print "ERROR: expecting resp.cmd == ctrl_pb2.CTRL_CMD_GET_RADIO_STATE"
-
- # Close socket
- print "closing socket"
- s.close()
-
-
-if __name__ == '__main__':
- main(sys.argv)
diff --git a/reference-ril/Android.mk b/reference-ril/Android.mk
index ec2692e..1c99a7e 100644
--- a/reference-ril/Android.mk
+++ b/reference-ril/Android.mk
@@ -12,7 +12,7 @@
at_tok.c
LOCAL_SHARED_LIBRARIES := \
- libcutils libutils libril
+ liblog libcutils libutils libril librilutils
# for asprinf
LOCAL_CFLAGS := -D_GNU_SOURCE
diff --git a/reference-ril/reference-ril.c b/reference-ril/reference-ril.c
index d1dd23f..facd223 100644
--- a/reference-ril/reference-ril.c
+++ b/reference-ril/reference-ril.c
@@ -16,6 +16,7 @@
*/
#include <telephony/ril_cdma_sms.h>
+#include <telephony/librilutils.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
@@ -223,6 +224,12 @@
static int s_expectAnswer = 0;
#endif /* WORKAROUND_ERRONEOUS_ANSWER */
+static int s_cell_info_rate_ms = INT_MAX;
+static int s_mcc = 0;
+static int s_mnc = 0;
+static int s_lac = 0;
+static int s_cid = 0;
+
static void pollSIMState (void *param);
static void setRadioState(RIL_RadioState newState);
static void setRadioTechnology(ModemInfo *mdm, int newtech);
@@ -1261,6 +1268,8 @@
default:
goto error;
}
+ s_lac = resp[1];
+ s_cid = resp[2];
if (response)
*response = resp;
if (items)
@@ -1443,6 +1452,12 @@
err = at_tok_nextstr(&line, &(response[i]));
if (err < 0) goto error;
+ // Simple assumption that mcc and mnc are 3 digits each
+ if (strlen(response[i]) == 6) {
+ if (sscanf(response[i], "%3d%3d", &s_mcc, &s_mnc) != 2) {
+ RLOGE("requestOperator expected mccmnc to be 6 decimal digits");
+ }
+ }
}
if (i != 3) {
@@ -1815,6 +1830,47 @@
return ret;
}
+static void requestGetCellInfoList(void *data, size_t datalen, RIL_Token t)
+{
+ uint64_t curTime = ril_nano_time();
+ RIL_CellInfo ci[1] =
+ {
+ { // ci[0]
+ 1, // cellInfoType
+ 1, // registered
+ curTime - 1000, // Fake some time in the past
+ { // union CellInfo
+ { // RIL_CellInfoGsm gsm
+ { // gsm.cellIdneityGsm
+ s_mcc, // mcc
+ s_mnc, // mnc
+ s_lac, // lac
+ s_cid, // cid
+ 0 // psc
+ },
+ { // gsm.signalStrengthGsm
+ 10, // signalStrength
+ 0 // bitErrorRate
+ }
+ }
+ }
+ }
+ };
+
+ RIL_onRequestComplete(t, RIL_E_SUCCESS, ci, sizeof(ci));
+}
+
+
+static void requestSetCellInfoListRate(void *data, size_t datalen, RIL_Token t)
+{
+ // For now we'll save the rate but no RIL_UNSOL_CELL_INFO_LIST messages
+ // will be sent.
+ assert (datalen == sizeof(int));
+ s_cell_info_rate_ms = ((int *)data)[0];
+
+ RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
+}
+
/*** Callback methods from the RIL library to us ***/
/**
@@ -2178,6 +2234,14 @@
break;
} // Fall-through if tech is not cdma
+ case RIL_REQUEST_GET_CELL_INFO_LIST:
+ requestGetCellInfoList(data, datalen, t);
+ break;
+
+ case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE:
+ requestSetCellInfoListRate(data, datalen, t);
+ break;
+
default:
RLOGD("Request not supported. Tech: %d",TECH(sMdmInfo));
RIL_onRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
diff --git a/rild/Android.mk b/rild/Android.mk
index c782933..f01b320 100644
--- a/rild/Android.mk
+++ b/rild/Android.mk
@@ -8,6 +8,7 @@
LOCAL_SHARED_LIBRARIES := \
+ liblog \
libcutils \
libril \
libdl
@@ -27,6 +28,7 @@
radiooptions.c
LOCAL_SHARED_LIBRARIES := \
+ liblog \
libcutils \
LOCAL_CFLAGS := \