summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorThe Android Open Source Project <initial-contribution@android.com>2009-03-03 19:32:14 -0800
committerThe Android Open Source Project <initial-contribution@android.com>2009-03-03 19:32:14 -0800
commitcc490161f6af9e4a6842ee827e4bfc43bc4509d5 (patch)
treea60e0ed36ef1d3a43530c46562c86c9cd431744c
parent3bbe5328cd738976443822502e23fb3971c5f87b (diff)
downloadhardware_libhardware_legacy-cc490161f6af9e4a6842ee827e4bfc43bc4509d5.zip
hardware_libhardware_legacy-cc490161f6af9e4a6842ee827e4bfc43bc4509d5.tar.gz
hardware_libhardware_legacy-cc490161f6af9e4a6842ee827e4bfc43bc4509d5.tar.bz2
auto import from //depot/cupcake/@135843
-rw-r--r--Android.mk33
-rw-r--r--MODULE_LICENSE_APACHE20
-rw-r--r--NOTICE190
-rw-r--r--flashlight/Android.mk6
-rw-r--r--flashlight/flashlight.c93
-rw-r--r--gps/Android.mk18
-rw-r--r--gps/gps.cpp37
-rw-r--r--gps/gps_qemu.c898
-rw-r--r--include/hardware_legacy/AudioHardwareBase.h74
-rw-r--r--include/hardware_legacy/AudioHardwareInterface.h240
-rw-r--r--include/hardware_legacy/IMountService.h78
-rw-r--r--include/hardware_legacy/flashlight.h32
-rw-r--r--include/hardware_legacy/gps.h261
-rw-r--r--include/hardware_legacy/led.h44
-rw-r--r--include/hardware_legacy/power.h60
-rw-r--r--include/hardware_legacy/qemu_tracing.h33
-rw-r--r--include/hardware_legacy/uevent.h31
-rw-r--r--include/hardware_legacy/vibrator.h44
-rw-r--r--include/hardware_legacy/wifi.h171
-rw-r--r--led/Android.mk15
-rw-r--r--led/led_qemu.c23
-rw-r--r--led/led_sardine.c78
-rw-r--r--led/led_stub.c51
-rw-r--r--led/led_trout.c115
-rw-r--r--mount/Android.mk4
-rw-r--r--mount/IMountService.cpp118
-rw-r--r--power/Android.mk8
-rw-r--r--power/power.c238
-rw-r--r--power/power_qemu.c51
-rw-r--r--power/power_qemu.h27
-rw-r--r--qemu.h110
-rw-r--r--qemu/Android.mk3
-rw-r--r--qemu/qemu.c312
-rw-r--r--qemu_tracing/Android.mk4
-rw-r--r--qemu_tracing/qemu_tracing.c86
-rw-r--r--tests/gpstest/Android.mk34
-rw-r--r--tests/gpstest/gpstest.cpp129
-rw-r--r--uevent/Android.mk7
-rw-r--r--uevent/uevent.c78
-rw-r--r--uevent/uevent_stub.c33
-rw-r--r--vibrator/Android.mk4
-rw-r--r--vibrator/vibrator.c58
-rw-r--r--wifi/Android.mk5
-rw-r--r--wifi/wifi.c458
44 files changed, 4392 insertions, 0 deletions
diff --git a/Android.mk b/Android.mk
new file mode 100644
index 0000000..c698e26
--- /dev/null
+++ b/Android.mk
@@ -0,0 +1,33 @@
+# Copyright 2006 The Android Open Source Project
+
+# Setting LOCAL_PATH will mess up all-subdir-makefiles, so do it beforehand.
+SAVE_MAKEFILES := $(call all-subdir-makefiles)
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SHARED_LIBRARIES := libutils libcutils libwpa_client
+
+LOCAL_INCLUDES += $(LOCAL_PATH)
+
+ifneq ($(TARGET_SIMULATOR),true)
+ LOCAL_CFLAGS += -DQEMU_HARDWARE
+ QEMU_HARDWARE := true
+endif
+
+ifneq ($(TARGET_SIMULATOR),true)
+LOCAL_SHARED_LIBRARIES += libdl
+endif
+
+include $(SAVE_MAKEFILES)
+
+# need "-lrt" on Linux simulator to pick up clock_gettime
+ifeq ($(TARGET_SIMULATOR),true)
+ ifeq ($(HOST_OS),linux)
+ LOCAL_LDLIBS += -lrt -lpthread -ldl
+ endif
+endif
+
+LOCAL_MODULE:= libhardware_legacy
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..c5b1efa
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,190 @@
+
+ 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
+
diff --git a/flashlight/Android.mk b/flashlight/Android.mk
new file mode 100644
index 0000000..237d0df
--- /dev/null
+++ b/flashlight/Android.mk
@@ -0,0 +1,6 @@
+# Copyright 2007 The Android Open Source Project
+
+LOCAL_SRC_FILES += flashlight/flashlight.c
+ifeq ($(QEMU_HARDWARE),yes)
+ LOCAL_CFLAGS += -DQEMU_FLASHLIGHT
+endif
diff --git a/flashlight/flashlight.c b/flashlight/flashlight.c
new file mode 100644
index 0000000..0325e11
--- /dev/null
+++ b/flashlight/flashlight.c
@@ -0,0 +1,93 @@
+#include <hardware_legacy/flashlight.h>
+
+#include <stdio.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include "qemu.h"
+
+#define FLASHLIGHT "/sys/class/leds/spotlight/brightness"
+#define CAMERA_FLASH "/sys/class/timed_output/flash/enable"
+
+#ifdef QEMU_HARDWARE
+int qemu_get_flashlight_enabled()
+{
+ char question[256];
+ char answer[256];
+ int len;
+
+ len = qemu_command_format( question, sizeof question,
+ "get_flashlight_enabled" );
+
+ len = qemu_control_query( question, len, answer, sizeof answer );
+ if (len <= 0) return 0;
+
+ /* we expect an answer of 0 or 1 */
+ return (answer[0] == '1');
+}
+
+int qemu_set_flashlight_enabled(int on)
+{
+ return qemu_control_command( "set_flashlight_enabled:%d", on );
+}
+
+int qemu_enable_camera_flash(int milliseconds)
+{
+ return qemu_control_command( "enable_camera_flash:%d", milliseconds );
+}
+#endif
+
+int get_flashlight_enabled()
+{
+ int fd;
+ int ret = 0;
+ char value;
+
+ QEMU_FALLBACK(get_flashlight_enabled());
+
+ fd = open(FLASHLIGHT, O_RDONLY);
+ if(fd && read(fd, &value, 1) == 1) {
+ ret = (value == '1');
+ }
+ close(fd);
+
+ return ret;
+}
+
+int set_flashlight_enabled(int on)
+{
+ int nwr, ret, fd;
+ char value[20];
+
+ QEMU_FALLBACK(set_flashlight_enabled(on));
+
+ fd = open(FLASHLIGHT, O_RDWR);
+ if(fd < 0)
+ return errno;
+
+ nwr = sprintf(value, "%d\n", !!on);
+ ret = write(fd, value, nwr);
+
+ close(fd);
+
+ return (ret == nwr) ? 0 : -1;
+}
+
+int enable_camera_flash(int milliseconds)
+{
+ int nwr, ret, fd;
+ char value[20];
+
+ QEMU_FALLBACK(enable_camera_flash(milliseconds));
+
+ fd = open(CAMERA_FLASH, O_RDWR);
+ if(fd < 0)
+ return errno;
+
+ nwr = sprintf(value, "%d\n", milliseconds);
+ ret = write(fd, value, nwr);
+
+ close(fd);
+
+ return (ret == nwr) ? 0 : -1;
+}
diff --git a/gps/Android.mk b/gps/Android.mk
new file mode 100644
index 0000000..6b33374
--- /dev/null
+++ b/gps/Android.mk
@@ -0,0 +1,18 @@
+# Use hardware GPS implementation if available.
+#
+ifneq ($(BOARD_GPS_LIBRARIES),)
+ LOCAL_CFLAGS += -DHAVE_GPS_HARDWARE
+ LOCAL_SHARED_LIBRARIES += $(BOARD_GPS_LIBRARIES)
+endif
+
+# Use emulator GPS implementation if QEMU_HARDWARE is set.
+#
+USE_QEMU_GPS_HARDWARE := $(QEMU_HARDWARE)
+
+ifeq ($(USE_QEMU_GPS_HARDWARE),true)
+ LOCAL_CFLAGS += -DHAVE_QEMU_GPS_HARDWARE
+ LOCAL_SRC_FILES += gps/gps_qemu.c
+endif
+
+LOCAL_SRC_FILES += gps/gps.cpp
+
diff --git a/gps/gps.cpp b/gps/gps.cpp
new file mode 100644
index 0000000..86e3234
--- /dev/null
+++ b/gps/gps.cpp
@@ -0,0 +1,37 @@
+#include <hardware_legacy/gps.h>
+#include <cutils/properties.h>
+
+#define LOG_TAG "libhardware_legacy"
+#include <utils/Log.h>
+#include "qemu.h"
+
+static const GpsInterface* sGpsInterface = NULL;
+
+static void
+gps_find_hardware( void )
+{
+#ifdef HAVE_QEMU_GPS_HARDWARE
+ if (qemu_check()) {
+ sGpsInterface = gps_get_qemu_interface();
+ if (sGpsInterface) {
+ LOGD("using QEMU GPS Hardware emulation\n");
+ return;
+ }
+ }
+#endif
+
+#ifdef HAVE_GPS_HARDWARE
+ sGpsInterface = gps_get_hardware_interface();
+#endif
+ if (!sGpsInterface)
+ LOGD("no GPS hardware on this device\n");
+}
+
+const GpsInterface*
+gps_get_interface()
+{
+ if (sGpsInterface == NULL)
+ gps_find_hardware();
+
+ return sGpsInterface;
+}
diff --git a/gps/gps_qemu.c b/gps/gps_qemu.c
new file mode 100644
index 0000000..d55fb22
--- /dev/null
+++ b/gps/gps_qemu.c
@@ -0,0 +1,898 @@
+
+#include <errno.h>
+#include <pthread.h>
+#include "qemu.h"
+#include <fcntl.h>
+#include <sys/epoll.h>
+#include <math.h>
+#include <time.h>
+
+#define LOG_TAG "gps_qemu"
+#include <cutils/log.h>
+#include <cutils/sockets.h>
+#include <hardware_legacy/gps.h>
+
+/* the name of the qemud-controlled socket */
+#define QEMU_CHANNEL_NAME "gps"
+
+#define GPS_DEBUG 0
+
+#if GPS_DEBUG
+# define D(...) LOGD(__VA_ARGS__)
+#else
+# define D(...) ((void)0)
+#endif
+
+
+/*****************************************************************/
+/*****************************************************************/
+/***** *****/
+/***** N M E A T O K E N I Z E R *****/
+/***** *****/
+/*****************************************************************/
+/*****************************************************************/
+
+typedef struct {
+ const char* p;
+ const char* end;
+} Token;
+
+#define MAX_NMEA_TOKENS 16
+
+typedef struct {
+ int count;
+ Token tokens[ MAX_NMEA_TOKENS ];
+} NmeaTokenizer;
+
+static int
+nmea_tokenizer_init( NmeaTokenizer* t, const char* p, const char* end )
+{
+ int count = 0;
+ char* q;
+
+ // the initial '$' is optional
+ if (p < end && p[0] == '$')
+ p += 1;
+
+ // remove trailing newline
+ if (end > p && end[-1] == '\n') {
+ end -= 1;
+ if (end > p && end[-1] == '\r')
+ end -= 1;
+ }
+
+ // get rid of checksum at the end of the sentecne
+ if (end >= p+3 && end[-3] == '*') {
+ end -= 3;
+ }
+
+ while (p < end) {
+ const char* q = p;
+
+ q = memchr(p, ',', end-p);
+ if (q == NULL)
+ q = end;
+
+ if (q > p) {
+ if (count < MAX_NMEA_TOKENS) {
+ t->tokens[count].p = p;
+ t->tokens[count].end = q;
+ count += 1;
+ }
+ }
+ if (q < end)
+ q += 1;
+
+ p = q;
+ }
+
+ t->count = count;
+ return count;
+}
+
+static Token
+nmea_tokenizer_get( NmeaTokenizer* t, int index )
+{
+ Token tok;
+ static const char* dummy = "";
+
+ if (index < 0 || index >= t->count) {
+ tok.p = tok.end = dummy;
+ } else
+ tok = t->tokens[index];
+
+ return tok;
+}
+
+
+static int
+str2int( const char* p, const char* end )
+{
+ int result = 0;
+ int len = end - p;
+
+ for ( ; len > 0; len--, p++ )
+ {
+ int c;
+
+ if (p >= end)
+ goto Fail;
+
+ c = *p - '0';
+ if ((unsigned)c >= 10)
+ goto Fail;
+
+ result = result*10 + c;
+ }
+ return result;
+
+Fail:
+ return -1;
+}
+
+static double
+str2float( const char* p, const char* end )
+{
+ int result = 0;
+ int len = end - p;
+ char temp[16];
+
+ if (len >= (int)sizeof(temp))
+ return 0.;
+
+ memcpy( temp, p, len );
+ temp[len] = 0;
+ return strtod( temp, NULL );
+}
+
+/*****************************************************************/
+/*****************************************************************/
+/***** *****/
+/***** N M E A P A R S E R *****/
+/***** *****/
+/*****************************************************************/
+/*****************************************************************/
+
+#define NMEA_MAX_SIZE 83
+
+typedef struct {
+ int pos;
+ int overflow;
+ int utc_year;
+ int utc_mon;
+ int utc_day;
+ int utc_diff;
+ GpsLocation fix;
+ gps_location_callback callback;
+ char in[ NMEA_MAX_SIZE+1 ];
+} NmeaReader;
+
+
+static void
+nmea_reader_update_utc_diff( NmeaReader* r )
+{
+ time_t now = time(NULL);
+ struct tm tm_local;
+ struct tm tm_utc;
+ long time_local, time_utc;
+
+ gmtime_r( &now, &tm_utc );
+ localtime_r( &now, &tm_local );
+
+ time_local = tm_local.tm_sec +
+ 60*(tm_local.tm_min +
+ 60*(tm_local.tm_hour +
+ 24*(tm_local.tm_yday +
+ 365*tm_local.tm_year)));
+
+ time_utc = tm_utc.tm_sec +
+ 60*(tm_utc.tm_min +
+ 60*(tm_utc.tm_hour +
+ 24*(tm_utc.tm_yday +
+ 365*tm_utc.tm_year)));
+
+ r->utc_diff = time_utc - time_local;
+}
+
+
+static void
+nmea_reader_init( NmeaReader* r )
+{
+ memset( r, 0, sizeof(*r) );
+
+ r->pos = 0;
+ r->overflow = 0;
+ r->utc_year = -1;
+ r->utc_mon = -1;
+ r->utc_day = -1;
+ r->callback = NULL;
+
+ nmea_reader_update_utc_diff( r );
+}
+
+
+static void
+nmea_reader_set_callback( NmeaReader* r, gps_location_callback cb )
+{
+ r->callback = cb;
+ if (cb != NULL && r->fix.flags != 0) {
+ D("%s: sending latest fix to new callback", __FUNCTION__);
+ r->callback( &r->fix );
+ r->fix.flags = 0;
+ }
+}
+
+
+static int
+nmea_reader_update_time( NmeaReader* r, Token tok )
+{
+ int hour, minute;
+ double seconds;
+ struct tm tm;
+ time_t fix_time;
+
+ if (tok.p + 6 > tok.end)
+ return -1;
+
+ if (r->utc_year < 0) {
+ // no date yet, get current one
+ time_t now = time(NULL);
+ gmtime_r( &now, &tm );
+ r->utc_year = tm.tm_year + 1900;
+ r->utc_mon = tm.tm_mon + 1;
+ r->utc_day = tm.tm_mday;
+ }
+
+ hour = str2int(tok.p, tok.p+2);
+ minute = str2int(tok.p+2, tok.p+4);
+ seconds = str2float(tok.p+4, tok.end);
+
+ tm.tm_hour = hour;
+ tm.tm_min = minute;
+ tm.tm_sec = (int) seconds;
+ tm.tm_year = r->utc_year - 1900;
+ tm.tm_mon = r->utc_mon - 1;
+ tm.tm_mday = r->utc_day;
+
+ fix_time = mktime( &tm ) + r->utc_diff;
+ r->fix.timestamp = (long long)fix_time * 1000;
+ return 0;
+}
+
+static int
+nmea_reader_update_date( NmeaReader* r, Token date, Token time )
+{
+ Token tok = date;
+ int day, mon, year;
+
+ if (tok.p + 6 != tok.end) {
+ D("date not properly formatted: '%.*s'", tok.end-tok.p, tok.p);
+ return -1;
+ }
+ day = str2int(tok.p, tok.p+2);
+ mon = str2int(tok.p+2, tok.p+4);
+ year = str2int(tok.p+4, tok.p+6) + 2000;
+
+ if ((day|mon|year) < 0) {
+ D("date not properly formatted: '%.*s'", tok.end-tok.p, tok.p);
+ return -1;
+ }
+
+ r->utc_year = year;
+ r->utc_mon = mon;
+ r->utc_day = day;
+
+ return nmea_reader_update_time( r, time );
+}
+
+
+static double
+convert_from_hhmm( Token tok )
+{
+ double val = str2float(tok.p, tok.end);
+ int degrees = (int)(floor(val) / 100);
+ double minutes = val - degrees*100.;
+ double dcoord = degrees + minutes / 60.0;
+ return dcoord;
+}
+
+
+static int
+nmea_reader_update_latlong( NmeaReader* r,
+ Token latitude,
+ char latitudeHemi,
+ Token longitude,
+ char longitudeHemi )
+{
+ double lat, lon;
+ Token tok;
+
+ tok = latitude;
+ if (tok.p + 6 > tok.end) {
+ D("latitude is too short: '%.*s'", tok.end-tok.p, tok.p);
+ return -1;
+ }
+ lat = convert_from_hhmm(tok);
+ if (latitudeHemi == 'S')
+ lat = -lat;
+
+ tok = longitude;
+ if (tok.p + 6 > tok.end) {
+ D("longitude is too short: '%.*s'", tok.end-tok.p, tok.p);
+ return -1;
+ }
+ lon = convert_from_hhmm(tok);
+ if (longitudeHemi == 'W')
+ lon = -lon;
+
+ r->fix.flags |= GPS_LOCATION_HAS_LAT_LONG;
+ r->fix.latitude = lat;
+ r->fix.longitude = lon;
+ return 0;
+}
+
+
+static int
+nmea_reader_update_altitude( NmeaReader* r,
+ Token altitude,
+ Token units )
+{
+ double alt;
+ Token tok = altitude;
+
+ if (tok.p >= tok.end)
+ return -1;
+
+ r->fix.flags |= GPS_LOCATION_HAS_ALTITUDE;
+ r->fix.altitude = str2float(tok.p, tok.end);
+ return 0;
+}
+
+
+static int
+nmea_reader_update_bearing( NmeaReader* r,
+ Token bearing )
+{
+ double alt;
+ Token tok = bearing;
+
+ if (tok.p >= tok.end)
+ return -1;
+
+ r->fix.flags |= GPS_LOCATION_HAS_BEARING;
+ r->fix.bearing = str2float(tok.p, tok.end);
+ return 0;
+}
+
+
+static int
+nmea_reader_update_speed( NmeaReader* r,
+ Token speed )
+{
+ double alt;
+ Token tok = speed;
+
+ if (tok.p >= tok.end)
+ return -1;
+
+ r->fix.flags |= GPS_LOCATION_HAS_SPEED;
+ r->fix.speed = str2float(tok.p, tok.end);
+ return 0;
+}
+
+
+static void
+nmea_reader_parse( NmeaReader* r )
+{
+ /* we received a complete sentence, now parse it to generate
+ * a new GPS fix...
+ */
+ NmeaTokenizer tzer[1];
+ Token tok;
+
+ D("Received: '%.*s'", r->pos, r->in);
+ if (r->pos < 9) {
+ D("Too short. discarded.");
+ return;
+ }
+
+ nmea_tokenizer_init(tzer, r->in, r->in + r->pos);
+#if GPS_DEBUG
+ {
+ int n;
+ D("Found %d tokens", tzer->count);
+ for (n = 0; n < tzer->count; n++) {
+ Token tok = nmea_tokenizer_get(tzer,n);
+ D("%2d: '%.*s'", n, tok.end-tok.p, tok.p);
+ }
+ }
+#endif
+
+ tok = nmea_tokenizer_get(tzer, 0);
+ if (tok.p + 5 > tok.end) {
+ D("sentence id '%.*s' too short, ignored.", tok.end-tok.p, tok.p);
+ return;
+ }
+
+ // ignore first two characters.
+ tok.p += 2;
+ if ( !memcmp(tok.p, "GGA", 3) ) {
+ // GPS fix
+ Token tok_time = nmea_tokenizer_get(tzer,1);
+ Token tok_latitude = nmea_tokenizer_get(tzer,2);
+ Token tok_latitudeHemi = nmea_tokenizer_get(tzer,3);
+ Token tok_longitude = nmea_tokenizer_get(tzer,4);
+ Token tok_longitudeHemi = nmea_tokenizer_get(tzer,5);
+ Token tok_altitude = nmea_tokenizer_get(tzer,9);
+ Token tok_altitudeUnits = nmea_tokenizer_get(tzer,10);
+
+ nmea_reader_update_time(r, tok_time);
+ nmea_reader_update_latlong(r, tok_latitude,
+ tok_latitudeHemi.p[0],
+ tok_longitude,
+ tok_longitudeHemi.p[0]);
+ nmea_reader_update_altitude(r, tok_altitude, tok_altitudeUnits);
+
+ } else if ( !memcmp(tok.p, "GSA", 3) ) {
+ // do something ?
+ } else if ( !memcmp(tok.p, "RMC", 3) ) {
+ Token tok_time = nmea_tokenizer_get(tzer,1);
+ Token tok_fixStatus = nmea_tokenizer_get(tzer,2);
+ Token tok_latitude = nmea_tokenizer_get(tzer,3);
+ Token tok_latitudeHemi = nmea_tokenizer_get(tzer,4);
+ Token tok_longitude = nmea_tokenizer_get(tzer,5);
+ Token tok_longitudeHemi = nmea_tokenizer_get(tzer,6);
+ Token tok_speed = nmea_tokenizer_get(tzer,7);
+ Token tok_bearing = nmea_tokenizer_get(tzer,8);
+ Token tok_date = nmea_tokenizer_get(tzer,9);
+
+ D("in RMC, fixStatus=%c", tok_fixStatus.p[0]);
+ if (tok_fixStatus.p[0] == 'A')
+ {
+ nmea_reader_update_date( r, tok_date, tok_time );
+
+ nmea_reader_update_latlong( r, tok_latitude,
+ tok_latitudeHemi.p[0],
+ tok_longitude,
+ tok_longitudeHemi.p[0] );
+
+ nmea_reader_update_bearing( r, tok_bearing );
+ nmea_reader_update_speed ( r, tok_speed );
+ }
+ } else {
+ tok.p -= 2;
+ D("unknown sentence '%.*s", tok.end-tok.p, tok.p);
+ }
+ if (r->fix.flags != 0) {
+#if GPS_DEBUG
+ char temp[256];
+ char* p = temp;
+ char* end = p + sizeof(temp);
+ struct tm utc;
+
+ p += snprintf( p, end-p, "sending fix" );
+ if (r->fix.flags & GPS_LOCATION_HAS_LAT_LONG) {
+ p += snprintf(p, end-p, " lat=%g lon=%g", r->fix.latitude, r->fix.longitude);
+ }
+ if (r->fix.flags & GPS_LOCATION_HAS_ALTITUDE) {
+ p += snprintf(p, end-p, " altitude=%g", r->fix.altitude);
+ }
+ if (r->fix.flags & GPS_LOCATION_HAS_SPEED) {
+ p += snprintf(p, end-p, " speed=%g", r->fix.speed);
+ }
+ if (r->fix.flags & GPS_LOCATION_HAS_BEARING) {
+ p += snprintf(p, end-p, " bearing=%g", r->fix.bearing);
+ }
+ if (r->fix.flags & GPS_LOCATION_HAS_ACCURACY) {
+ p += snprintf(p,end-p, " accuracy=%g", r->fix.accuracy);
+ }
+ gmtime_r( (time_t*) &r->fix.timestamp, &utc );
+ p += snprintf(p, end-p, " time=%s", asctime( &utc ) );
+ D(temp);
+#endif
+ if (r->callback) {
+ r->callback( &r->fix );
+ r->fix.flags = 0;
+ }
+ else {
+ D("no callback, keeping data until needed !");
+ }
+ }
+}
+
+
+static void
+nmea_reader_addc( NmeaReader* r, int c )
+{
+ if (r->overflow) {
+ r->overflow = (c != '\n');
+ return;
+ }
+
+ if (r->pos >= (int) sizeof(r->in)-1 ) {
+ r->overflow = 1;
+ r->pos = 0;
+ return;
+ }
+
+ r->in[r->pos] = (char)c;
+ r->pos += 1;
+
+ if (c == '\n') {
+ nmea_reader_parse( r );
+ r->pos = 0;
+ }
+}
+
+
+/*****************************************************************/
+/*****************************************************************/
+/***** *****/
+/***** C O N N E C T I O N S T A T E *****/
+/***** *****/
+/*****************************************************************/
+/*****************************************************************/
+
+/* commands sent to the gps thread */
+enum {
+ CMD_QUIT = 0,
+ CMD_START = 1,
+ CMD_STOP = 2
+};
+
+
+/* this is the state of our connection to the qemu_gpsd daemon */
+typedef struct {
+ int init;
+ int fd;
+ GpsCallbacks callbacks;
+ pthread_t thread;
+ int control[2];
+ QemuChannel channel;
+} GpsState;
+
+static GpsState _gps_state[1];
+
+
+static void
+gps_state_done( GpsState* s )
+{
+ // tell the thread to quit, and wait for it
+ char cmd = CMD_QUIT;
+ void* dummy;
+ write( s->control[0], &cmd, 1 );
+ pthread_join(s->thread, &dummy);
+
+ // close the control socket pair
+ close( s->control[0] ); s->control[0] = -1;
+ close( s->control[1] ); s->control[1] = -1;
+
+ // close connection to the QEMU GPS daemon
+ close( s->fd ); s->fd = -1;
+ s->init = 0;
+}
+
+
+static void
+gps_state_start( GpsState* s )
+{
+ char cmd = CMD_START;
+ int ret;
+
+ do { ret=write( s->control[0], &cmd, 1 ); }
+ while (ret < 0 && errno == EINTR);
+
+ if (ret != 1)
+ D("%s: could not send CMD_START command: ret=%d: %s",
+ __FUNCTION__, ret, strerror(errno));
+}
+
+
+static void
+gps_state_stop( GpsState* s )
+{
+ char cmd = CMD_STOP;
+ int ret;
+
+ do { ret=write( s->control[0], &cmd, 1 ); }
+ while (ret < 0 && errno == EINTR);
+
+ if (ret != 1)
+ D("%s: could not send CMD_STOP command: ret=%d: %s",
+ __FUNCTION__, ret, strerror(errno));
+}
+
+
+static int
+epoll_register( int epoll_fd, int fd )
+{
+ struct epoll_event ev;
+ int ret, flags;
+
+ /* important: make the fd non-blocking */
+ flags = fcntl(fd, F_GETFL);
+ fcntl(fd, F_SETFL, flags | O_NONBLOCK);
+
+ ev.events = EPOLLIN;
+ ev.data.fd = fd;
+ do {
+ ret = epoll_ctl( epoll_fd, EPOLL_CTL_ADD, fd, &ev );
+ } while (ret < 0 && errno == EINTR);
+ return ret;
+}
+
+
+static int
+epoll_deregister( int epoll_fd, int fd )
+{
+ int ret;
+ do {
+ ret = epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd, NULL );
+ } while (ret < 0 && errno == EINTR);
+ return ret;
+}
+
+/* this is the main thread, it waits for commands from gps_state_start/stop and,
+ * when started, messages from the QEMU GPS daemon. these are simple NMEA sentences
+ * that must be parsed to be converted into GPS fixes sent to the framework
+ */
+static void*
+gps_state_thread( void* arg )
+{
+ GpsState* state = (GpsState*) arg;
+ NmeaReader reader[1];
+ int epoll_fd = epoll_create(2);
+ int started = 0;
+ int gps_fd = state->fd;
+ int control_fd = state->control[1];
+
+ nmea_reader_init( reader );
+
+ // register control file descriptors for polling
+ epoll_register( epoll_fd, control_fd );
+ epoll_register( epoll_fd, gps_fd );
+
+ D("gps thread running");
+
+ // now loop
+ for (;;) {
+ struct epoll_event events[2];
+ int ne, nevents;
+
+ nevents = epoll_wait( epoll_fd, events, 2, -1 );
+ if (nevents < 0) {
+ if (errno != EINTR)
+ LOGE("epoll_wait() unexpected error: %s", strerror(errno));
+ continue;
+ }
+ D("gps thread received %d events", nevents);
+ for (ne = 0; ne < nevents; ne++) {
+ if ((events[ne].events & (EPOLLERR|EPOLLHUP)) != 0) {
+ LOGE("EPOLLERR or EPOLLHUP after epoll_wait() !?");
+ goto Exit;
+ }
+ if ((events[ne].events & EPOLLIN) != 0) {
+ int fd = events[ne].data.fd;
+
+ if (fd == control_fd)
+ {
+ char cmd = 255;
+ int ret;
+ D("gps control fd event");
+ do {
+ ret = read( fd, &cmd, 1 );
+ } while (ret < 0 && errno == EINTR);
+
+ if (cmd == CMD_QUIT) {
+ D("gps thread quitting on demand");
+ goto Exit;
+ }
+ else if (cmd == CMD_START) {
+ if (!started) {
+ D("gps thread starting location_cb=%p", state->callbacks.location_cb);
+ started = 1;
+ nmea_reader_set_callback( reader, state->callbacks.location_cb );
+ }
+ }
+ else if (cmd == CMD_STOP) {
+ if (started) {
+ D("gps thread stopping");
+ started = 0;
+ nmea_reader_set_callback( reader, NULL );
+ }
+ }
+ }
+ else if (fd == gps_fd)
+ {
+ char buff[32];
+ D("gps fd event");
+ for (;;) {
+ int nn, ret;
+
+ ret = read( fd, buff, sizeof(buff) );
+ if (ret < 0) {
+ if (errno == EINTR)
+ continue;
+ if (errno != EWOULDBLOCK)
+ LOGE("error while reading from gps daemon socket: %s:", strerror(errno));
+ break;
+ }
+ D("received %d bytes: %.*s", ret, ret, buff);
+ for (nn = 0; nn < ret; nn++)
+ nmea_reader_addc( reader, buff[nn] );
+ }
+ D("gps fd event end");
+ }
+ else
+ {
+ LOGE("epoll_wait() returned unkown fd %d ?", fd);
+ }
+ }
+ }
+ }
+Exit:
+ return NULL;
+}
+
+
+static void
+gps_state_init( GpsState* state )
+{
+ state->init = 1;
+ state->control[0] = -1;
+ state->control[1] = -1;
+ state->fd = -1;
+
+ state->fd = qemu_channel_open( &state->channel,
+ QEMU_CHANNEL_NAME,
+ O_RDONLY );
+
+ if (state->fd < 0) {
+ D("no gps emulation detected");
+ return;
+ }
+
+ D("gps emulation will read from %s", device);
+
+ if ( socketpair( AF_LOCAL, SOCK_STREAM, 0, state->control ) < 0 ) {
+ LOGE("could not create thread control socket pair: %s", strerror(errno));
+ goto Fail;
+ }
+
+ if ( pthread_create( &state->thread, NULL, gps_state_thread, state ) != 0 ) {
+ LOGE("could not create gps thread: %s", strerror(errno));
+ goto Fail;
+ }
+
+ D("gps state initialized");
+ return;
+
+Fail:
+ gps_state_done( state );
+}
+
+
+/*****************************************************************/
+/*****************************************************************/
+/***** *****/
+/***** I N T E R F A C E *****/
+/***** *****/
+/*****************************************************************/
+/*****************************************************************/
+
+
+static int
+qemu_gps_init(GpsCallbacks* callbacks)
+{
+ GpsState* s = _gps_state;
+
+ if (!s->init)
+ gps_state_init(s);
+
+ if (s->fd < 0)
+ return -1;
+
+ s->callbacks = *callbacks;
+
+ return 0;
+}
+
+static void
+qemu_gps_cleanup(void)
+{
+ GpsState* s = _gps_state;
+
+ if (s->init)
+ gps_state_done(s);
+}
+
+
+static int
+qemu_gps_start()
+{
+ GpsState* s = _gps_state;
+
+ if (!s->init) {
+ D("%s: called with uninitialized state !!", __FUNCTION__);
+ return -1;
+ }
+
+ D("%s: called", __FUNCTION__);
+ gps_state_start(s);
+ return 0;
+}
+
+
+static int
+qemu_gps_stop()
+{
+ GpsState* s = _gps_state;
+
+ if (!s->init) {
+ D("%s: called with uninitialized state !!", __FUNCTION__);
+ return -1;
+ }
+
+ D("%s: called", __FUNCTION__);
+ gps_state_stop(s);
+ return 0;
+}
+
+
+static void
+qemu_gps_set_fix_frequency()
+{
+ GpsState* s = _gps_state;
+
+ if (!s->init) {
+ D("%s: called with uninitialized state !!", __FUNCTION__);
+ return;
+ }
+
+ D("%s: called", __FUNCTION__);
+ // FIXME - support fix_frequency
+}
+
+static int
+qemu_gps_inject_time(GpsUtcTime time, int64_t timeReference, int uncertainty)
+{
+ return 0;
+}
+
+static void
+qemu_gps_delete_aiding_data(GpsAidingData flags)
+{
+}
+
+static int qemu_gps_set_position_mode(GpsPositionMode mode, int fix_frequency)
+{
+ // FIXME - support fix_frequency
+ // only standalone supported for now.
+ if (mode != GPS_POSITION_MODE_STANDALONE)
+ return -1;
+ return 0;
+}
+
+static const void*
+qemu_gps_get_extension(const char* name)
+{
+ return NULL;
+}
+
+static const GpsInterface qemuGpsInterface = {
+ qemu_gps_init,
+ qemu_gps_start,
+ qemu_gps_stop,
+ qemu_gps_set_fix_frequency,
+ qemu_gps_cleanup,
+ qemu_gps_inject_time,
+ qemu_gps_delete_aiding_data,
+ qemu_gps_set_position_mode,
+ qemu_gps_get_extension,
+};
+
+const GpsInterface* gps_get_qemu_interface()
+{
+ return &qemuGpsInterface;
+}
+
diff --git a/include/hardware_legacy/AudioHardwareBase.h b/include/hardware_legacy/AudioHardwareBase.h
new file mode 100644
index 0000000..1065c39
--- /dev/null
+++ b/include/hardware_legacy/AudioHardwareBase.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2007 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 ANDROID_AUDIO_HARDWARE_BASE_H
+#define ANDROID_AUDIO_HARDWARE_BASE_H
+
+#include "hardware_legacy/AudioHardwareInterface.h"
+
+
+namespace android {
+
+// ----------------------------------------------------------------------------
+
+/**
+ * AudioHardwareBase is a convenient base class used for implementing the
+ * AudioHardwareInterface interface.
+ */
+class AudioHardwareBase : public AudioHardwareInterface
+{
+public:
+ AudioHardwareBase();
+ virtual ~AudioHardwareBase() { }
+
+ /**
+ * Audio routing methods. Routes defined in include/hardware_legacy/AudioSystem.h.
+ * Audio routes can be (ROUTE_EARPIECE | ROUTE_SPEAKER | ROUTE_BLUETOOTH
+ * | ROUTE_HEADSET)
+ *
+ * setRouting sets the routes for a mode. This is called at startup. It is
+ * also called when a new device is connected, such as a wired headset is
+ * plugged in or a Bluetooth headset is paired.
+ */
+ virtual status_t setRouting(int mode, uint32_t routes);
+
+ virtual status_t getRouting(int mode, uint32_t* routes);
+
+ /**
+ * setMode is called when the audio mode changes. NORMAL mode is for
+ * standard audio playback, RINGTONE when a ringtone is playing, and IN_CALL
+ * when a call is in progress.
+ */
+ virtual status_t setMode(int mode);
+ virtual status_t getMode(int* mode);
+
+ // Temporary interface, do not use
+ // TODO: Replace with a more generic key:value get/set mechanism
+ virtual status_t setParameter(const char* key, const char* value);
+
+ virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount);
+
+ /**This method dumps the state of the audio hardware */
+ virtual status_t dumpState(int fd, const Vector<String16>& args);
+
+protected:
+ int mMode;
+ uint32_t mRoutes[AudioSystem::NUM_MODES];
+};
+
+}; // namespace android
+
+#endif // ANDROID_AUDIO_HARDWARE_BASE_H
diff --git a/include/hardware_legacy/AudioHardwareInterface.h b/include/hardware_legacy/AudioHardwareInterface.h
new file mode 100644
index 0000000..0aa3a95
--- /dev/null
+++ b/include/hardware_legacy/AudioHardwareInterface.h
@@ -0,0 +1,240 @@
+/*
+ * Copyright (C) 2007 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 ANDROID_AUDIO_HARDWARE_INTERFACE_H
+#define ANDROID_AUDIO_HARDWARE_INTERFACE_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/Vector.h>
+#include <utils/String16.h>
+
+#include <media/IAudioFlinger.h>
+#include "media/AudioSystem.h"
+
+
+namespace android {
+
+// ----------------------------------------------------------------------------
+
+/**
+ * AudioStreamOut is the abstraction interface for the audio output hardware.
+ *
+ * It provides information about various properties of the audio output hardware driver.
+ */
+class AudioStreamOut {
+public:
+ virtual ~AudioStreamOut() = 0;
+
+ /** return audio sampling rate in hz - eg. 44100 */
+ virtual uint32_t sampleRate() const = 0;
+
+ /** returns size of output buffer - eg. 4800 */
+ virtual size_t bufferSize() const = 0;
+
+ /**
+ * return number of output audio channels.
+ * Acceptable values are 1 (mono) or 2 (stereo)
+ */
+ virtual int channelCount() const = 0;
+
+ /**
+ * return audio format in 8bit or 16bit PCM format -
+ * eg. AudioSystem:PCM_16_BIT
+ */
+ virtual int format() const = 0;
+
+ /**
+ * return the frame size (number of bytes per sample).
+ */
+ uint32_t frameSize() const { return channelCount()*((format()==AudioSystem::PCM_16_BIT)?sizeof(int16_t):sizeof(int8_t)); }
+
+ /**
+ * return the audio hardware driver latency in milli seconds.
+ */
+ virtual uint32_t latency() const = 0;
+
+ /**
+ * Use this method in situations where audio mixing is done in the
+ * hardware. This method serves as a direct interface with hardware,
+ * allowing you to directly set the volume as apposed to via the framework.
+ * This method might produce multiple PCM outputs or hardware accelerated
+ * codecs, such as MP3 or AAC.
+ */
+ virtual status_t setVolume(float volume) = 0;
+
+ /** write audio buffer to driver. Returns number of bytes written */
+ virtual ssize_t write(const void* buffer, size_t bytes) = 0;
+
+ /**
+ * Put the audio hardware output into standby mode. Returns
+ * status based on include/utils/Errors.h
+ */
+ virtual status_t standby() = 0;
+
+ /** dump the state of the audio output device */
+ virtual status_t dump(int fd, const Vector<String16>& args) = 0;
+};
+
+/**
+ * AudioStreamIn is the abstraction interface for the audio input hardware.
+ *
+ * It defines the various properties of the audio hardware input driver.
+ */
+class AudioStreamIn {
+public:
+ virtual ~AudioStreamIn() = 0;
+
+ /** return the input buffer size allowed by audio driver */
+ virtual size_t bufferSize() const = 0;
+
+ /** return the number of audio input channels */
+ virtual int channelCount() const = 0;
+
+ /**
+ * return audio format in 8bit or 16bit PCM format -
+ * eg. AudioSystem:PCM_16_BIT
+ */
+ virtual int format() const = 0;
+
+ /**
+ * return the frame size (number of bytes per sample).
+ */
+ uint32_t frameSize() const { return channelCount()*((format()==AudioSystem::PCM_16_BIT)?sizeof(int16_t):sizeof(int8_t)); }
+
+ /** set the input gain for the audio driver. This method is for
+ * for future use */
+ virtual status_t setGain(float gain) = 0;
+
+ /** read audio buffer in from audio driver */
+ virtual ssize_t read(void* buffer, ssize_t bytes) = 0;
+
+ /** dump the state of the audio input device */
+ virtual status_t dump(int fd, const Vector<String16>& args) = 0;
+
+ /**
+ * Put the audio hardware input into standby mode. Returns
+ * status based on include/utils/Errors.h
+ */
+ virtual status_t standby() = 0;
+
+};
+
+/**
+ * AudioHardwareInterface.h defines the interface to the audio hardware abstraction layer.
+ *
+ * The interface supports setting and getting parameters, selecting audio routing
+ * paths, and defining input and output streams.
+ *
+ * AudioFlinger initializes the audio hardware and immediately opens an output stream.
+ * You can set Audio routing to output to handset, speaker, Bluetooth, or a headset.
+ *
+ * The audio input stream is initialized when AudioFlinger is called to carry out
+ * a record operation.
+ */
+class AudioHardwareInterface
+{
+public:
+ /**
+ * check to see if the audio hardware interface has been initialized.
+ * return status based on values defined in include/utils/Errors.h
+ */
+ virtual status_t initCheck() = 0;
+
+ /** set the audio volume of a voice call. Range is between 0.0 and 1.0 */
+ virtual status_t setVoiceVolume(float volume) = 0;
+
+ /**
+ * set the audio volume for all audio activities other than voice call.
+ * Range between 0.0 and 1.0. If any value other than NO_ERROR is returned,
+ * the software mixer will emulate this capability.
+ */
+ virtual status_t setMasterVolume(float volume) = 0;
+
+ /**
+ * Audio routing methods. Routes defined in include/hardware_legacy/AudioSystem.h.
+ * Audio routes can be (ROUTE_EARPIECE | ROUTE_SPEAKER | ROUTE_BLUETOOTH
+ * | ROUTE_HEADSET)
+ *
+ * setRouting sets the routes for a mode. This is called at startup. It is
+ * also called when a new device is connected, such as a wired headset is
+ * plugged in or a Bluetooth headset is paired.
+ */
+ virtual status_t setRouting(int mode, uint32_t routes) = 0;
+
+ virtual status_t getRouting(int mode, uint32_t* routes) = 0;
+
+ /**
+ * setMode is called when the audio mode changes. NORMAL mode is for
+ * standard audio playback, RINGTONE when a ringtone is playing, and IN_CALL
+ * when a call is in progress.
+ */
+ virtual status_t setMode(int mode) = 0;
+ virtual status_t getMode(int* mode) = 0;
+
+ // mic mute
+ virtual status_t setMicMute(bool state) = 0;
+ virtual status_t getMicMute(bool* state) = 0;
+
+ // Temporary interface, do not use
+ // TODO: Replace with a more generic key:value get/set mechanism
+ virtual status_t setParameter(const char* key, const char* value) = 0;
+
+ // Returns audio input buffer size according to parameters passed or 0 if one of the
+ // parameters is not supported
+ virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount) = 0;
+
+ /** This method creates and opens the audio hardware output stream */
+ virtual AudioStreamOut* openOutputStream(
+ int format=0,
+ int channelCount=0,
+ uint32_t sampleRate=0,
+ status_t *status=0) = 0;
+
+ /** This method creates and opens the audio hardware input stream */
+ virtual AudioStreamIn* openInputStream(
+ int format,
+ int channelCount,
+ uint32_t sampleRate,
+ status_t *status,
+ AudioSystem::audio_in_acoustics acoustics) = 0;
+
+ /**This method dumps the state of the audio hardware */
+ virtual status_t dumpState(int fd, const Vector<String16>& args) = 0;
+
+ static AudioHardwareInterface* create();
+
+protected:
+ /**
+ * doRouting actually initiates the routing. A call to setRouting
+ * or setMode may result in a routing change. The generic logic calls
+ * doRouting when required. If the device has any special requirements these
+ * methods can be overriden.
+ */
+ virtual status_t doRouting() = 0;
+
+ virtual status_t dump(int fd, const Vector<String16>& args) = 0;
+};
+
+// ----------------------------------------------------------------------------
+
+extern "C" AudioHardwareInterface* createAudioHardware(void);
+
+}; // namespace android
+
+#endif // ANDROID_AUDIO_HARDWARE_INTERFACE_H
diff --git a/include/hardware_legacy/IMountService.h b/include/hardware_legacy/IMountService.h
new file mode 100644
index 0000000..b956ec8
--- /dev/null
+++ b/include/hardware_legacy/IMountService.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2007 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 ANDROID_HARDWARE_IMOUNTSERVICE_H
+#define ANDROID_HARDWARE_IMOUNTSERVICE_H
+
+#include <utils/IInterface.h>
+#include <utils/String16.h>
+
+namespace android {
+
+// ----------------------------------------------------------------------
+
+class IMountService : public IInterface
+{
+public:
+ DECLARE_META_INTERFACE(MountService);
+
+ /**
+ * Is mass storage support enabled?
+ */
+ virtual bool getMassStorageEnabled() = 0;
+
+ /**
+ * Enable or disable mass storage support.
+ */
+ virtual void setMassStorageEnabled(bool enabled) = 0;
+
+ /**
+ * Is mass storage connected?
+ */
+ virtual bool getMassStorageConnected() = 0;
+
+ /**
+ * Mount external storage at given mount point.
+ */
+ virtual void mountMedia(String16 mountPoint) = 0;
+
+ /**
+ * Safely unmount external storage at given mount point.
+ */
+ virtual void unmountMedia(String16 mountPoint) = 0;
+
+ /**
+ * Format external storage at given mount point.
+ */
+ virtual void formatMedia(String16 mountPoint) = 0;
+
+ /**
+ * Returns true if we're playing media notification sounds.
+ */
+ virtual bool getPlayNotificationSounds() = 0;
+
+ /**
+ * Sets whether or not media notification sounds are played.
+ */
+ virtual void setPlayNotificationSounds(bool enabled) = 0;
+};
+
+// ----------------------------------------------------------------------
+
+}; // namespace android
+
+#endif // ANDROID_HARDWARE_IMOUNTSERVICE_H
diff --git a/include/hardware_legacy/flashlight.h b/include/hardware_legacy/flashlight.h
new file mode 100644
index 0000000..d372307
--- /dev/null
+++ b/include/hardware_legacy/flashlight.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 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.
+ * 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 _HARDWARE_FLASHLIGHT_H
+#define _HARDWARE_FLASHLIGHT_H
+
+#if __cplusplus
+extern "C" {
+#endif
+
+int get_flashlight_enabled();
+int set_flashlight_enabled(int on);
+int enable_camera_flash(int milliseconds);
+
+#if __cplusplus
+} // extern "C"
+#endif
+
+#endif // _HARDWARE_FLASHLIGHT_H
diff --git a/include/hardware_legacy/gps.h b/include/hardware_legacy/gps.h
new file mode 100644
index 0000000..5f8740f
--- /dev/null
+++ b/include/hardware_legacy/gps.h
@@ -0,0 +1,261 @@
+/*
+ * Copyright (C) 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.
+ * 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 _HARDWARE_GPS_H
+#define _HARDWARE_GPS_H
+
+#include <stdint.h>
+
+#if __cplusplus
+extern "C" {
+#endif
+
+/** Milliseconds since January 1, 1970 */
+typedef int64_t GpsUtcTime;
+
+/** Maximum number of SVs for gps_sv_status_callback(). */
+#define GPS_MAX_SVS 32
+
+/** Requested mode for GPS operation. */
+typedef uint16_t GpsPositionMode;
+// IMPORTANT: Note that the following values must match
+// constants in GpsLocationProvider.java.
+/** Mode for running GPS standalone (no assistance). */
+#define GPS_POSITION_MODE_STANDALONE 0
+/** SUPL MS-Based mode. */
+#define GPS_POSITION_MODE_MS_BASED 1
+/** SUPL MS-Assisted mode. */
+#define GPS_POSITION_MODE_MS_ASSISTED 2
+
+/** GPS status event values. */
+typedef uint16_t GpsStatusValue;
+// IMPORTANT: Note that the following values must match
+// constants in GpsLocationProvider.java.
+/** GPS status unknown. */
+#define GPS_STATUS_NONE 0
+/** GPS has begun navigating. */
+#define GPS_STATUS_SESSION_BEGIN 1
+/** GPS has stopped navigating. */
+#define GPS_STATUS_SESSION_END 2
+/** GPS has powered on but is not navigating. */
+#define GPS_STATUS_ENGINE_ON 3
+/** GPS is powered off. */
+#define GPS_STATUS_ENGINE_OFF 4
+
+/** Flags to indicate which values are valid in a GpsLocation. */
+typedef uint16_t GpsLocationFlags;
+// IMPORTANT: Note that the following values must match
+// constants in GpsLocationProvider.java.
+/** GpsLocation has valid latitude and longitude. */
+#define GPS_LOCATION_HAS_LAT_LONG 0x0001
+/** GpsLocation has valid altitude. */
+#define GPS_LOCATION_HAS_ALTITUDE 0x0002
+/** GpsLocation has valid speed. */
+#define GPS_LOCATION_HAS_SPEED 0x0004
+/** GpsLocation has valid bearing. */
+#define GPS_LOCATION_HAS_BEARING 0x0008
+/** GpsLocation has valid accuracy. */
+#define GPS_LOCATION_HAS_ACCURACY 0x0010
+
+/** Flags used to specify which aiding data to delete
+ when calling delete_aiding_data(). */
+typedef uint16_t GpsAidingData;
+// IMPORTANT: Note that the following values must match
+// constants in GpsLocationProvider.java.
+#define GPS_DELETE_EPHEMERIS 0x0001
+#define GPS_DELETE_ALMANAC 0x0002
+#define GPS_DELETE_POSITION 0x0004
+#define GPS_DELETE_TIME 0x0008
+#define GPS_DELETE_IONO 0x0010
+#define GPS_DELETE_UTC 0x0020
+#define GPS_DELETE_HEALTH 0x0040
+#define GPS_DELETE_SVDIR 0x0080
+#define GPS_DELETE_SVSTEER 0x0100
+#define GPS_DELETE_SADATA 0x0200
+#define GPS_DELETE_RTI 0x0400
+#define GPS_DELETE_CELLDB_INFO 0x8000
+#define GPS_DELETE_ALL 0xFFFF
+
+/**
+ * Name for the GPS XTRA interface.
+ */
+#define GPS_XTRA_INTERFACE "gps-xtra"
+
+/**
+ * Name for the GPS SUPL interface.
+ */
+#define GPS_SUPL_INTERFACE "gps-supl"
+
+/** Represents a location. */
+typedef struct {
+ /** Contains GpsLocationFlags bits. */
+ uint16_t flags;
+ /** Represents latitude in degrees. */
+ double latitude;
+ /** Represents longitude in degrees. */
+ double longitude;
+ /** Represents altitude in meters above the WGS 84 reference
+ * ellipsoid. */
+ double altitude;
+ /** Represents speed in meters per second. */
+ float speed;
+ /** Represents heading in degrees. */
+ float bearing;
+ /** Represents expected accuracy in meters. */
+ float accuracy;
+ /** Timestamp for the location fix. */
+ GpsUtcTime timestamp;
+} GpsLocation;
+
+/** Represents the status. */
+typedef struct {
+ GpsStatusValue status;
+} GpsStatus;
+
+/** Represents SV information. */
+typedef struct {
+ /** Pseudo-random number for the SV. */
+ int prn;
+ /** Signal to noise ratio. */
+ float snr;
+ /** Elevation of SV in degrees. */
+ float elevation;
+ /** Azimuth of SV in degrees. */
+ float azimuth;
+} GpsSvInfo;
+
+/** Represents SV status. */
+typedef struct {
+ /** Number of SVs currently visible. */
+ int num_svs;
+
+ /** Contains an array of SV information. */
+ GpsSvInfo sv_list[GPS_MAX_SVS];
+
+ /** Represents a bit mask indicating which SVs
+ * have ephemeris data.
+ */
+ uint32_t ephemeris_mask;
+
+ /** Represents a bit mask indicating which SVs
+ * have almanac data.
+ */
+ uint32_t almanac_mask;
+
+ /**
+ * Represents a bit mask indicating which SVs
+ * were used for computing the most recent position fix.
+ */
+ uint32_t used_in_fix_mask;
+} GpsSvStatus;
+
+/** Callback with location information. */
+typedef void (* gps_location_callback)(GpsLocation* location);
+
+/** Callback with status information. */
+typedef void (* gps_status_callback)(GpsStatus* status);
+
+/** Callback with SV status information. */
+typedef void (* gps_sv_status_callback)(GpsSvStatus* sv_info);
+
+/** GPS callback structure. */
+typedef struct {
+ gps_location_callback location_cb;
+ gps_status_callback status_cb;
+ gps_sv_status_callback sv_status_cb;
+} GpsCallbacks;
+
+
+/** Represents the standard GPS interface. */
+typedef struct {
+ /**
+ * Opens the interface and provides the callback routines
+ * to the implemenation of this interface.
+ */
+ int (*init)( GpsCallbacks* callbacks );
+
+ /** Starts navigating. */
+ int (*start)( void );
+
+ /** Stops navigating. */
+ int (*stop)( void );
+
+ /** Sets requested frequency of fixes in seconds. */
+ void (*set_fix_frequency)( int frequency );
+
+ /** Closes the interface. */
+ void (*cleanup)( void );
+
+ /** Injects the current time. */
+ int (*inject_time)(GpsUtcTime time, int64_t timeReference,
+ int uncertainty);
+
+ /**
+ * Specifies that the next call to start will not use the
+ * information defined in the flags. GPS_DELETE_ALL is passed for
+ * a cold start.
+ */
+ void (*delete_aiding_data)(GpsAidingData flags);
+
+ /**
+ * fix_frequency represents the time between fixes in seconds.
+ * Set fix_frequency to zero for a single-shot fix.
+ */
+ int (*set_position_mode)(GpsPositionMode mode, int fix_frequency);
+
+ /** Get a pointer to extension information. */
+ const void* (*get_extension)(const char* name);
+} GpsInterface;
+
+/** Callback to request the client to download XTRA data.
+ The client should download XTRA data and inject it by calling
+ inject_xtra_data(). */
+typedef void (* gps_xtra_download_request)();
+
+/** Callback structure for the XTRA interface. */
+typedef struct {
+ gps_xtra_download_request download_request_cb;
+} GpsXtraCallbacks;
+
+/** Extended interface for XTRA support. */
+typedef struct {
+ /**
+ * Opens the XTRA interface and provides the callback routines
+ * to the implemenation of this interface.
+ */
+ int (*init)( GpsXtraCallbacks* callbacks );
+ /** Injects XTRA data into the GPS. */
+ int (*inject_xtra_data)( char* data, int length );
+} GpsXtraInterface;
+
+/** Returns the hardware GPS interface. */
+const GpsInterface* gps_get_hardware_interface();
+
+/**
+ * Returns the qemu emulated GPS interface.
+ */
+const GpsInterface* gps_get_qemu_interface();
+
+/**
+ * Returns the default GPS interface.
+ */
+const GpsInterface* gps_get_interface();
+
+#if __cplusplus
+} // extern "C"
+#endif
+
+#endif // _HARDWARE_GPS_H
diff --git a/include/hardware_legacy/led.h b/include/hardware_legacy/led.h
new file mode 100644
index 0000000..b5acb73
--- /dev/null
+++ b/include/hardware_legacy/led.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 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.
+ * 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 _HARDWARE_LED_H
+#define _HARDWARE_LED_H
+
+#if __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Changes the state of the LED.
+ *
+ * -# Turn on LED: Alpha != 0 and RBG != 0, onMS == 0 && offMS == 0.
+ * -# Blink LED: Alpha != 0 and RBG != 0, onMS != 0 && offMS != 0.
+ * -# Turn off LED: Alpha == 0 or RGB == 0.
+ *
+ * @param colorARGB represents the LED's color: Alpha=31:24, Red=23:16
+ * Green=15:8 Blue=7:0
+ * @param onMS represents the time the LED is on in milliseconds
+ * @param offMS represents the time the LED is off in milliseconds
+ *
+ * @return 0 if successful
+ */
+int set_led_state(unsigned colorARGB, int onMS, int offMS);
+
+#if __cplusplus
+} // extern "C"
+#endif
+
+#endif // _HARDWARE_LED_H
diff --git a/include/hardware_legacy/power.h b/include/hardware_legacy/power.h
new file mode 100644
index 0000000..993bca5
--- /dev/null
+++ b/include/hardware_legacy/power.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 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.
+ * 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 _HARDWARE_POWER_H
+#define _HARDWARE_POWER_H
+
+#include <stdint.h>
+
+#if __cplusplus
+extern "C" {
+#endif
+
+enum {
+ PARTIAL_WAKE_LOCK = 1, // the cpu stays on, but the screen is off
+ FULL_WAKE_LOCK = 2 // the screen is also on
+};
+
+// while you have a lock held, the device will stay on at least at the
+// level you request.
+int acquire_wake_lock(int lock, const char* id);
+int release_wake_lock(const char* id);
+
+
+enum {
+ KEYBOARD_LIGHT = 0x00000001,
+ SCREEN_LIGHT = 0x00000002,
+ BUTTON_LIGHT = 0x00000004,
+};
+
+// set the lights identified in mask to the brightness specified
+// in value. for example
+// set_light_brightness(SCREEN_LIGHT | KEYBOARD_LIGHT, 200);
+// sets the screen and keyboard lights to brightness 200
+int set_light_brightness(unsigned int mask, unsigned int brightness);
+
+// true if you want the screen on, false if you want it off
+int set_screen_state(int on);
+
+// set how long to stay awake after the last user activity in seconds
+int set_last_user_activity_timeout(int64_t delay);
+
+
+#if __cplusplus
+} // extern "C"
+#endif
+
+#endif // _HARDWARE_POWER_H
diff --git a/include/hardware_legacy/qemu_tracing.h b/include/hardware_legacy/qemu_tracing.h
new file mode 100644
index 0000000..645a0be
--- /dev/null
+++ b/include/hardware_legacy/qemu_tracing.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 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.
+ * 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 _HARDWARE_QEMU_TRACING_H
+#define _HARDWARE_QEMU_TRACING_H
+
+#if __cplusplus
+extern "C" {
+#endif
+
+int qemu_start_tracing();
+int qemu_stop_tracing();
+int qemu_add_mapping(unsigned int addr, const char *name);
+int qemu_remove_mapping(unsigned int addr);
+
+#if __cplusplus
+} // extern "C"
+#endif
+
+#endif // _HARDWARE_QEMU_TRACING_H
diff --git a/include/hardware_legacy/uevent.h b/include/hardware_legacy/uevent.h
new file mode 100644
index 0000000..7a5ce58
--- /dev/null
+++ b/include/hardware_legacy/uevent.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 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.
+ * 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 _HARDWARE_UEVENT_H
+#define _HARDWARE_UEVENT_H
+
+#if __cplusplus
+extern "C" {
+#endif
+
+int uevent_init();
+int uevent_next_event(char* buffer, int buffer_length);
+
+#if __cplusplus
+} // extern "C"
+#endif
+
+#endif // _HARDWARE_UEVENT_H
diff --git a/include/hardware_legacy/vibrator.h b/include/hardware_legacy/vibrator.h
new file mode 100644
index 0000000..15fd942
--- /dev/null
+++ b/include/hardware_legacy/vibrator.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 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.
+ * 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 _HARDWARE_VIBRATOR_H
+#define _HARDWARE_VIBRATOR_H
+
+#if __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Turn on vibrator
+ *
+ * @param timeout_ms number of milliseconds to vibrate
+ *
+ * @return 0 if successful, -1 if error
+ */
+int vibrator_on(int timeout_ms);
+
+/**
+ * Turn off vibrator
+ *
+ * @return 0 if successful, -1 if error
+ */
+int vibrator_off();
+
+#if __cplusplus
+} // extern "C"
+#endif
+
+#endif // _HARDWARE_VIBRATOR_H
diff --git a/include/hardware_legacy/wifi.h b/include/hardware_legacy/wifi.h
new file mode 100644
index 0000000..23cc92a
--- /dev/null
+++ b/include/hardware_legacy/wifi.h
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 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.
+ * 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 _WIFI_H
+#define _WIFI_H
+
+#if __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Load the Wi-Fi driver.
+ *
+ * @return 0 on success, < 0 on failure.
+ */
+int wifi_load_driver();
+
+/**
+ * Unload the Wi-Fi driver.
+ *
+ * @return 0 on success, < 0 on failure.
+ */
+int wifi_unload_driver();
+
+/**
+ * Start supplicant.
+ *
+ * @return 0 on success, < 0 on failure.
+ */
+int wifi_start_supplicant();
+
+/**
+ * Stop supplicant.
+ *
+ * @return 0 on success, < 0 on failure.
+ */
+int wifi_stop_supplicant();
+
+/**
+ * Open a connection to supplicant.
+ *
+ * @return 0 on success, < 0 on failure.
+ */
+int wifi_connect_to_supplicant();
+
+/**
+ * Close connection supplicant.
+ *
+ * @return 0 on success, < 0 on failure.
+ */
+void wifi_close_supplicant_connection();
+
+/**
+ * wifi_wait_for_event() performs a blocking call to
+ * get a Wi-Fi event and returns a string representing
+ * a Wi-Fi event when it occurs.
+ *
+ * @param buf is the buffer that receives the event
+ * @param len is the maximum length of the buffer
+ *
+ * @returns number of bytes in buffer, 0 if no
+ * event (for instance, no connection), and less than 0
+ * if there is an error.
+ */
+int wifi_wait_for_event(char *buf, size_t len);
+
+/**
+ * wifi_command() issues a command to the Wi-Fi driver.
+ *
+ * Android extends the standard commands listed at
+ * /link http://hostap.epitest.fi/wpa_supplicant/devel/ctrl_iface_page.html
+ * to include support for sending commands to the driver:
+ *
+ * <table border="2" cellspacing="2" cellpadding="2">
+ * <tr>
+ * <td><strong>Command / Command summary</strong></td>
+ * <td><strong>Form of Response</strong></td>
+ * <td><strong>Processing</strong></td>
+ * </tr>
+ * <tr>
+ * <td>DRIVER START<BR>&nbsp;&nbsp;Turn on Wi-Fi Hardware</td>
+ * <td>OK if successful</td>
+ * <td>OK ? true : false</td>
+ * </tr>
+ * <tr>
+ * <td>DRIVER STOP<BR>&nbsp;&nbsp;Turn off Wi-Fi hardware</td>
+ * <td>OK if successful</td>
+ * <td>OK ? true : false</td>
+ * </tr>
+ * <tr>
+ * <td>DRIVER RSSI<BR>&nbsp;&nbsp;Return received signal strength indicator in -db for current AP</td>
+ * <td>&lt;ssid&gt; Rssi xx</td>
+ * <td>%*s %*s %d", &rssi</td>
+ * </tr>
+ * <tr>
+ * <td>DRIVER LINKSPEED<BR>&nbsp;&nbsp;Return link speed in MBPS</td>
+ * <td>LinkSpeed xx</td>
+ * <td>%*s %d", &linkspd</td>
+ * </tr>
+ * <tr>
+ * <td>DRIVER MACADDR<BR>&nbsp;&nbsp;Return mac address of the station</td>
+ * <td>Macaddr = xx.xx.xx.xx.xx.xx</td>
+ * <td>"%*s = %s", &macadr</td>
+ * </tr>
+ * <tr>
+ * <td>DRIVER SCAN-ACTIVE<BR>&nbsp;&nbsp;Set scan type to active</td>
+ * <td>"OK" if successful</td>
+ * <td>"OK" ? true : false</td>
+ * </tr>
+ * <tr>
+ * <td>DRIVER SCAN-PASSIVE<BR>&nbsp;&nbsp;Set scan type to passive</td>
+ * <td>"OK" if successful</td>
+ * <td>"OK" ? true : false</td>
+ * </tr>
+ * </table>
+ *
+ * See libs/android_runtime/android_net_wifi_Wifi.cpp for more information
+ * describing how these and other commands are invoked.
+ *
+ * @param command is the string command
+ * @param reply is a buffer to receive a reply string
+ * @param reply_len on entry, this is the maximum length of
+ * the reply buffer. On exit, the number of
+ * bytes in the reply buffer.
+ *
+ * @return 0 if successful, < 0 if an error.
+ */
+int wifi_command(const char *command, char *reply, size_t *reply_len);
+
+/**
+ * do_dhcp_request() issues a dhcp request and returns the acquired
+ * information.
+ *
+ * All IPV4 addresses/mask are in network byte order.
+ *
+ * @param ipaddr return the assigned IPV4 address
+ * @param gateway return the gateway being used
+ * @param mask return the IPV4 mask
+ * @param dns1 return the IPV4 address of a DNS server
+ * @param dns2 return the IPV4 address of a DNS server
+ * @param server return the IPV4 address of DHCP server
+ * @param lease return the length of lease in seconds.
+ *
+ * @return 0 if successful, < 0 if error.
+ */
+int do_dhcp_request(int *ipaddr, int *gateway, int *mask,
+ int *dns1, int *dns2, int *server, int *lease);
+
+/**
+ * Return the error string of the last do_dhcp_request().
+ */
+const char *get_dhcp_error_string();
+
+#if __cplusplus
+}; // extern "C"
+#endif
+
+#endif // _WIFI_H
diff --git a/led/Android.mk b/led/Android.mk
new file mode 100644
index 0000000..a0326b9
--- /dev/null
+++ b/led/Android.mk
@@ -0,0 +1,15 @@
+# Copyright 2006 The Android Open Source Project
+
+ifeq ($(TARGET_DEVICE),sooner)
+LOCAL_SRC_FILES += led/led_sardine.c
+LOCAL_CFLAGS += -DCONFIG_LED_SARDINE
+endif
+ifneq (,$(filter $(TARGET_DEVICE),dream sapphire))
+LOCAL_SRC_FILES += led/led_trout.c
+LOCAL_CFLAGS += -DCONFIG_LED_TROUT
+endif
+ifeq ($(QEMU_HARDWARE),true)
+LOCAL_CFLAGS += -DCONFIG_LED_QEMU
+endif
+LOCAL_SRC_FILES += led/led_stub.c
+
diff --git a/led/led_qemu.c b/led/led_qemu.c
new file mode 100644
index 0000000..c98402b
--- /dev/null
+++ b/led/led_qemu.c
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 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.
+ * 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 "qemu.h"
+
+int
+qemu_set_led_state(unsigned color, int on, int off)
+{
+ qemu_control_command( "set_led_state:%08x:%d:%d", color, on, off );
+ return 0;
+}
diff --git a/led/led_sardine.c b/led/led_sardine.c
new file mode 100644
index 0000000..b6a508a
--- /dev/null
+++ b/led/led_sardine.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 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.
+ * 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 <hardware_legacy/led.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdio.h>
+
+const char* const CADENCE_FILE = "/sys/class/leds/left/cadence";
+const char* const COLOR_FILE = "/sys/class/leds/left/color";
+const char* const BT_WIFI_FILE = "/sys/class/leds/right/brightness";
+
+static int
+write_string(const char* file, const char* string, int len)
+{
+ int fd;
+ ssize_t amt;
+
+ fd = open(file, O_RDWR);
+ if (fd < 0) {
+ return errno;
+ }
+
+ amt = write(fd, string, len+1);
+
+ close(fd);
+ return amt >= 0 ? 0 : errno;
+}
+
+int sardine_set_led_state(unsigned colorARGB, int onMS, int offMS)
+{
+ int len;
+ char buf[30];
+ int red, green, color;
+
+ // alpha of 0 or color of 0 (ignoring blue) means off
+ if ((colorARGB & 0xff000000) == 0 || (colorARGB & 0x00ffff00) == 0) {
+ onMS = 0;
+ offMS = 0;
+ }
+
+ // blue means green
+ if ((colorARGB & 0x00ffff00) == 0 && (colorARGB & 0x000000ff) != 0) {
+ colorARGB |= (colorARGB & 0x000000ff) << 8;
+ }
+
+ // ===== color =====
+ // this color conversion isn't really correct, but it's better to
+ // have the light come bright on when asked for low intensity than to
+ // not come on at all. we have no blue
+ red = (colorARGB & 0x00ff0000) ? 1 : 0;
+ green = (colorARGB & 0x0000ff00) ? 2 : 0;
+ color = (red | green) - 1;
+
+ len = sprintf(buf, "%d", color);
+ write_string(COLOR_FILE, buf, len);
+
+ // ===== color =====
+ len = sprintf(buf, "%d,%d", onMS, offMS);
+ write_string(CADENCE_FILE, buf, len);
+
+ return 0;
+}
diff --git a/led/led_stub.c b/led/led_stub.c
new file mode 100644
index 0000000..6b3b3da
--- /dev/null
+++ b/led/led_stub.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 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.
+ * 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 <hardware_legacy/led.h>
+
+typedef int (*LedFunc)(unsigned, int, int);
+
+#ifdef CONFIG_LED_SARDINE
+extern int sardine_set_led_state(unsigned, int, int);
+# define HW_LED_FUNC sardine_set_led_state
+#endif
+
+#ifdef CONFIG_LED_TROUT
+extern int trout_set_led_state(unsigned, int, int);
+# define HW_LED_FUNC trout_set_led_state
+#endif
+
+#ifdef CONFIG_LED_QEMU
+#include "qemu.h"
+static int
+qemu_set_led_state(unsigned color, int on, int off)
+{
+ qemu_control_command( "set_led_state:%08x:%d:%d", color, on, off );
+ return 0;
+}
+#endif
+
+int
+set_led_state(unsigned color, int on, int off)
+{
+#ifdef CONFIG_LED_QEMU
+ QEMU_FALLBACK(set_led_state(color,on,off));
+#endif
+#ifdef HW_LED_FUNC
+ return HW_LED_FUNC(color, on, off);
+#else
+ return 0;
+#endif
+}
diff --git a/led/led_trout.c b/led/led_trout.c
new file mode 100644
index 0000000..b129ec9
--- /dev/null
+++ b/led/led_trout.c
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 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.
+ * 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 <hardware_legacy/led.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdio.h>
+
+#define LOG_TAG "LED"
+#include <utils/Log.h>
+
+const char* const AMBER_BRIGHTNESS_FILE = "/sys/class/leds/amber/brightness";
+const char* const RED_BRIGHTNESS_FILE = "/sys/class/leds/red/brightness";
+const char* const GREEN_BRIGHTNESS_FILE = "/sys/class/leds/green/brightness";
+const char* const BLUE_BRIGHTNESS_FILE = "/sys/class/leds/blue/brightness";
+const char* const BLINK_ENABLE_FILE = "/sys/class/leds/red/device/blink";
+const char* const BLINK_FREQ_FILE = "/sys/class/leds/red/device/grpfreq";
+const char* const BLINK_PWM_FILE = "/sys/class/leds/red/device/grppwm";
+
+static int
+write_string(const char* file, const char* string, int len)
+{
+ int fd;
+ ssize_t amt;
+
+ fd = open(file, O_RDWR);
+ if (fd < 0) {
+ LOGE("open failed errno: %d\n", errno);
+ return errno;
+ }
+
+ amt = write(fd, string, len);
+ if (amt < 0) {
+ LOGE("write failed errno: %d\n", errno);
+ }
+
+ close(fd);
+ return amt >= 0 ? 0 : errno;
+}
+
+int trout_set_led_state(unsigned colorARGB, int onMS, int offMS)
+{
+ int len;
+ char buf[30];
+ int alpha, red, green, blue;
+ int blink, freq, pwm;
+
+ LOGV("set_led_state colorARGB=%08X, onMS=%d, offMS=%d\n", colorARGB, onMS, offMS);
+
+ // alpha of 0 or color of 0 means off
+ if ((colorARGB & 0xff000000) == 0 || (colorARGB & 0x00ffffff) == 0) {
+ onMS = 0;
+ offMS = 0;
+ }
+
+ red = (colorARGB >> 16) & 0xFF;
+ green = (colorARGB >> 8) & 0xFF;
+ blue = colorARGB & 0xFF;
+
+ len = sprintf(buf, "%d", red);
+ write_string(RED_BRIGHTNESS_FILE, buf, len);
+ len = sprintf(buf, "%d", green);
+ write_string(GREEN_BRIGHTNESS_FILE, buf, len);
+ len = sprintf(buf, "%d", blue);
+ write_string(BLUE_BRIGHTNESS_FILE, buf, len);
+
+ if (onMS > 0 && offMS > 0) {
+ int totalMS = onMS + offMS;
+
+ // the LED appears to blink about once per second if freq is 20
+ // 1000ms / 20 = 50
+ freq = totalMS / 50;
+ // pwm specifies the ratio of ON versus OFF
+ // pwm = 0 -> always off
+ // pwm = 255 => always on
+ pwm = (onMS * 255) / totalMS;
+
+ // the low 4 bits are ignored, so round up if necessary
+ if (pwm > 0 && pwm < 16)
+ pwm = 16;
+
+ blink = 1;
+ } else {
+ blink = 0;
+ freq = 0;
+ pwm = 0;
+ }
+
+ if (blink) {
+ len = sprintf(buf, "%d", freq);
+ write_string(BLINK_FREQ_FILE, buf, len);
+ len = sprintf(buf, "%d", pwm);
+ write_string(BLINK_PWM_FILE, buf, len);
+ }
+
+ len = sprintf(buf, "%d", blink);
+ write_string(BLINK_ENABLE_FILE, buf, len);
+
+ return 0;
+}
diff --git a/mount/Android.mk b/mount/Android.mk
new file mode 100644
index 0000000..1f4c1fa
--- /dev/null
+++ b/mount/Android.mk
@@ -0,0 +1,4 @@
+# Copyright 2007 The Android Open Source Project
+
+LOCAL_SRC_FILES += mount/IMountService.cpp
+
diff --git a/mount/IMountService.cpp b/mount/IMountService.cpp
new file mode 100644
index 0000000..d747ba2
--- /dev/null
+++ b/mount/IMountService.cpp
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 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.
+ * 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 <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Parcel.h>
+
+#include <hardware_legacy/IMountService.h>
+
+namespace android {
+
+enum {
+ GET_MASS_STORAGE_ENABLED_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
+ SET_MASS_STORAGE_ENABLED_TRANSACTION,
+ GET_MASS_STORAGE_CONNECTED_TRANSACTION,
+ MOUNT_MEDIA_TRANSACTION,
+ UNMOUNT_MEDIA_TRANSACTION,
+ FORMAT_MEDIA_TRANSACTION,
+ SET_PLAY_NOTIFICATION_SOUNDS_TRANSACTION,
+ GET_PLAY_NOTIFICATION_SOUNDS_TRANSACTION,
+};
+
+class BpMountService : public BpInterface<IMountService>
+{
+public:
+ BpMountService(const sp<IBinder>& impl)
+ : BpInterface<IMountService>(impl)
+ {
+ }
+
+ virtual bool getMassStorageEnabled()
+ {
+ uint32_t n;
+ Parcel data, reply;
+ data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
+ remote()->transact(GET_MASS_STORAGE_ENABLED_TRANSACTION, data, &reply);
+ return reply.readInt32();
+ }
+
+ virtual void setMassStorageEnabled(bool enabled)
+ {
+ Parcel data, reply;
+ data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
+ data.writeInt32(enabled ? 1 : 0);
+ remote()->transact(SET_MASS_STORAGE_ENABLED_TRANSACTION, data, &reply);
+ }
+
+ virtual bool getMassStorageConnected()
+ {
+ uint32_t n;
+ Parcel data, reply;
+ data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
+ remote()->transact(GET_MASS_STORAGE_CONNECTED_TRANSACTION, data, &reply);
+ return reply.readInt32();
+ }
+
+ virtual void mountMedia(String16 mountPoint)
+ {
+ Parcel data, reply;
+ data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
+ data.writeString16(mountPoint);
+ remote()->transact(MOUNT_MEDIA_TRANSACTION, data, &reply);
+ }
+
+ virtual void unmountMedia(String16 mountPoint)
+ {
+ Parcel data, reply;
+ data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
+ data.writeString16(mountPoint);
+ remote()->transact(UNMOUNT_MEDIA_TRANSACTION, data, &reply);
+ }
+
+ virtual void formatMedia(String16 mountPoint)
+ {
+ Parcel data, reply;
+ data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
+ data.writeString16(mountPoint);
+ remote()->transact(FORMAT_MEDIA_TRANSACTION, data, &reply);
+ }
+
+ virtual bool getPlayNotificationSounds()
+ {
+ uint32_t n;
+ Parcel data, reply;
+ data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
+ remote()->transact(GET_PLAY_NOTIFICATION_SOUNDS_TRANSACTION, data, &reply);
+ return reply.readInt32();
+ }
+
+ virtual void setPlayNotificationSounds(bool enabled)
+ {
+ Parcel data, reply;
+ data.writeInterfaceToken(IMountService::getInterfaceDescriptor());
+ data.writeInt32(enabled ? 1 : 0);
+ remote()->transact(SET_PLAY_NOTIFICATION_SOUNDS_TRANSACTION, data, &reply);
+ }
+
+
+};
+
+IMPLEMENT_META_INTERFACE(MountService, "android.os.IMountService");
+
+
+};
diff --git a/power/Android.mk b/power/Android.mk
new file mode 100644
index 0000000..a524d0e
--- /dev/null
+++ b/power/Android.mk
@@ -0,0 +1,8 @@
+# Copyright 2006 The Android Open Source Project
+
+LOCAL_SRC_FILES += power/power.c
+
+ifeq ($(QEMU_HARDWARE),true)
+ LOCAL_SRC_FILES += power/power_qemu.c
+ LOCAL_CFLAGS += -DQEMU_POWER=1
+endif
diff --git a/power/power.c b/power/power.c
new file mode 100644
index 0000000..1130dfa
--- /dev/null
+++ b/power/power.c
@@ -0,0 +1,238 @@
+/*
+ * Copyright (C) 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.
+ * 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 <hardware_legacy/power.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <sys/time.h>
+#include <time.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <pthread.h>
+
+#define LOG_TAG "power"
+#include <utils/Log.h>
+
+#include "qemu.h"
+#ifdef QEMU_POWER
+#include "power_qemu.h"
+#endif
+
+enum {
+ ACQUIRE_PARTIAL_WAKE_LOCK = 0,
+ RELEASE_WAKE_LOCK,
+ REQUEST_STATE,
+ OUR_FD_COUNT
+};
+
+const char * const OLD_PATHS[] = {
+ "/sys/android_power/acquire_partial_wake_lock",
+ "/sys/android_power/release_wake_lock",
+ "/sys/android_power/request_state"
+};
+
+const char * const NEW_PATHS[] = {
+ "/sys/power/wake_lock",
+ "/sys/power/wake_unlock",
+ "/sys/power/state"
+};
+
+const char * const AUTO_OFF_TIMEOUT_DEV = "/sys/android_power/auto_off_timeout";
+
+const char * const LCD_BACKLIGHT = "/sys/class/leds/lcd-backlight/brightness";
+const char * const BUTTON_BACKLIGHT = "/sys/class/leds/button-backlight/brightness";
+const char * const KEYBOARD_BACKLIGHT = "/sys/class/leds/keyboard-backlight/brightness";
+
+//XXX static pthread_once_t g_initialized = THREAD_ONCE_INIT;
+static int g_initialized = 0;
+static int g_fds[OUR_FD_COUNT];
+static int g_error = 1;
+
+static const char *off_state = "mem";
+static const char *on_state = "on";
+
+static int64_t systemTime()
+{
+ struct timespec t;
+ t.tv_sec = t.tv_nsec = 0;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ return t.tv_sec*1000000000LL + t.tv_nsec;
+}
+
+static int
+open_file_descriptors(const char * const paths[])
+{
+ int i;
+ for (i=0; i<OUR_FD_COUNT; i++) {
+ int fd = open(paths[i], O_RDWR);
+ if (fd < 0) {
+ fprintf(stderr, "fatal error opening \"%s\"\n", paths[i]);
+ g_error = errno;
+ return -1;
+ }
+ g_fds[i] = fd;
+ }
+
+ g_error = 0;
+ return 0;
+}
+
+static inline void
+initialize_fds(void)
+{
+ // XXX: should be this:
+ //pthread_once(&g_initialized, open_file_descriptors);
+ // XXX: not this:
+ if (g_initialized == 0) {
+ if(open_file_descriptors(NEW_PATHS) < 0) {
+ open_file_descriptors(OLD_PATHS);
+ on_state = "wake";
+ off_state = "standby";
+ }
+ g_initialized = 1;
+ }
+}
+
+int
+acquire_wake_lock(int lock, const char* id)
+{
+ initialize_fds();
+
+// LOGI("acquire_wake_lock lock=%d id='%s'\n", lock, id);
+
+ if (g_error) return g_error;
+
+ int fd;
+
+ if (lock == PARTIAL_WAKE_LOCK) {
+ fd = g_fds[ACQUIRE_PARTIAL_WAKE_LOCK];
+ }
+ else {
+ return EINVAL;
+ }
+
+ return write(fd, id, strlen(id));
+}
+
+int
+release_wake_lock(const char* id)
+{
+ initialize_fds();
+
+// LOGI("release_wake_lock id='%s'\n", id);
+
+ if (g_error) return g_error;
+
+ ssize_t len = write(g_fds[RELEASE_WAKE_LOCK], id, strlen(id));
+ return len >= 0;
+}
+
+int
+set_last_user_activity_timeout(int64_t delay)
+{
+// LOGI("set_last_user_activity_timeout delay=%d\n", ((int)(delay)));
+
+ int fd = open(AUTO_OFF_TIMEOUT_DEV, O_RDWR);
+ if (fd >= 0) {
+ char buf[32];
+ ssize_t len;
+ len = sprintf(buf, "%d", ((int)(delay)));
+ len = write(fd, buf, len);
+ close(fd);
+ return 0;
+ } else {
+ return errno;
+ }
+}
+
+static void
+set_a_light(const char* path, int value)
+{
+ int fd;
+ static int already_warned = 0;
+
+ // LOGI("set_a_light(%s, %d)\n", path, value);
+
+ fd = open(path, O_RDWR);
+ if (fd >= 0) {
+ char buffer[20];
+ int bytes = sprintf(buffer, "%d\n", value);
+ write(fd, buffer, bytes);
+ close(fd);
+ } else {
+ if (already_warned == 0) {
+ LOGE("set_a_light failed to open %s\n", path);
+ already_warned = 1;
+ }
+ }
+}
+
+int
+set_light_brightness(unsigned int mask, unsigned int brightness)
+{
+ QEMU_FALLBACK(set_light_brightness(mask,brightness));
+
+ initialize_fds();
+
+// LOGI("set_light_brightness mask=0x%08x brightness=%d now=%lld g_error=%s\n",
+// mask, brightness, systemTime(), strerror(g_error));
+
+ if (mask & KEYBOARD_LIGHT) {
+ set_a_light(KEYBOARD_BACKLIGHT, brightness);
+ }
+
+ if (mask & SCREEN_LIGHT) {
+ set_a_light(LCD_BACKLIGHT, brightness);
+ }
+
+ if (mask & BUTTON_LIGHT) {
+ set_a_light(BUTTON_BACKLIGHT, brightness);
+ }
+
+ return 0;
+}
+
+
+int
+set_screen_state(int on)
+{
+ QEMU_FALLBACK(set_screen_state(on));
+
+ //LOGI("*** set_screen_state %d", on);
+
+ initialize_fds();
+
+ //LOGI("go_to_sleep eventTime=%lld now=%lld g_error=%s\n", eventTime,
+ // systemTime(), strerror(g_error));
+
+ if (g_error) return g_error;
+
+ char buf[32];
+ int len;
+ if(on)
+ len = sprintf(buf, on_state);
+ else
+ len = sprintf(buf, off_state);
+ len = write(g_fds[REQUEST_STATE], buf, len);
+ if(len < 0) {
+ LOGE("Failed setting last user activity: g_error=%d\n", g_error);
+ }
+ return 0;
+}
diff --git a/power/power_qemu.c b/power/power_qemu.c
new file mode 100644
index 0000000..d400082
--- /dev/null
+++ b/power/power_qemu.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 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.
+ * 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 "qemu.h"
+#include "power_qemu.h"
+#include <fcntl.h>
+#include <errno.h>
+#include <hardware_legacy/power.h>
+
+static void
+set_a_light(const char* name, unsigned brightness)
+{
+ qemu_control_command( "power:light:brightness:%s:%d",
+ name, brightness );
+}
+
+int
+qemu_set_light_brightness(unsigned int mask, unsigned int brightness)
+{
+ if (mask & KEYBOARD_LIGHT) {
+ set_a_light("keyboard_backlight", brightness);
+ }
+ if (mask & SCREEN_LIGHT) {
+ set_a_light("lcd_backlight", brightness);
+ }
+ if (mask & BUTTON_LIGHT) {
+ set_a_light("button_backlight", brightness);
+ }
+ return 0;
+}
+
+
+int
+qemu_set_screen_state(int on)
+{
+ qemu_control_command( "power:screen_state:%s", on ? "wake" : "standby" );
+ return 0;
+}
+
diff --git a/power/power_qemu.h b/power/power_qemu.h
new file mode 100644
index 0000000..3004950
--- /dev/null
+++ b/power/power_qemu.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 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.
+ * 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 _power_qemu_h
+#define _power_qemu_h
+
+#include <stdint.h>
+
+extern int
+qemu_set_light_brightness(unsigned int mask, unsigned int brightness);
+
+extern int
+qemu_set_screen_state(int on);
+
+#endif /* _power_qemu_h */
diff --git a/qemu.h b/qemu.h
new file mode 100644
index 0000000..5fcbfa7
--- /dev/null
+++ b/qemu.h
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 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.
+ * 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 _libs_hardware_qemu_h
+#define _libs_hardware_qemu_h
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef QEMU_HARDWARE
+
+/* returns 1 iff we're running in the emulator */
+extern int qemu_check(void);
+
+/* a structure used to hold enough state to connect to a given
+ * QEMU communication channel, either through a qemud socket or
+ * a serial port.
+ *
+ * initialize the structure by zero-ing it out
+ */
+typedef struct {
+ char is_inited;
+ char is_available;
+ char is_qemud;
+ char is_tty;
+ char device[32];
+} QemuChannel;
+
+/* try to open a qemu communication channel.
+ * returns a file descriptor on success, or -1 in case of
+ * error.
+ *
+ * 'channel' must be a QemuChannel structure that is empty
+ * on the first call. You can call this function several
+ * time to re-open the channel using the same 'channel'
+ * object to speed things a bit.
+ */
+extern int qemu_channel_open( QemuChannel* channel,
+ const char* name,
+ int mode );
+
+/* create a command made of a 4-hexchar prefix followed
+ * by the content. the prefix contains the content's length
+ * in hexadecimal coding.
+ *
+ * 'buffer' must be at last 6 bytes
+ * returns -1 in case of overflow, or the command's total length
+ * otherwise (i.e. content length + 4)
+ */
+extern int qemu_command_format( char* buffer,
+ int buffer_size,
+ const char* format,
+ ... );
+
+/* directly sends a command through the 'control' channel.
+ * this will open the channel, send the formatted command, then
+ * close the channel automatically.
+ * returns 0 on success, or -1 on error.
+ */
+extern int qemu_control_command( const char* fmt, ... );
+
+/* sends a question to the control channel, then receive an answer in
+ * a user-allocated buffer. returns the lenght of the answer, or -1
+ * in case of error.
+ *
+ * 'question' *must* have been formatted through qemu_command_format
+ */
+extern int qemu_control_query( const char* question, int questionlen,
+ char* answer, int answersize );
+
+#endif /* QEMU_HARDWARE */
+
+/* use QEMU_FALLBACK(call) to call a QEMU-specific callback */
+/* use QEMU_FALLBACK_VOID(call) if the function returns void */
+#ifdef QEMU_HARDWARE
+# define QEMU_FALLBACK(x) \
+ do { \
+ if (qemu_check()) \
+ return qemu_ ## x ; \
+ } while (0)
+# define QEMU_FALLBACK_VOID(x) \
+ do { \
+ if (qemu_check()) { \
+ qemu_ ## x ; \
+ return; \
+ } \
+ } while (0)
+#else
+# define QEMU_FALLBACK(x) ((void)0)
+# define QEMU_FALLBACK_VOID(x) ((void)0)
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _libs_hardware_qemu_h */
diff --git a/qemu/Android.mk b/qemu/Android.mk
new file mode 100644
index 0000000..5171754
--- /dev/null
+++ b/qemu/Android.mk
@@ -0,0 +1,3 @@
+ifeq ($(QEMU_HARDWARE),true)
+LOCAL_SRC_FILES += qemu/qemu.c
+endif
diff --git a/qemu/qemu.c b/qemu/qemu.c
new file mode 100644
index 0000000..2631c58
--- /dev/null
+++ b/qemu/qemu.c
@@ -0,0 +1,312 @@
+/*
+ * Copyright (C) 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.
+ * 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.
+ */
+
+/* this file contains various functions used by all libhardware modules
+ * that support QEMU emulation
+ */
+#include "qemu.h"
+#define LOG_TAG "hardware-qemu"
+#include <cutils/log.h>
+#include <cutils/properties.h>
+#include <cutils/sockets.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <termios.h>
+#include <stdio.h>
+#include <stdarg.h>
+
+#define QEMU_DEBUG 0
+
+#if QEMU_DEBUG
+# define D(...) LOGD(__VA_ARGS__)
+#else
+# define D(...) ((void)0)
+#endif
+
+
+int
+qemu_check(void)
+{
+ static int in_qemu = -1;
+
+ if (__builtin_expect(in_qemu < 0,0)) {
+ char propBuf[PROPERTY_VALUE_MAX];
+ property_get("ro.kernel.qemu", propBuf, "");
+ in_qemu = (propBuf[0] == '1');
+ }
+ return in_qemu;
+}
+
+
+int
+qemu_channel_open( QemuChannel* channel,
+ const char* name,
+ int mode )
+{
+ int fd = -1;
+
+ /* initialize the channel is needed */
+ if (!channel->is_inited)
+ {
+ int done = 0;
+
+ // try to connect to qemud socket first
+ do {
+ snprintf(channel->device, sizeof channel->device,
+ "qemud_%s", name);
+
+ fd = socket_local_client( channel->device,
+ ANDROID_SOCKET_NAMESPACE_RESERVED,
+ SOCK_STREAM );
+ if (fd < 0) {
+ D("no '%s' control socket available: %s",
+ channel->device, strerror(errno));
+ break;
+ }
+ close(fd);
+ channel->is_qemud = 1;
+ done = 1;
+ } while (0);
+
+ // otherwise, look for a kernel-provided device name
+ if (!done) do {
+ char key[PROPERTY_KEY_MAX];
+ char prop[PROPERTY_VALUE_MAX];
+ int ret;
+
+ ret = snprintf(key, sizeof key, "ro.kernel.android.%s", name);
+ if (ret >= (int)sizeof key)
+ break;
+
+ if (property_get(key, prop, "") == 0) {
+ D("no kernel-provided %s device name", name);
+ break;
+ }
+
+ ret = snprintf(channel->device, sizeof channel->device,
+ "/dev/%s", prop);
+ if (ret >= (int)sizeof channel->device) {
+ D("%s device name too long: '%s'", name, prop);
+ break;
+ }
+ channel->is_tty = !memcmp("/dev/tty", channel->device, 8);
+ done = 1;
+
+ } while (0);
+
+ channel->is_available = done;
+ channel->is_inited = 1;
+ }
+
+ /* try to open the file */
+ if (!channel->is_available) {
+ fd = -1;
+ errno = ENOENT;
+ } else if (channel->is_qemud) {
+ do {
+ fd = socket_local_client( channel->device,
+ ANDROID_SOCKET_NAMESPACE_RESERVED,
+ SOCK_STREAM );
+ } while (fd < 0 && errno == EINTR);
+ } else {
+ do {
+ fd = open(channel->device, mode);
+ } while (fd < 0 && errno == EINTR);
+
+ /* disable ECHO on serial lines */
+ if (fd >= 0 && channel->is_tty) {
+ struct termios ios;
+ tcgetattr( fd, &ios );
+ ios.c_lflag = 0; /* disable ECHO, ICANON, etc... */
+ tcsetattr( fd, TCSANOW, &ios );
+ }
+ }
+ return fd;
+}
+
+
+static int
+qemu_command_vformat( char* buffer,
+ int buffer_size,
+ const char* format,
+ va_list args )
+{
+ char header[5];
+ int len;
+
+ if (buffer_size < 6)
+ return -1;
+
+ len = vsnprintf(buffer+4, buffer_size-4, format, args);
+ if (len >= buffer_size-4)
+ return -1;
+
+ snprintf(header, sizeof header, "%04x", len);
+ memcpy(buffer, header, 4);
+ return len + 4;
+}
+
+extern int
+qemu_command_format( char* buffer,
+ int buffer_size,
+ const char* format,
+ ... )
+{
+ va_list args;
+ int ret;
+
+ va_start(args, format);
+ ret = qemu_command_format(buffer, buffer_size, format, args);
+ va_end(args);
+ return ret;
+}
+
+
+static int
+qemu_control_fd(void)
+{
+ static QemuChannel channel[1];
+ int fd;
+
+ fd = qemu_channel_open( channel, "control", O_RDWR );
+ if (fd < 0) {
+ D("%s: could not open control channel: %s", __FUNCTION__,
+ strerror(errno));
+ }
+ return fd;
+}
+
+static int
+qemu_control_write( int fd, const char* cmd, int len )
+{
+ int len2;
+ do {
+ len2 = write(fd, cmd, len);
+ } while (len2 < 0 && errno == EINTR);
+ return len2;
+}
+
+static int
+qemu_control_read( int fd, char* buff, int len )
+{
+ int len2;
+ do {
+ len2 = read(fd, buff, len);
+ } while (len2 < 0 && errno == EINTR);
+ return len2;
+}
+
+static int
+qemu_control_send(const char* cmd, int len)
+{
+ int fd, len2;
+
+ if (len < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ fd = qemu_control_fd();
+ if (fd < 0)
+ return -1;
+
+ len2 = qemu_control_write(fd, cmd, len);
+ close(fd);
+ if (len2 != len) {
+ D("%s: could not send everything %d < %d",
+ __FUNCTION__, len2, len);
+ return -1;
+ }
+ return 0;
+}
+
+
+int
+qemu_control_command( const char* fmt, ... )
+{
+ va_list args;
+ char command[256];
+ int len, fd;
+
+ va_start(args, fmt);
+ len = qemu_command_vformat( command, sizeof command, fmt, args );
+ va_end(args);
+
+ if (len < 0 || len >= (int)sizeof command) {
+ if (len < 0) {
+ D("%s: could not send: %s", __FUNCTION__, strerror(errno));
+ } else {
+ D("%s: too large %d > %d", __FUNCTION__, len, (int)(sizeof command));
+ }
+ errno = EINVAL;
+ return -1;
+ }
+
+ return qemu_control_send( command, len );
+}
+
+extern int qemu_control_query( const char* question, int questionlen,
+ char* answer, int answersize )
+{
+ int ret, fd, len, result = -1;
+ char header[5], *end;
+
+ if (questionlen <= 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ fd = qemu_control_fd();
+ if (fd < 0)
+ return -1;
+
+ ret = qemu_control_write( fd, question, questionlen );
+ if (ret != questionlen) {
+ D("%s: could not write all: %d < %d", __FUNCTION__,
+ ret, questionlen);
+ goto Exit;
+ }
+
+ /* read a 4-byte header giving the length of the following content */
+ ret = qemu_control_read( fd, header, 4 );
+ if (ret != 4) {
+ D("%s: could not read header (%d != 4)",
+ __FUNCTION__, ret);
+ goto Exit;
+ }
+
+ header[5] = 0;
+ len = strtol( header, &end, 16 );
+ if ( len < 0 || end == NULL || end != header+4 || len > answersize ) {
+ D("%s: could not parse header: '%s'",
+ __FUNCTION__, header);
+ goto Exit;
+ }
+
+ /* read the answer */
+ ret = qemu_control_read( fd, answer, len );
+ if (ret != len) {
+ D("%s: could not read all of answer %d < %d",
+ __FUNCTION__, ret, len);
+ goto Exit;
+ }
+
+ result = len;
+
+Exit:
+ close(fd);
+ return result;
+}
diff --git a/qemu_tracing/Android.mk b/qemu_tracing/Android.mk
new file mode 100644
index 0000000..8c5bab0
--- /dev/null
+++ b/qemu_tracing/Android.mk
@@ -0,0 +1,4 @@
+# Copyright 2007 The Android Open Source Project
+
+LOCAL_SRC_FILES += qemu_tracing/qemu_tracing.c
+
diff --git a/qemu_tracing/qemu_tracing.c b/qemu_tracing/qemu_tracing.c
new file mode 100644
index 0000000..847102c
--- /dev/null
+++ b/qemu_tracing/qemu_tracing.c
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 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.
+ * 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 <string.h>
+#include <errno.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+// This is the pathname to the sysfs file that enables and disables
+// tracing on the qemu emulator.
+#define SYS_QEMU_TRACE_STATE "/sys/qemu_trace/state"
+
+
+// This is the pathname to the sysfs file that adds new (address, symbol)
+// pairs to the trace.
+#define SYS_QEMU_TRACE_SYMBOL "/sys/qemu_trace/symbol"
+
+// The maximum length of a symbol name
+#define MAX_SYMBOL_NAME_LENGTH (4 * 1024)
+
+// Allow space in the buffer for the address plus whitespace.
+#define MAX_BUF_SIZE (MAX_SYMBOL_NAME_LENGTH + 20)
+
+// return 0 on success, or an error if the qemu driver cannot be opened
+int qemu_start_tracing()
+{
+ int fd = open(SYS_QEMU_TRACE_STATE, O_WRONLY);
+ if (fd < 0)
+ return fd;
+ write(fd, "1\n", 2);
+ close(fd);
+ return 0;
+}
+
+int qemu_stop_tracing()
+{
+ int fd = open(SYS_QEMU_TRACE_STATE, O_WRONLY);
+ if (fd < 0)
+ return fd;
+ write(fd, "0\n", 2);
+ close(fd);
+ return 0;
+}
+
+int qemu_add_mapping(unsigned int addr, const char *name)
+{
+ char buf[MAX_BUF_SIZE];
+
+ if (strlen(name) > MAX_SYMBOL_NAME_LENGTH)
+ return EINVAL;
+ int fd = open(SYS_QEMU_TRACE_SYMBOL, O_WRONLY);
+ if (fd < 0)
+ return fd;
+ sprintf(buf, "%x %s\n", addr, name);
+ write(fd, buf, strlen(buf));
+ close(fd);
+ return 0;
+}
+
+int qemu_remove_mapping(unsigned int addr)
+{
+ char buf[MAX_BUF_SIZE];
+
+ int fd = open(SYS_QEMU_TRACE_SYMBOL, O_WRONLY);
+ if (fd < 0)
+ return fd;
+ sprintf(buf, "%x\n", addr);
+ write(fd, buf, strlen(buf));
+ close(fd);
+ return 0;
+}
diff --git a/tests/gpstest/Android.mk b/tests/gpstest/Android.mk
new file mode 100644
index 0000000..36ada0a
--- /dev/null
+++ b/tests/gpstest/Android.mk
@@ -0,0 +1,34 @@
+# Copyright (C) 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.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+
+LOCAL_SRC_FILES:= gpstest.cpp
+
+LOCAL_CFLAGS:= -fno-short-enums
+
+LOCAL_SHARED_LIBRARIES:= libhardware_legacy
+
+LOCAL_C_INCLUDES:= \
+ include/hardware_legacy
+
+LOCAL_MODULE:= gpstest
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES)
+
+LOCAL_MODULE_TAGS:= tests development
+
+include $(BUILD_EXECUTABLE)
diff --git a/tests/gpstest/gpstest.cpp b/tests/gpstest/gpstest.cpp
new file mode 100644
index 0000000..27cbd17
--- /dev/null
+++ b/tests/gpstest/gpstest.cpp
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 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.
+ * 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 <stdlib.h>
+#include <stdio.h>
+#include <unistd.h>
+
+extern "C" size_t dlmalloc_footprint();
+
+#include "hardware_legacy/gps.h"
+
+static const GpsInterface* sGpsInterface = NULL;
+
+static bool sDone = false;
+static int sFixes = 0;
+static int sMaxFixes = 0;
+static int sStatus = GPS_STATUS_ENGINE_OFF;
+
+static void location_callback(GpsLocation* location)
+{
+ printf("Got Fix: latitude: %lf longitude: %lf altitude: %.1lf\n",
+ location->latitude, location->longitude, location->altitude);
+ sFixes++;
+ if (sMaxFixes > 0 && sFixes >= sMaxFixes) {
+ sDone = true;
+ }
+}
+
+static void status_callback(GpsStatus* status)
+{
+ switch (status->status) {
+ case GPS_STATUS_NONE:
+ printf("status: GPS_STATUS_NONE\n");
+ break;
+ case GPS_STATUS_SESSION_BEGIN:
+ printf("status: GPS_STATUS_SESSION_BEGIN\n");
+ break;
+ case GPS_STATUS_SESSION_END:
+ printf("status: GPS_STATUS_SESSION_END\n");
+ break;
+ case GPS_STATUS_ENGINE_ON:
+ printf("status: GPS_STATUS_ENGINE_ON\n");
+ break;
+ case GPS_STATUS_ENGINE_OFF:
+ printf("status: GPS_STATUS_ENGINE_OFF\n");
+ break;
+ default:
+ printf("unknown status: %d\n", status->status);
+ break;
+ }
+
+ sStatus = status->status;
+}
+
+static void sv_status_callback(GpsSvStatus* sv_status)
+{
+ if (sv_status->num_svs > 0) {
+ for (int i = 0; i < sv_status->num_svs; i++) {
+ printf("SV: %2d SNR: %.1f Elev: %.1f Azim: %.1f %s %s\n", sv_status->sv_list[i].prn,
+ sv_status->sv_list[i].snr, sv_status->sv_list[i].elevation,
+ sv_status->sv_list[i].azimuth,
+ ((sv_status->ephemeris_mask & (1 << (sv_status->sv_list[i].prn - 1))) ? "E" : " "),
+ ((sv_status->almanac_mask & (1 << (sv_status->sv_list[i].prn - 1))) ? "A" : " ")
+ );
+ }
+ printf("\n");
+ }
+}
+
+GpsCallbacks sCallbacks = {
+ location_callback,
+ status_callback,
+ sv_status_callback,
+};
+
+int main(int argc, char *argv[])
+{
+ size_t initial = dlmalloc_footprint();
+
+ if (argc >= 2) {
+ sMaxFixes = atoi(argv[1]);
+ printf("max fixes: %d\n", sMaxFixes);
+ }
+
+ sGpsInterface = gps_get_interface();
+ if (!sGpsInterface) {
+ fprintf(stderr, "could not get gps interface\n");
+ return -1;
+ }
+
+ int err = sGpsInterface->init(&sCallbacks);
+ if (err) {
+ fprintf(stderr, "gps_init failed %d\n", err);
+ return err;
+ }
+
+ sGpsInterface->start();
+
+ while (!sDone) {
+ sleep(1);
+ }
+
+ sGpsInterface->stop();
+
+ printf("waiting for GPS to shut down\n");
+ while (sStatus != GPS_STATUS_ENGINE_OFF) {
+ sleep(1);
+ }
+
+ sGpsInterface->cleanup();
+
+ size_t final = dlmalloc_footprint();
+ fprintf(stderr, "KO: initial == %d, final == %d\n", initial, final );
+
+ return 0;
+}
diff --git a/uevent/Android.mk b/uevent/Android.mk
new file mode 100644
index 0000000..74ccdbc
--- /dev/null
+++ b/uevent/Android.mk
@@ -0,0 +1,7 @@
+# Copyright 2008 The Android Open Source Project
+
+ifeq ($(TARGET_SIMULATOR),true)
+LOCAL_SRC_FILES += uevent/uevent_stub.c
+else
+LOCAL_SRC_FILES += uevent/uevent.c
+endif
diff --git a/uevent/uevent.c b/uevent/uevent.c
new file mode 100644
index 0000000..d1d4b8e
--- /dev/null
+++ b/uevent/uevent.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 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.
+ * 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 <hardware_legacy/uevent.h>
+
+#include <string.h>
+#include <unistd.h>
+#include <poll.h>
+
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <linux/netlink.h>
+
+
+static int fd = -1;
+
+/* Returns 0 on failure, 1 on success */
+int uevent_init()
+{
+ struct sockaddr_nl addr;
+ int sz = 64*1024;
+ int s;
+
+ memset(&addr, 0, sizeof(addr));
+ addr.nl_family = AF_NETLINK;
+ addr.nl_pid = getpid();
+ addr.nl_groups = 0xffffffff;
+
+ s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
+ if(s < 0)
+ return 0;
+
+ setsockopt(s, SOL_SOCKET, SO_RCVBUFFORCE, &sz, sizeof(sz));
+
+ if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
+ close(s);
+ return 0;
+ }
+
+ fd = s;
+ return (fd > 0);
+}
+
+int uevent_next_event(char* buffer, int buffer_length)
+{
+ while (1) {
+ struct pollfd fds;
+ int nr;
+
+ fds.fd = fd;
+ fds.events = POLLIN;
+ fds.revents = 0;
+ nr = poll(&fds, 1, -1);
+
+ if(nr > 0 && fds.revents == POLLIN) {
+ int count = recv(fd, buffer, buffer_length, 0);
+ if (count > 0) {
+ return count;
+ }
+ }
+ }
+
+ // won't get here
+ return 0;
+}
diff --git a/uevent/uevent_stub.c b/uevent/uevent_stub.c
new file mode 100644
index 0000000..2f28ab4
--- /dev/null
+++ b/uevent/uevent_stub.c
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 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.
+ * 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 <hardware_legacy/uevent.h>
+#include <unistd.h>
+
+int uevent_init()
+{
+ return 1;
+}
+
+int uevent_next_event(char* buffer, int buffer_length)
+{
+ while (1) {
+ sleep(10000);
+ }
+
+ // won't get here
+ return 0;
+}
diff --git a/vibrator/Android.mk b/vibrator/Android.mk
new file mode 100644
index 0000000..6681f84
--- /dev/null
+++ b/vibrator/Android.mk
@@ -0,0 +1,4 @@
+# Copyright 2006 The Android Open Source Project
+
+LOCAL_SRC_FILES += vibrator/vibrator.c
+
diff --git a/vibrator/vibrator.c b/vibrator/vibrator.c
new file mode 100644
index 0000000..22cc506
--- /dev/null
+++ b/vibrator/vibrator.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 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.
+ * 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 <hardware_legacy/vibrator.h>
+#include "qemu.h"
+
+#include <stdio.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+
+#define THE_DEVICE "/sys/class/timed_output/vibrator/enable"
+
+static int sendit(int timeout_ms)
+{
+ int nwr, ret, fd;
+ char value[20];
+
+#ifdef QEMU_HARDWARE
+ if (qemu_check()) {
+ return qemu_control_command( "vibrator:%d", timeout_ms );
+ }
+#endif
+
+ fd = open(THE_DEVICE, O_RDWR);
+ if(fd < 0)
+ return errno;
+
+ nwr = sprintf(value, "%d\n", timeout_ms);
+ ret = write(fd, value, nwr);
+
+ close(fd);
+
+ return (ret == nwr) ? 0 : -1;
+}
+
+int vibrator_on(int timeout_ms)
+{
+ /* constant on, up to maximum allowed time */
+ return sendit(timeout_ms);
+}
+
+int vibrator_off()
+{
+ return sendit(0);
+}
diff --git a/wifi/Android.mk b/wifi/Android.mk
new file mode 100644
index 0000000..8444a40
--- /dev/null
+++ b/wifi/Android.mk
@@ -0,0 +1,5 @@
+# Copyright 2006 The Android Open Source Project
+
+LOCAL_SRC_FILES += wifi/wifi.c
+
+LOCAL_SHARED_LIBRARIES += libnetutils
diff --git a/wifi/wifi.c b/wifi/wifi.c
new file mode 100644
index 0000000..0778e77
--- /dev/null
+++ b/wifi/wifi.c
@@ -0,0 +1,458 @@
+/*
+ * Copyright 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.
+ * 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 <stdlib.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+
+#include "hardware_legacy/wifi.h"
+#include "libwpa_client/wpa_ctrl.h"
+
+#define LOG_TAG "WifiHW"
+#include "cutils/log.h"
+#include "cutils/memory.h"
+#include "cutils/misc.h"
+#include "cutils/properties.h"
+#include "private/android_filesystem_config.h"
+#ifdef HAVE_LIBC_SYSTEM_PROPERTIES
+#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
+#include <sys/_system_properties.h>
+#endif
+
+static struct wpa_ctrl *ctrl_conn;
+static struct wpa_ctrl *monitor_conn;
+
+extern int do_dhcp();
+extern int ifc_init();
+extern void ifc_close();
+extern char *dhcp_lasterror();
+extern void get_dhcp_info();
+extern int init_module(void *, unsigned long, const char *);
+extern int delete_module(const char *, unsigned int);
+
+static char iface[PROPERTY_VALUE_MAX];
+// TODO: use new ANDROID_SOCKET mechanism, once support for multiple
+// sockets is in
+
+static const char IFACE_DIR[] = "/data/system/wpa_supplicant";
+static const char DRIVER_MODULE_NAME[] = "wlan";
+static const char DRIVER_MODULE_TAG[] = "wlan ";
+static const char DRIVER_MODULE_PATH[] = "/system/lib/modules/wlan.ko";
+static const char FIRMWARE_LOADER[] = "wlan_loader";
+static const char DRIVER_PROP_NAME[] = "wlan.driver.status";
+static const char SUPPLICANT_NAME[] = "wpa_supplicant";
+static const char SUPP_PROP_NAME[] = "init.svc.wpa_supplicant";
+static const char SUPP_CONFIG_TEMPLATE[]= "/system/etc/wifi/wpa_supplicant.conf";
+static const char SUPP_CONFIG_FILE[] = "/data/misc/wifi/wpa_supplicant.conf";
+static const char MODULE_FILE[] = "/proc/modules";
+
+static int insmod(const char *filename)
+{
+ void *module;
+ unsigned int size;
+ int ret;
+
+ module = load_file(filename, &size);
+ if (!module)
+ return -1;
+
+ ret = init_module(module, size, "");
+
+ free(module);
+
+ return ret;
+}
+
+static int rmmod(const char *modname)
+{
+ int ret = -1;
+ int maxtry = 10;
+
+ while (maxtry-- > 0) {
+ ret = delete_module(modname, O_NONBLOCK | O_EXCL);
+ if (ret < 0 && errno == EAGAIN)
+ usleep(500000);
+ else
+ break;
+ }
+
+ if (ret != 0)
+ LOGD("Unable to unload driver module \"%s\": %s\n",
+ modname, strerror(errno));
+ return ret;
+}
+
+int do_dhcp_request(int *ipaddr, int *gateway, int *mask,
+ int *dns1, int *dns2, int *server, int *lease) {
+ /* For test driver, always report success */
+ if (strcmp(iface, "sta") == 0)
+ return 0;
+
+ if (ifc_init() < 0)
+ return -1;
+
+ if (do_dhcp(iface) < 0) {
+ ifc_close();
+ return -1;
+ }
+ ifc_close();
+ get_dhcp_info(ipaddr, gateway, mask, dns1, dns2, server, lease);
+ return 0;
+}
+
+const char *get_dhcp_error_string() {
+ return dhcp_lasterror();
+}
+
+static int check_driver_loaded() {
+ char driver_status[PROPERTY_VALUE_MAX];
+ FILE *proc;
+ char line[sizeof(DRIVER_MODULE_TAG)+10];
+
+ if (!property_get(DRIVER_PROP_NAME, driver_status, NULL)
+ || strcmp(driver_status, "ok") != 0) {
+ return 0; /* driver not loaded */
+ }
+ /*
+ * If the property says the driver is loaded, check to
+ * make sure that the property setting isn't just left
+ * over from a previous manual shutdown or a runtime
+ * crash.
+ */
+ if ((proc = fopen(MODULE_FILE, "r")) == NULL) {
+ LOGW("Could not open %s: %s", MODULE_FILE, strerror(errno));
+ property_set(DRIVER_PROP_NAME, "unloaded");
+ return 0;
+ }
+ while ((fgets(line, sizeof(line), proc)) != NULL) {
+ if (strncmp(line, DRIVER_MODULE_TAG, strlen(DRIVER_MODULE_TAG)) == 0) {
+ fclose(proc);
+ return 1;
+ }
+ }
+ fclose(proc);
+ property_set(DRIVER_PROP_NAME, "unloaded");
+ return 0;
+}
+
+int wifi_load_driver()
+{
+ char driver_status[PROPERTY_VALUE_MAX];
+ int count = 100; /* wait at most 20 seconds for completion */
+
+ if (check_driver_loaded()) {
+ return 0;
+ }
+
+ if (insmod(DRIVER_MODULE_PATH) < 0)
+ return -1;
+
+ property_set("ctl.start", FIRMWARE_LOADER);
+ sched_yield();
+ while (count-- > 0) {
+ if (property_get(DRIVER_PROP_NAME, driver_status, NULL)) {
+ if (strcmp(driver_status, "ok") == 0)
+ return 0;
+ else if (strcmp(DRIVER_PROP_NAME, "failed") == 0)
+ return -1;
+ }
+ usleep(200000);
+ }
+ property_set(DRIVER_PROP_NAME, "timeout");
+ return -1;
+}
+
+int wifi_unload_driver()
+{
+ int count = 20; /* wait at most 10 seconds for completion */
+
+ if (rmmod(DRIVER_MODULE_NAME) == 0) {
+ while (count-- > 0) {
+ if (!check_driver_loaded())
+ break;
+ usleep(500000);
+ }
+ if (count) {
+ return 0;
+ }
+ return -1;
+ } else
+ return -1;
+}
+
+int ensure_config_file_exists()
+{
+ char buf[2048];
+ int srcfd, destfd;
+ int nread;
+
+ if (access(SUPP_CONFIG_FILE, R_OK|W_OK) == 0) {
+ return 0;
+ } else if (errno != ENOENT) {
+ LOGE("Cannot access \"%s\": %s", SUPP_CONFIG_FILE, strerror(errno));
+ return -1;
+ }
+
+ srcfd = open(SUPP_CONFIG_TEMPLATE, O_RDONLY);
+ if (srcfd < 0) {
+ LOGE("Cannot open \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
+ return -1;
+ }
+
+ destfd = open(SUPP_CONFIG_FILE, O_CREAT|O_WRONLY, 0660);
+ if (destfd < 0) {
+ close(srcfd);
+ LOGE("Cannot create \"%s\": %s", SUPP_CONFIG_FILE, strerror(errno));
+ return -1;
+ }
+
+ while ((nread = read(srcfd, buf, sizeof(buf))) != 0) {
+ if (nread < 0) {
+ LOGE("Error reading \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
+ close(srcfd);
+ close(destfd);
+ unlink(SUPP_CONFIG_FILE);
+ return -1;
+ }
+ write(destfd, buf, nread);
+ }
+
+ close(destfd);
+ close(srcfd);
+
+ if (chown(SUPP_CONFIG_FILE, AID_SYSTEM, AID_WIFI) < 0) {
+ LOGE("Error changing group ownership of %s to %d: %s",
+ SUPP_CONFIG_FILE, AID_WIFI, strerror(errno));
+ unlink(SUPP_CONFIG_FILE);
+ return -1;
+ }
+ return 0;
+}
+
+int wifi_start_supplicant()
+{
+ char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
+ int count = 200; /* wait at most 20 seconds for completion */
+#ifdef HAVE_LIBC_SYSTEM_PROPERTIES
+ const prop_info *pi;
+ unsigned serial = 0;
+#endif
+
+ /* Check whether already running */
+ if (property_get(SUPP_PROP_NAME, supp_status, NULL)
+ && strcmp(supp_status, "running") == 0) {
+ return 0;
+ }
+
+ /* Before starting the daemon, make sure its config file exists */
+ if (ensure_config_file_exists() < 0) {
+ LOGE("Wi-Fi will not be enabled");
+ return -1;
+ }
+
+ /* Clear out any stale socket files that might be left over. */
+ wpa_ctrl_cleanup();
+
+#ifdef HAVE_LIBC_SYSTEM_PROPERTIES
+ /*
+ * Get a reference to the status property, so we can distinguish
+ * the case where it goes stopped => running => stopped (i.e.,
+ * it start up, but fails right away) from the case in which
+ * it starts in the stopped state and never manages to start
+ * running at all.
+ */
+ pi = __system_property_find(SUPP_PROP_NAME);
+ if (pi != NULL) {
+ serial = pi->serial;
+ }
+#endif
+ property_set("ctl.start", SUPPLICANT_NAME);
+ sched_yield();
+
+ while (count-- > 0) {
+ #ifdef HAVE_LIBC_SYSTEM_PROPERTIES
+ if (pi == NULL) {
+ pi = __system_property_find(SUPP_PROP_NAME);
+ }
+ if (pi != NULL) {
+ __system_property_read(pi, NULL, supp_status);
+ if (strcmp(supp_status, "running") == 0) {
+ return 0;
+ } else if (pi->serial != serial &&
+ strcmp(supp_status, "stopped") == 0) {
+ return -1;
+ }
+ }
+#else
+ if (property_get(SUPP_PROP_NAME, supp_status, NULL)) {
+ if (strcmp(supp_status, "running") == 0)
+ return 0;
+ }
+#endif
+ usleep(100000);
+ }
+ return -1;
+}
+
+int wifi_stop_supplicant()
+{
+ char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
+ int count = 50; /* wait at most 5 seconds for completion */
+
+ /* Check whether supplicant already stopped */
+ if (property_get(SUPP_PROP_NAME, supp_status, NULL)
+ && strcmp(supp_status, "stopped") == 0) {
+ return 0;
+ }
+
+ property_set("ctl.stop", SUPPLICANT_NAME);
+ sched_yield();
+
+ while (count-- > 0) {
+ if (property_get(SUPP_PROP_NAME, supp_status, NULL)) {
+ if (strcmp(supp_status, "stopped") == 0)
+ return 0;
+ }
+ usleep(100000);
+ }
+ return -1;
+}
+
+int wifi_connect_to_supplicant()
+{
+ char ifname[256];
+ char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
+
+ /* Make sure supplicant is running */
+ if (!property_get(SUPP_PROP_NAME, supp_status, NULL)
+ || strcmp(supp_status, "running") != 0) {
+ LOGE("Supplicant not running, cannot connect");
+ return -1;
+ }
+
+ property_get("wifi.interface", iface, "sta");
+
+ if (access(IFACE_DIR, F_OK) == 0) {
+ snprintf(ifname, sizeof(ifname), "%s/%s", IFACE_DIR, iface);
+ } else {
+ strlcpy(ifname, iface, sizeof(ifname));
+ }
+
+ ctrl_conn = wpa_ctrl_open(ifname);
+ if (ctrl_conn == NULL) {
+ LOGE("Unable to open connection to supplicant on \"%s\": %s",
+ ifname, strerror(errno));
+ return -1;
+ }
+ monitor_conn = wpa_ctrl_open(ifname);
+ if (monitor_conn == NULL) {
+ wpa_ctrl_close(ctrl_conn);
+ ctrl_conn = NULL;
+ return -1;
+ }
+ if (wpa_ctrl_attach(monitor_conn) != 0) {
+ wpa_ctrl_close(monitor_conn);
+ wpa_ctrl_close(ctrl_conn);
+ ctrl_conn = monitor_conn = NULL;
+ return -1;
+ }
+ return 0;
+}
+
+int wifi_send_command(struct wpa_ctrl *ctrl, const char *cmd, char *reply, size_t *reply_len)
+{
+ int ret;
+
+ if (ctrl_conn == NULL) {
+ LOGV("Not connected to wpa_supplicant - \"%s\" command dropped.\n", cmd);
+ return -1;
+ }
+ ret = wpa_ctrl_request(ctrl, cmd, strlen(cmd), reply, reply_len, NULL);
+ if (ret == -2) {
+ LOGD("'%s' command timed out.\n", cmd);
+ return -2;
+ } else if (ret < 0 || strncmp(reply, "FAIL", 4) == 0) {
+ return -1;
+ }
+ if (strncmp(cmd, "PING", 4) == 0) {
+ reply[*reply_len] = '\0';
+ }
+ return 0;
+}
+
+int wifi_wait_for_event(char *buf, size_t buflen)
+{
+ size_t nread = buflen - 1;
+ int fd;
+ fd_set rfds;
+ int result;
+ struct timeval tval;
+ struct timeval *tptr;
+
+ if (monitor_conn == NULL)
+ return 0;
+
+ result = wpa_ctrl_recv(monitor_conn, buf, &nread);
+ if (result < 0) {
+ LOGD("wpa_ctrl_recv failed: %s\n", strerror(errno));
+ return -1;
+ }
+ buf[nread] = '\0';
+ /* LOGD("wait_for_event: result=%d nread=%d string=\"%s\"\n", result, nread, buf); */
+ /* Check for EOF on the socket */
+ if (result == 0 && nread == 0) {
+ /* Fabricate an event to pass up */
+ LOGD("Received EOF on supplicant socket\n");
+ strncpy(buf, WPA_EVENT_TERMINATING " - signal 0 received", buflen-1);
+ buf[buflen-1] = '\0';
+ return strlen(buf);
+ }
+ /*
+ * Events strings are in the format
+ *
+ * <N>CTRL-EVENT-XXX
+ *
+ * where N is the message level in numerical form (0=VERBOSE, 1=DEBUG,
+ * etc.) and XXX is the event name. The level information is not useful
+ * to us, so strip it off.
+ */
+ if (buf[0] == '<') {
+ char *match = strchr(buf, '>');
+ if (match != NULL) {
+ nread -= (match+1-buf);
+ memmove(buf, match+1, nread+1);
+ }
+ }
+ return nread;
+}
+
+void wifi_close_supplicant_connection()
+{
+ if (ctrl_conn != NULL) {
+ wpa_ctrl_close(ctrl_conn);
+ ctrl_conn = NULL;
+ }
+ if (monitor_conn != NULL) {
+ wpa_ctrl_close(monitor_conn);
+ monitor_conn = NULL;
+ }
+}
+
+int wifi_command(const char *command, char *reply, size_t *reply_len)
+{
+ return wifi_send_command(ctrl_conn, command, reply, reply_len);
+}