diff options
author | The Android Open Source Project <initial-contribution@android.com> | 2008-10-21 07:00:00 -0700 |
---|---|---|
committer | The Android Open Source Project <initial-contribution@android.com> | 2008-10-21 07:00:00 -0700 |
commit | d6054a36475b5ff502b4af78f7d272a713c1a8e7 (patch) | |
tree | 15482ee71b318f54f288240adce0b59febf76bc7 | |
download | hardware_libhardware-d6054a36475b5ff502b4af78f7d272a713c1a8e7.zip hardware_libhardware-d6054a36475b5ff502b4af78f7d272a713c1a8e7.tar.gz hardware_libhardware-d6054a36475b5ff502b4af78f7d272a713c1a8e7.tar.bz2 |
Initial Contribution
39 files changed, 4196 insertions, 0 deletions
diff --git a/Android.mk b/Android.mk new file mode 100644 index 0000000..05dc61a --- /dev/null +++ b/Android.mk @@ -0,0 +1,22 @@ +# 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 + +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 + endif +endif + +LOCAL_MODULE:= libhardware + +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 @@ -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..c696e1b --- /dev/null +++ b/flashlight/Android.mk @@ -0,0 +1,4 @@ +# Copyright 2007 The Android Open Source Project + +LOCAL_SRC_FILES += flashlight/flashlight.c + diff --git a/flashlight/flashlight.c b/flashlight/flashlight.c new file mode 100644 index 0000000..028a1dc --- /dev/null +++ b/flashlight/flashlight.c @@ -0,0 +1,59 @@ +#include <hardware/flashlight.h> + +#include <stdio.h> +#include <unistd.h> +#include <fcntl.h> +#include <errno.h> + +#define FLASHLIGHT "/sys/class/leds/spotlight/brightness" +#define CAMERA_FLASH "/sys/class/timed_output/flash/enable" + + +int get_flashlight_enabled() +{ + int fd; + int ret = 0; + char value; + + 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]; + + 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]; + + 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..64ada57 --- /dev/null +++ b/gps/Android.mk @@ -0,0 +1,19 @@ +# the Dream and Surf use the Qualcom GPS stuff +# + +ifneq ($(BOARD_GPS_LIBRARIES),) + LOCAL_CFLAGS += -DHAVE_GPS_HARDWARE + LOCAL_SHARED_LIBRARIES += $(BOARD_GPS_LIBRARIES) +endif + +# always compile the emulator-specific hardware for now +# +USE_QEMU_GPS_HARDWARE := true + +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..efd1181 --- /dev/null +++ b/gps/gps.cpp @@ -0,0 +1,39 @@ +#include <hardware/gps.h> +#include <cutils/properties.h> + +#define LOG_TAG "libhardware" +#include <utils/Log.h> + +static const GpsInterface* sGpsInterface = NULL; + +static void +gps_find_hardware( void ) +{ +#ifdef HAVE_QEMU_GPS_HARDWARE + char propBuf[PROPERTY_VALUE_MAX]; + + property_get("ro.kernel.qemu", propBuf, ""); + if (propBuf[0] == '1') { + 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..67737c1 --- /dev/null +++ b/gps/gps_qemu.c @@ -0,0 +1,945 @@ + +#include <errno.h> +#include <pthread.h> +#include <termios.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 <cutils/properties.h> +#include <hardware/gps.h> + +/* the name of the qemud-controlled socket */ +#define QEMUD_SOCKET_NAME "qemud_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]; + +} 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 ) +{ + char prop[PROPERTY_VALUE_MAX]; + char device[256]; + int ret; + int done = 0; + + state->init = 1; + state->control[0] = -1; + state->control[1] = -1; + state->fd = -1; + + // try to connect to the qemud socket + do { + state->fd = socket_local_client( QEMUD_SOCKET_NAME, + ANDROID_SOCKET_NAMESPACE_RESERVED, + SOCK_STREAM ); + if (state->fd < 0) { + D("no '%s' control socket available: %s", QEMUD_SOCKET_NAME, strerror(errno)); + break; + } + snprintf( device, sizeof(device), "/dev/socket/%s", QEMUD_SOCKET_NAME ); + done = 1; + + } while (0); + + // otherwise, look for a kernel-provided device name + if (!done) do { + if (property_get("ro.kernel.android.gps",prop,"") == 0) { + D("no kernel-provided gps device name"); + break; + } + if ( snprintf(device, sizeof(device), "/dev/%s", prop) >= (int)sizeof(device) ) { + LOGE("gps serial device name too long: '%s'", prop); + break; + } + + do { + state->fd = open( device, O_RDWR ); + } while (state->fd < 0 && errno == EINTR); + + if (state->fd < 0) { + LOGE("could not open gps serial device %s: %s", device, strerror(errno) ); + break; + } + done = 1; + + } while (0); + + if (!done) { + D("no gps emulation detected"); + return; + } + + D("gps emulation will read from %s", device); + + // disable echo on serial lines + if ( !memcmp( device, "/dev/ttyS", 9 ) ) { + struct termios ios; + tcgetattr( state->fd, &ios ); + ios.c_lflag = 0; /* disable ECHO, ICANON, etc... */ + tcsetattr( state->fd, TCSANOW, &ios ); + } + + 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 -1; + } + + 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/AudioHardwareInterface.h b/include/hardware/AudioHardwareInterface.h new file mode 100644 index 0000000..febc86a --- /dev/null +++ b/include/hardware/AudioHardwareInterface.h @@ -0,0 +1,214 @@ +/* + * 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 { + +// ---------------------------------------------------------------------------- + +/** + * This 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; + + /** + * This method can be used in situations where audio mixing is done in the + * hardware. It is a direct interface to the hardware to set the volume as + * as opposed to controlling this via the framework. It could be 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; + + /** dump the state of the audio output device */ + virtual status_t dump(int fd, const Vector<String16>& args) = 0; +}; + +/** + * This 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; + + /** 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; +}; + +/** + * This defines the interface to the audio hardware abstraction layer. It + * 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. Audio routing can be set to output to handset, speaker, bluetooth or + * headset. + * + * The audio input stream is initialized when AudioFlinger is called to carry + * out a record operation. + */ +class AudioHardwareInterface +{ +public: + AudioHardwareInterface(); + virtual ~AudioHardwareInterface() { } + + /** + * 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; + + /** + * put the audio hardware into standby mode to conserve power. Returns + * status based on include/utils/Errors.h + */ + virtual status_t standby() = 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/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); + + // 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); + + /** This method creates and opens the audio hardware output stream */ + virtual AudioStreamOut* openOutputStream( + int format=0, + int channelCount=0, + uint32_t sampleRate=0) = 0; + + /** This method creates and opens the audio hardware input stream */ + virtual AudioStreamIn* openInputStream( + int format, + int channelCount, + uint32_t sampleRate) = 0; + + /**This method dumps the state of the audio hardware */ + virtual status_t dumpState(int fd, const Vector<String16>& args); + + static AudioHardwareInterface* create(); + +protected: + /** + * doRouting actually initiates the routing to occur. A call to setRouting + * or setMode may result in a routing change. The generic logic will call + * 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; + + int mMode; + uint32_t mRoutes[AudioSystem::NUM_MODES]; +}; + +// ---------------------------------------------------------------------------- + +extern "C" AudioHardwareInterface* createAudioHardware(void); + +}; // namespace android + +#endif // ANDROID_AUDIO_HARDWARE_INTERFACE_H diff --git a/include/hardware/IMountService.h b/include/hardware/IMountService.h new file mode 100644 index 0000000..6737dcf --- /dev/null +++ b/include/hardware/IMountService.h @@ -0,0 +1,63 @@ +/* + * 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; +}; + +// ---------------------------------------------------------------------- + +}; // namespace android + +#endif // ANDROID_HARDWARE_IMOUNTSERVICE_H diff --git a/include/hardware/flashlight.h b/include/hardware/flashlight.h new file mode 100644 index 0000000..d372307 --- /dev/null +++ b/include/hardware/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/gps.h b/include/hardware/gps.h new file mode 100644 index 0000000..54b50a5 --- /dev/null +++ b/include/hardware/gps.h @@ -0,0 +1,218 @@ +/* + * 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 Space Vehicles for gps_sv_status_callback */ +#define GPS_MAX_SVS 32 + + +typedef uint16_t GpsPositionMode; +#define GPS_POSITION_MODE_STANDALONE 0 +#define GPS_POSITION_MODE_MS_BASED 1 +#define GPS_POSITION_MODE_MS_ASSISTED 2 + +typedef uint16_t GpsStatusValue; +// IMPORTANT - these symbols here must match constants in GpsLocationProvider.java +#define GPS_STATUS_NONE 0 +#define GPS_STATUS_SESSION_BEGIN 1 +#define GPS_STATUS_SESSION_END 2 +#define GPS_STATUS_ENGINE_ON 3 +#define GPS_STATUS_ENGINE_OFF 4 + +typedef uint16_t GpsLocationFlags; +// IMPORTANT - these symbols here must match constants in GpsLocationProvider.java +#define GPS_LOCATION_HAS_LAT_LONG 0x0001 +#define GPS_LOCATION_HAS_ALTITUDE 0x0002 +#define GPS_LOCATION_HAS_SPEED 0x0004 +#define GPS_LOCATION_HAS_BEARING 0x0008 +#define GPS_LOCATION_HAS_ACCURACY 0x0010 + +typedef uint16_t GpsAidingData; +// IMPORTANT - these symbols here 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 + +/** + * names for GPS XTRA interface + */ +#define GPS_XTRA_INTERFACE "gps-xtra" + +/** + * names for GPS supplemental interface + * TODO: Remove not used. + */ +#define GPS_SUPL_INTERFACE "gps-supl" + +/** The location */ +typedef struct { + /** contains GpsLocationFlags bits */ + uint16_t flags; + double latitude; + double longitude; + double altitude; + float speed; + float bearing; + float accuracy; + GpsUtcTime timestamp; +} GpsLocation; + +/** The status */ +typedef struct { + GpsStatusValue status; +} GpsStatus; + +/** Space Vehicle info */ +typedef struct { + int prn; + float snr; + float elevation; + float azimuth; +} GpsSvInfo; + +/** Space Vehicle status */ +typedef struct { + /** number of SVs currently visible */ + int num_svs; + + /** Array of space vehicle info */ + GpsSvInfo sv_list[GPS_MAX_SVS]; + + /** bit mask indicating which SVs have ephemeris data */ + uint32_t ephemeris_mask; + + /** bit mask indicating which SVs have almanac data */ + uint32_t almanac_mask; + + /** + * 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 the status information */ +typedef void (* gps_status_callback)(GpsStatus* status); + +/** Callback with the space vehicle status information */ +typedef void (* gps_sv_status_callback)(GpsSvStatus* sv_info); + +/** GPS call back structure */ +typedef struct { + gps_location_callback location_cb; + gps_status_callback status_cb; + gps_sv_status_callback sv_status_cb; +} GpsCallbacks; + + +/** Standard GPS interface */ +typedef struct { + /** + * Open the interface and provide the callback routines + * to the implemenation of this interface. + */ + int (*init)( GpsCallbacks* callbacks ); + + /** Start navigating */ + int (*start)( void ); + + /** Stop navigating */ + int (*stop)( void ); + + /** Set requested frequency of fixes in seconds */ + void (*set_fix_frequency)( int frequency ); + + /** Close the interface */ + void (*cleanup)( void ); + + /** Inject the current time */ + int (*inject_time)(GpsUtcTime time, int64_t timeReference, + int uncertainty); + + /** + * 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 is 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; + +/** The download request callback routine. */ +typedef void (* gps_xtra_download_request)(); + +/** The download request callback structure. */ +typedef struct { + gps_xtra_download_request download_request_cb; +} GpsXtraCallbacks; + +/** Extended interface for XTRA support. */ +typedef struct { + int (*init)( GpsXtraCallbacks* callbacks ); + int (*inject_xtra_data)( char* data, int length ); +} GpsXtraInterface; + +/** returns the hardware GPS interface. */ +const GpsInterface* gps_get_hardware_interface(); + +/** + * returns the qemu hardware interface GPS interface. + */ +const GpsInterface* gps_get_qemu_interface(); + +/** + * returns the default GPS interface, + * implemented in lib/hardware/gps.cpp. + */ +const GpsInterface* gps_get_interface(); + +#if __cplusplus +} // extern "C" +#endif + +#endif // _HARDWARE_GPS_H diff --git a/include/hardware/led.h b/include/hardware/led.h new file mode 100644 index 0000000..d7b2363 --- /dev/null +++ b/include/hardware/led.h @@ -0,0 +1,43 @@ +/* + * 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 + +/** + * Change the state of the led + * + * To turn on the led; Alpha != 0 and RBG != 0, onMS == 0 && offMS == 0. + * To blink the led; Alpha != 0 and RBG != 0, onMS != 0 && offMS != 0. + * To turn off the led; Alpha == 0 or RGB == 0. + * + * @param colorARGB the is color, Alpha=31:24, Red=23:16 Green=15:8 Blue=7:0 + * @param onMS is the time on in milli-seconds + * @param offMS is the time off in milli-seconds + * + * @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/power.h b/include/hardware/power.h new file mode 100644 index 0000000..993bca5 --- /dev/null +++ b/include/hardware/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/qemu_tracing.h b/include/hardware/qemu_tracing.h new file mode 100644 index 0000000..645a0be --- /dev/null +++ b/include/hardware/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/sensors.h b/include/hardware/sensors.h new file mode 100644 index 0000000..19fd72c --- /dev/null +++ b/include/hardware/sensors.h @@ -0,0 +1,243 @@ +/* + * 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_SENSORS_H +#define _HARDWARE_SENSORS_H + +#include <stdint.h> + +#if __cplusplus +extern "C" { +#endif + +/** + * Sensor IDs must be a power of two and + * must match values in SensorManager.java + */ + +#define SENSORS_ORIENTATION 0x00000001 +#define SENSORS_ACCELERATION 0x00000002 +#define SENSORS_TEMPERATURE 0x00000004 +#define SENSORS_MAGNETIC_FIELD 0x00000008 +#define SENSORS_LIGHT 0x00000010 +#define SENSORS_PROXIMITY 0x00000020 +#define SENSORS_TRICORDER 0x00000040 +#define SENSORS_ORIENTATION_RAW 0x00000080 +#define SENSORS_MASK 0x000000FF + +/** + * Values returned by the accelerometer in various locations in the universe. + * all values are in SI units (m/s^2) + */ + +#define GRAVITY_SUN (275.0f) +#define GRAVITY_MERCURY (3.70f) +#define GRAVITY_VENUS (8.87f) +#define GRAVITY_EARTH (9.80665f) +#define GRAVITY_MOON (1.6f) +#define GRAVITY_MARS (3.71f) +#define GRAVITY_JUPITER (23.12f) +#define GRAVITY_SATURN (8.96f) +#define GRAVITY_URANUS (8.69f) +#define GRAVITY_NEPTUN (11.0f) +#define GRAVITY_PLUTO (0.6f) +#define GRAVITY_DEATH_STAR_I (0.000000353036145f) +#define GRAVITY_THE_ISLAND (4.815162342f) + +/** Maximum magnetic field on Earth's surface */ +#define MAGNETIC_FIELD_EARTH_MAX (60.0f) + +/** Minimum magnetic field on Earth's surface */ +#define MAGNETIC_FIELD_EARTH_MIN (30.0f) + +/** + * Various luminance values during the day (lux) + */ + +#define LIGHT_SUNLIGHT_MAX (120000.0f) +#define LIGHT_SUNLIGHT (110000.0f) +#define LIGHT_SHADE (20000.0f) +#define LIGHT_OVERCAST (10000.0f) +#define LIGHT_SUNRISE (400.0f) +#define LIGHT_CLOUDY (100.0f) + +/* + * Various luminance values during the night (lux) + */ + +#define LIGHT_FULLMOON (0.25f) +#define LIGHT_NO_MOON (0.001f) + +/** + * status of each sensor + */ + +#define SENSOR_STATUS_UNRELIABLE 0 +#define SENSOR_STATUS_ACCURACY_LOW 1 +#define SENSOR_STATUS_ACCURACY_MEDIUM 2 +#define SENSOR_STATUS_ACCURACY_HIGH 3 + +/** + * Definition of the axis + * + * This API is relative to the screen of the device in its default orientation, + * that is, if the device can be used in portrait or landscape, this API + * is only relative to the NATURAL orientation of the screen. In other words, + * the axis are not swapped when the device's screen orientation changes. + * Higher level services /may/ perform this transformation. + * + * -x +x + * ^ + * | + * +-----------+--> +y + * | | + * | | + * | | + * | | / -z + * | | / + * | | / + * +-----------+/ + * | o O o / + * +----------/+ -y + * / + * / + * |/ +z + * + */ +typedef struct { + union { + float v[3]; + struct { + float x; + float y; + float z; + }; + struct { + float yaw; + float pitch; + float roll; + }; + }; + int8_t status; + uint8_t reserved[3]; +} sensors_vec_t; + +/** + * Union of the various types of sensor data + * that can be returned. + */ +typedef struct { + /* sensor identifier */ + int sensor; + + union { + /* x,y,z values of the given sensor */ + sensors_vec_t vector; + + /* orientation values are in degres */ + sensors_vec_t orientation; + + /* acceleration values are in meter per second per second (m/s^2) */ + sensors_vec_t acceleration; + + /* magnetic vector values are in micro-Tesla (uT) */ + sensors_vec_t magnetic; + + /* temperature is in degres C */ + float temperature; + }; + + /* time is in nanosecond */ + int64_t time; + + uint32_t reserved; +} sensors_data_t; + +/** + * Initialize the module. This is the first entry point + * called and typically initializes the hardware. + * + * @return bit map of available sensors defined by + * the constants SENSORS_XXXX. + */ +uint32_t sensors_control_init(); + +/** + * Returns the fd which will be the parameter to + * sensors_data_open. The caller takes ownership + * of this fd. + * + * @return a fd if successful, < 0 on error + */ +int sensors_control_open(); + +/** Activate/deactiveate one or more of the sensors. + * + * @param sensors is a bitmask of the sensors to change. + * @param mask is a bitmask for enabling/disabling sensors. + * + * @return bitmask of SENSORS_XXXX indicating which sensors are enabled + */ +uint32_t sensors_control_activate(uint32_t sensors, uint32_t mask); + +/** + * Set the delay between sensor events in ms + * + * @return 0 if successful, < 0 on error + */ +int sensors_control_delay(int32_t ms); + +/** + * Prepare to read sensor data. + * + * This routiune does NOT take ownership of the fd + * and must not close it. Typcially this routine would + * use a duplicate of the fd parameter. + * + * @param fd from sensors_control_open. + * + * @return 0 if successful, < 0 on error + */ +int sensors_data_open(int fd); + +/** + * Caller has completed using the sensor data. + * The caller will not be blocked in sensors_data_poll + * when this routine is called. + * + * @return 0 if successful, < 0 on error + */ +int sensors_data_close(); + +/** + * Return sensor data for one of the enabled sensors. + * + * @return SENSOR_XXXX for the returned data, -1 on error + * */ +int sensors_data_poll(sensors_data_t* data, uint32_t sensors_of_interest); + +/** + * @return bit map of available sensors defined by + * the constants SENSORS_XXXX. + */ +uint32_t sensors_data_get_sensors(); + + +#if __cplusplus +} // extern "C" +#endif + +#endif // _HARDWARE_SENSORS_H diff --git a/include/hardware/uevent.h b/include/hardware/uevent.h new file mode 100644 index 0000000..7a5ce58 --- /dev/null +++ b/include/hardware/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/vibrator.h b/include/hardware/vibrator.h new file mode 100644 index 0000000..5245aeb --- /dev/null +++ b/include/hardware/vibrator.h @@ -0,0 +1,42 @@ +/* + * 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 + * + * @return 0 if successful, -1 if error + */ +int vibrator_on(); + +/** + * 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/wifi.h b/include/hardware/wifi.h new file mode 100644 index 0000000..0b1acdc --- /dev/null +++ b/include/hardware/wifi.h @@ -0,0 +1,153 @@ +/* + * 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 wifi driver. + * + * @return 0 on success, < 0 on failure. + */ +int wifi_load_driver(); + +/** + * Unload the wifi 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(); + +/** + * Do a blocking call to get a wifi event and + * return a string representing a wifi 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, < 0 if an + * error. + */ +int wifi_wait_for_event(char *buf, size_t len); + +/** + * Issue a command to the wifi driver. + * + * see \link http://hostap.epitest.fi/wpa_supplicant/devel/ctrl_iface_page.html + * for the list of the standard commands. Android has extended these to include + * support for sending commands to the driver: + * + *------------------------------------------------------------------------------ + * command form of response processing + * Summary of the command + *------------------------------------------------------------------------------ + * "DRIVER START" -> "OK" if successful -> "OK" ? true : false + * Turn on WiFi Hardware + * + * "DRIVER STOP" -> "OK" if successful -> "OK" ? true : false + * Turn off WiFi Hardware + * + * "DRIVER RSSI" -> "<ssid> Rssi xx" -> "%*s %*s %d", &rssi + * Return received signal strength indicator in -db for current AP + * + * "DRIVER LINKSPEED" -> "LinkSpeed xx" -> "%*s %d", &linkspd + * Return link speed in MBPS + * + * "DRIVER MACADDR" -> "Macaddr = xx.xx.xx.xx.xx.xx" -> "%*s = %s", &macadr + * Return mac address of the station + * + * "DRIVER SCAN-ACTIVE" -> "OK" if successful -> "OK" ? true : false + * Set scan type to active + * + * "DRIVER SCAN-PASSIVE" -> "OK" if successful -> "OK" ? true : false + * Set scan type to passive + *------------------------------------------------------------------------------ + * + * See libs/android_runtime/android_net_wifi_Wifi.cpp for more information + * on how these and other commands invoked. + * + * @param command is the string command + * @param reply is a buffer to receive a reply string + * @param reply_len on entry is the maximum length of + * reply buffer and 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); + +/** + * Issues a dhcp request returning 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 serverAddress 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..3ecaff8 --- /dev/null +++ b/led/Android.mk @@ -0,0 +1,12 @@ +# Copyright 2006 The Android Open Source Project + +ifeq ($(TARGET_PRODUCT),sooner) +LOCAL_SRC_FILES += led/led_sardine.c +else +ifeq ($(TARGET_PRODUCT),dream) +LOCAL_SRC_FILES += led/led_trout.c +else +LOCAL_SRC_FILES += led/led_stub.c +endif +endif + diff --git a/led/led_sardine.c b/led/led_sardine.c new file mode 100644 index 0000000..a53729f --- /dev/null +++ b/led/led_sardine.c @@ -0,0 +1,63 @@ +#include <hardware/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 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..644efe3 --- /dev/null +++ b/led/led_stub.c @@ -0,0 +1,7 @@ +#include <hardware/led.h> + +int +set_led_state(unsigned color, int on, int off) +{ + return 0; +} diff --git a/led/led_trout.c b/led/led_trout.c new file mode 100644 index 0000000..847b6bc --- /dev/null +++ b/led/led_trout.c @@ -0,0 +1,100 @@ +#include <hardware/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 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..a32e470 --- /dev/null +++ b/mount/IMountService.cpp @@ -0,0 +1,88 @@ +/* + * 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/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 +}; + +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); + } +}; + +IMPLEMENT_META_INTERFACE(MountService, "android.os.IMountService"); + + +}; diff --git a/power/Android.mk b/power/Android.mk new file mode 100644 index 0000000..fe671a5 --- /dev/null +++ b/power/Android.mk @@ -0,0 +1,4 @@ +# Copyright 2006 The Android Open Source Project + +LOCAL_SRC_FILES += power/power.c + diff --git a/power/power.c b/power/power.c new file mode 100644 index 0000000..907726a --- /dev/null +++ b/power/power.c @@ -0,0 +1,204 @@ +#include <hardware/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> + +enum { + ACQUIRE_PARTIAL_WAKE_LOCK = 0, + ACQUIRE_FULL_WAKE_LOCK, + RELEASE_WAKE_LOCK, + REQUEST_STATE, + OUR_FD_COUNT +}; + +const char * const PATHS[] = { + "/sys/android_power/acquire_partial_wake_lock", + "/sys/android_power/acquire_full_wake_lock", + "/sys/android_power/release_wake_lock", + "/sys/android_power/request_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 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 void +open_file_descriptors(void) +{ + 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; + } + g_fds[i] = fd; + } + + g_error = 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) { + open_file_descriptors(); + 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 if (lock == FULL_WAKE_LOCK) { + fd = g_fds[ACQUIRE_FULL_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; + + // LOGI("set_a_light(%s, %d)\n", path, value); + + fd = open(path, O_RDWR); + if (fd) { + char buffer[20]; + int bytes = sprintf(buffer, "%d\n", value); + write(fd, buffer, bytes); + close(fd); + } else { + LOGE("set_a_light failed to open %s\n", path); + } +} + +int +set_light_brightness(unsigned int mask, unsigned int 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) +{ + //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, "wake"); + else + len = sprintf(buf, "standby"); + 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/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..aacd1aa --- /dev/null +++ b/qemu_tracing/qemu_tracing.c @@ -0,0 +1,71 @@ +#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/sensors/Android.mk b/sensors/Android.mk new file mode 100644 index 0000000..00fdbad --- /dev/null +++ b/sensors/Android.mk @@ -0,0 +1,8 @@ +# Copyright 2008 The Android Open Source Project + +ifeq ($(TARGET_PRODUCT),dream) +LOCAL_SRC_FILES += sensors/sensors_trout.c +else +LOCAL_SRC_FILES += sensors/sensors_stub.c +endif + diff --git a/sensors/sensors_stub.c b/sensors/sensors_stub.c new file mode 100644 index 0000000..c096cf2 --- /dev/null +++ b/sensors/sensors_stub.c @@ -0,0 +1,60 @@ +/* + * 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 <hardware/sensors.h> +#include <unistd.h> + + +uint32_t sensors_control_init() { + return 0; +} + +/* returns a fd where to read the events from. the caller takes + * ownership of this fd */ +int sensors_control_open() { + return -1; +} + +/* returns a bitmask indicating which sensors are enabled */ +uint32_t sensors_control_activate(uint32_t sensors, uint32_t mask) { + return 0; +} + +/* set the delay between sensor events in ms */ +int sensors_control_delay(int32_t ms) { + return -1; +} + +/* initialize the sensor data read. doesn't take ownership of the fd */ +int sensors_data_open(int fd) { + return 0; +} + +/* done with sensor data */ +int sensors_data_close() { + return -1; +} + +/* returns a bitmask indicating which sensors have changed */ +int sensors_data_poll(sensors_data_t* data, uint32_t sensors_of_interest) { + usleep(60000000); + return 0; +} + +/* returns available sensors */ +uint32_t sensors_data_get_sensors() { + return 0; +} diff --git a/sensors/sensors_trout.c b/sensors/sensors_trout.c new file mode 100644 index 0000000..f3c0b3a --- /dev/null +++ b/sensors/sensors_trout.c @@ -0,0 +1,599 @@ +/* + * 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. + */ + +#define LOG_TAG "Sensors" + +#include <hardware/sensors.h> +#include <fcntl.h> +#include <errno.h> +#include <dirent.h> +#include <math.h> +#include <poll.h> + +#include <linux/input.h> +#include <linux/akm8976.h> + +#include <cutils/log.h> +#include <cutils/atomic.h> + +/*****************************************************************************/ + +#define AKM_DEVICE_NAME "/dev/akm8976_aot" + +#define SUPPORTED_SENSORS (SENSORS_ORIENTATION | \ + SENSORS_ACCELERATION | \ + SENSORS_MAGNETIC_FIELD | \ + SENSORS_ORIENTATION_RAW) + + +// sensor IDs must be a power of two and +// must match values in SensorManager.java +#define EVENT_TYPE_ACCEL_X ABS_X +#define EVENT_TYPE_ACCEL_Y ABS_Z +#define EVENT_TYPE_ACCEL_Z ABS_Y +#define EVENT_TYPE_ACCEL_STATUS ABS_WHEEL + +#define EVENT_TYPE_YAW ABS_RX +#define EVENT_TYPE_PITCH ABS_RY +#define EVENT_TYPE_ROLL ABS_RZ +#define EVENT_TYPE_ORIENT_STATUS ABS_RUDDER + +#define EVENT_TYPE_MAGV_X ABS_HAT0X +#define EVENT_TYPE_MAGV_Y ABS_HAT0Y +#define EVENT_TYPE_MAGV_Z ABS_BRAKE + +#define EVENT_TYPE_TEMPERATURE ABS_THROTTLE +#define EVENT_TYPE_STEP_COUNT ABS_GAS + +// 720 LSG = 1G +#define LSG (720.0f) + +// conversion of acceleration data to SI units (m/s^2) +#define CONVERT_A (GRAVITY_EARTH / LSG) +#define CONVERT_A_X (CONVERT_A) +#define CONVERT_A_Y (-CONVERT_A) +#define CONVERT_A_Z (CONVERT_A) + +// conversion of magnetic data to uT units +#define CONVERT_M (1.0f/16.0f) +#define CONVERT_M_X (CONVERT_M) +#define CONVERT_M_Y (CONVERT_M) +#define CONVERT_M_Z (CONVERT_M) + +#define SENSOR_STATE_MASK (0x7FFF) + +/*****************************************************************************/ + +static int sAkmFD = -1; +static uint32_t sActiveSensors = 0; + +/*****************************************************************************/ + +/* + * We use a Least Mean Squares filter to smooth out the output of the yaw + * sensor. + * + * The goal is to estimate the output of the sensor based on previous acquired + * samples. + * + * We approximate the input by a line with the equation: + * Z(t) = a * t + b + * + * We use the Least Mean Squares method to calculate a and b so that the + * distance between the line and the measured COUNT inputs Z(t) is minimal. + * + * In practice we only need to compute b, which is the value we're looking for + * (it's the estimated Z at t=0). However, to improve the latency a little bit, + * we're going to discard a certain number of samples that are too far from + * the estimated line and compute b again with the new (trimmed down) samples. + * + * notes: + * 'a' is the slope of the line, and physicaly represent how fast the input + * is changing. In our case, how fast the yaw is changing, that is, how fast the + * user is spinning the device (in degre / nanosecond). This value should be + * zero when the device is not moving. + * + * The minimum distance between the line and the samples (which we are not + * explicitely computing here), is an indication of how bad the samples are + * and gives an idea of the "quality" of the estimation (well, really of the + * sensor values). + * + */ + +/* sensor rate in me */ +#define SENSORS_RATE_MS 20 +/* timeout (constant value) in ms */ +#define SENSORS_TIMEOUT_MS 100 +/* # of samples to look at in the past for filtering */ +#define COUNT 24 +/* prediction ratio */ +#define PREDICTION_RATIO (1.0f/3.0f) +/* prediction time in seconds (>=0) */ +#define PREDICTION_TIME ((SENSORS_RATE_MS*COUNT/1000.0f)*PREDICTION_RATIO) + +static float mV[COUNT*2]; +static float mT[COUNT*2]; +static int mIndex; + +static inline +float normalize(float x) +{ + x *= (1.0f / 360.0f); + if (fabsf(x) >= 0.5f) + x = x - ceilf(x + 0.5f) + 1.0f; + if (x < 0) + x += 1.0f; + x *= 360.0f; + return x; +} + +static void LMSInit(void) +{ + memset(mV, 0, sizeof(mV)); + memset(mT, 0, sizeof(mT)); + mIndex = COUNT; +} + +static float LMSFilter(int64_t time, int v) +{ + const float ns = 1.0f / 1000000000.0f; + const float t = time*ns; + float v1 = mV[mIndex]; + if ((v-v1) > 180) { + v -= 360; + } else if ((v1-v) > 180) { + v += 360; + } + /* Manage the circular buffer, we write the data twice spaced by COUNT + * values, so that we don't have to memcpy() the array when it's full */ + mIndex++; + if (mIndex >= COUNT*2) + mIndex = COUNT; + mV[mIndex] = v; + mT[mIndex] = t; + mV[mIndex-COUNT] = v; + mT[mIndex-COUNT] = t; + + float A, B, C, D, E; + float a, b; + int i; + + A = B = C = D = E = 0; + for (i=0 ; i<COUNT-1 ; i++) { + const int j = mIndex - 1 - i; + const float Z = mV[j]; + const float T = 0.5f*(mT[j] + mT[j+1]) - t; + float dT = mT[j] - mT[j+1]; + dT *= dT; + A += Z*dT; + B += T*(T*dT); + C += (T*dT); + D += Z*(T*dT); + E += dT; + } + b = (A*B + C*D) / (E*B + C*C); + a = (E*b - A) / C; + float f = b + PREDICTION_TIME*a; + + //LOGD("A=%f, B=%f, C=%f, D=%f, E=%f", A,B,C,D,E); + //LOGD("%lld %d %f %f", time, v, f, a); + + f = normalize(f); + return f; +} + +/*****************************************************************************/ + +static int open_input() +{ + /* scan all input drivers and look for "compass" */ + int fd = -1; + const char *dirname = "/dev/input"; + char devname[PATH_MAX]; + char *filename; + DIR *dir; + struct dirent *de; + dir = opendir(dirname); + if(dir == NULL) + return -1; + strcpy(devname, dirname); + filename = devname + strlen(devname); + *filename++ = '/'; + while((de = readdir(dir))) { + if(de->d_name[0] == '.' && + (de->d_name[1] == '\0' || + (de->d_name[1] == '.' && de->d_name[2] == '\0'))) + continue; + strcpy(filename, de->d_name); + fd = open(devname, O_RDONLY); + if (fd>=0) { + char name[80]; + if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) < 1) { + name[0] = '\0'; + } + if (!strcmp(name, "compass")) { + LOGD("using %s (name=%s)", devname, name); + break; + } + close(fd); + fd = -1; + } + } + closedir(dir); + + if (fd < 0) { + LOGE("Couldn't find or open 'compass' driver (%s)", strerror(errno)); + } + return fd; +} + +static int open_akm() +{ + if (sAkmFD <= 0) { + sAkmFD = open(AKM_DEVICE_NAME, O_RDONLY); + LOGD("%s, fd=%d", __PRETTY_FUNCTION__, sAkmFD); + LOGE_IF(sAkmFD<0, "Couldn't open %s (%s)", + AKM_DEVICE_NAME, strerror(errno)); + if (sAkmFD >= 0) { + sActiveSensors = 0; + } + } + return sAkmFD; +} + +static void close_akm() +{ + if (sAkmFD > 0) { + LOGD("%s, fd=%d", __PRETTY_FUNCTION__, sAkmFD); + close(sAkmFD); + sAkmFD = -1; + } +} + +static void enable_disable(int fd, uint32_t sensors, uint32_t mask) +{ + if (fd<0) return; + short flags; + + if (sensors & SENSORS_ORIENTATION_RAW) { + sensors |= SENSORS_ORIENTATION; + mask |= SENSORS_ORIENTATION; + } else if (mask & SENSORS_ORIENTATION_RAW) { + mask |= SENSORS_ORIENTATION; + } + + if (mask & SENSORS_ORIENTATION) { + flags = (sensors & SENSORS_ORIENTATION) ? 1 : 0; + if (ioctl(fd, ECS_IOCTL_APP_SET_MFLAG, &flags) < 0) { + LOGE("ECS_IOCTL_APP_SET_MFLAG error (%s)", strerror(errno)); + } + } + if (mask & SENSORS_ACCELERATION) { + flags = (sensors & SENSORS_ACCELERATION) ? 1 : 0; + if (ioctl(fd, ECS_IOCTL_APP_SET_AFLAG, &flags) < 0) { + LOGE("ECS_IOCTL_APP_SET_AFLAG error (%s)", strerror(errno)); + } + } + if (mask & SENSORS_TEMPERATURE) { + flags = (sensors & SENSORS_TEMPERATURE) ? 1 : 0; + if (ioctl(fd, ECS_IOCTL_APP_SET_TFLAG, &flags) < 0) { + LOGE("ECS_IOCTL_APP_SET_TFLAG error (%s)", strerror(errno)); + } + } +#ifdef ECS_IOCTL_APP_SET_MVFLAG + if (mask & SENSORS_MAGNETIC_FIELD) { + flags = (sensors & SENSORS_MAGNETIC_FIELD) ? 1 : 0; + if (ioctl(fd, ECS_IOCTL_APP_SET_MVFLAG, &flags) < 0) { + LOGE("ECS_IOCTL_APP_SET_MVFLAG error (%s)", strerror(errno)); + } + } +#endif +} + +static uint32_t read_sensors_state(int fd) +{ + if (fd<0) return 0; + short flags; + uint32_t sensors = 0; + // read the actual value of all sensors + if (!ioctl(fd, ECS_IOCTL_APP_GET_MFLAG, &flags)) { + if (flags) sensors |= SENSORS_ORIENTATION; + else sensors &= ~SENSORS_ORIENTATION; + } + if (!ioctl(fd, ECS_IOCTL_APP_GET_AFLAG, &flags)) { + if (flags) sensors |= SENSORS_ACCELERATION; + else sensors &= ~SENSORS_ACCELERATION; + } + if (!ioctl(fd, ECS_IOCTL_APP_GET_TFLAG, &flags)) { + if (flags) sensors |= SENSORS_TEMPERATURE; + else sensors &= ~SENSORS_TEMPERATURE; + } +#ifdef ECS_IOCTL_APP_SET_MVFLAG + if (!ioctl(fd, ECS_IOCTL_APP_GET_MVFLAG, &flags)) { + if (flags) sensors |= SENSORS_MAGNETIC_FIELD; + else sensors &= ~SENSORS_MAGNETIC_FIELD; + } +#endif + return sensors; +} + +/*****************************************************************************/ + +uint32_t sensors_control_init() +{ + return SUPPORTED_SENSORS; +} + +int sensors_control_open() +{ + return open_input(); +} + +uint32_t sensors_control_activate(uint32_t sensors, uint32_t mask) +{ + mask &= SUPPORTED_SENSORS; + uint32_t active = sActiveSensors; + uint32_t new_sensors = (active & ~mask) | (sensors & mask); + uint32_t changed = active ^ new_sensors; + if (changed) { + int fd = open_akm(); + if (fd < 0) return 0; + + if (!active && new_sensors) { + // force all sensors to be updated + changed = SUPPORTED_SENSORS; + } + + enable_disable(fd, new_sensors, changed); + + if (active && !new_sensors) { + // close the driver + close_akm(); + } + sActiveSensors = active = new_sensors; + LOGD("sensors=%08x, real=%08x", + sActiveSensors, read_sensors_state(fd)); + } + return active; +} + +int sensors_control_delay(int32_t ms) +{ +#ifdef ECS_IOCTL_APP_SET_DELAY + if (sAkmFD <= 0) { + return -1; + } + short delay = ms; + if (!ioctl(sAkmFD, ECS_IOCTL_APP_SET_DELAY, &delay)) { + return -errno; + } + return 0; +#else + return -1; +#endif +} + +/*****************************************************************************/ + +#define MAX_NUM_SENSORS 8 +static int sInputFD = -1; +static const int ID_O = 0; +static const int ID_A = 1; +static const int ID_T = 2; +static const int ID_M = 3; +static const int ID_OR = 7; // orientation raw +static sensors_data_t sSensors[MAX_NUM_SENSORS]; +static uint32_t sPendingSensors; + +int sensors_data_open(int fd) +{ + int i; + LMSInit(); + memset(&sSensors, 0, sizeof(sSensors)); + for (i=0 ; i<MAX_NUM_SENSORS ; i++) { + // by default all sensors have high accuracy + // (we do this because we don't get an update if the value doesn't + // change). + sSensors[i].vector.status = SENSOR_STATUS_ACCURACY_HIGH; + } + sPendingSensors = 0; + sInputFD = dup(fd); + LOGD("sensors_data_open: fd = %d", sInputFD); + return 0; +} + +int sensors_data_close() +{ + close(sInputFD); + sInputFD = -1; + return 0; +} + +static int pick_sensor(sensors_data_t* values) +{ + uint32_t mask = SENSORS_MASK; + while(mask) { + uint32_t i = 31 - __builtin_clz(mask); + mask &= ~(1<<i); + if (sPendingSensors & (1<<i)) { + sPendingSensors &= ~(1<<i); + *values = sSensors[i]; + values->sensor = (1<<i); + LOGD_IF(0, "%d [%f, %f, %f]", (1<<i), + values->vector.x, + values->vector.y, + values->vector.z); + return (1<<i); + } + } + LOGE("No sensor to return!!! sPendingSensors=%08x", sPendingSensors); + // we may end-up in a busy loop, slow things down, just in case. + usleep(100000); + return -1; +} + +int sensors_data_poll(sensors_data_t* values, uint32_t sensors_of_interest) +{ + struct input_event event; + int nread; + int64_t t; + + int fd = sInputFD; + if (fd <= 0) + return -1; + + // there are pending sensors, returns them now... + if (sPendingSensors) { + return pick_sensor(values); + } + + uint32_t new_sensors = 0; + struct pollfd fds; + fds.fd = fd; + fds.events = POLLIN; + fds.revents = 0; + + // wait until we get a complete event for an enabled sensor + while (1) { + nread = 0; + if (sensors_of_interest & SENSORS_ORIENTATION) { + /* We do some special processing if the orientation sensor is + * activated. In particular the yaw value is filtered with a + * LMS filter. Since the kernel only sends an event when the + * value changes, we need to wake up at regular intervals to + * generate an output value (the output value may not be + * constant when the input value is constant) + */ + int err = poll(&fds, 1, SENSORS_TIMEOUT_MS); + if (err == 0) { + struct timespec time; + time.tv_sec = time.tv_nsec = 0; + clock_gettime(CLOCK_MONOTONIC, &time); + + /* generate an output value */ + t = time.tv_sec*1000000000LL+time.tv_nsec; + new_sensors |= SENSORS_ORIENTATION; + sSensors[ID_O].orientation.yaw = + LMSFilter(t, sSensors[ID_O].orientation.yaw); + + /* generate a fake sensors event */ + event.type = EV_SYN; + event.time.tv_sec = time.tv_sec; + event.time.tv_usec = time.tv_nsec/1000; + nread = sizeof(event); + } + } + if (nread == 0) { + /* read the next event */ + nread = read(fd, &event, sizeof(event)); + } + if (nread == sizeof(event)) { + uint32_t v; + if (event.type == EV_ABS) { + //LOGD("type: %d code: %d value: %-5d time: %ds", + // event.type, event.code, event.value, + // (int)event.time.tv_sec); + switch (event.code) { + + case EVENT_TYPE_ACCEL_X: + new_sensors |= SENSORS_ACCELERATION; + sSensors[ID_A].acceleration.x = event.value * CONVERT_A_X; + break; + case EVENT_TYPE_ACCEL_Y: + new_sensors |= SENSORS_ACCELERATION; + sSensors[ID_A].acceleration.y = event.value * CONVERT_A_Y; + break; + case EVENT_TYPE_ACCEL_Z: + new_sensors |= SENSORS_ACCELERATION; + sSensors[ID_A].acceleration.z = event.value * CONVERT_A_Z; + break; + + case EVENT_TYPE_MAGV_X: + new_sensors |= SENSORS_MAGNETIC_FIELD; + sSensors[ID_M].magnetic.x = event.value * CONVERT_M_X; + break; + case EVENT_TYPE_MAGV_Y: + new_sensors |= SENSORS_MAGNETIC_FIELD; + sSensors[ID_M].magnetic.y = event.value * CONVERT_M_Y; + break; + case EVENT_TYPE_MAGV_Z: + new_sensors |= SENSORS_MAGNETIC_FIELD; + sSensors[ID_M].magnetic.z = event.value * CONVERT_M_Z; + break; + + case EVENT_TYPE_YAW: + new_sensors |= SENSORS_ORIENTATION | SENSORS_ORIENTATION_RAW; + t = event.time.tv_sec*1000000000LL + + event.time.tv_usec*1000; + sSensors[ID_O].orientation.yaw = + (sensors_of_interest & SENSORS_ORIENTATION) ? + LMSFilter(t, event.value) : event.value; + sSensors[ID_OR].orientation.yaw = event.value; + break; + case EVENT_TYPE_PITCH: + new_sensors |= SENSORS_ORIENTATION | SENSORS_ORIENTATION_RAW; + sSensors[ID_O].orientation.pitch = event.value; + sSensors[ID_OR].orientation.pitch = event.value; + break; + case EVENT_TYPE_ROLL: + new_sensors |= SENSORS_ORIENTATION | SENSORS_ORIENTATION_RAW; + sSensors[ID_O].orientation.roll = event.value; + sSensors[ID_OR].orientation.roll = event.value; + break; + + case EVENT_TYPE_TEMPERATURE: + new_sensors |= SENSORS_TEMPERATURE; + sSensors[ID_T].temperature = event.value; + break; + + case EVENT_TYPE_STEP_COUNT: + // step count (only reported in MODE_FFD) + // we do nothing with it for now. + break; + case EVENT_TYPE_ACCEL_STATUS: + // accuracy of the calibration (never returned!) + //LOGD("G-Sensor status %d", event.value); + break; + case EVENT_TYPE_ORIENT_STATUS: + // accuracy of the calibration + v = (uint32_t)(event.value & SENSOR_STATE_MASK); + LOGD_IF(sSensors[ID_O].orientation.status != (uint8_t)v, + "M-Sensor status %d", v); + sSensors[ID_O].orientation.status = (uint8_t)v; + sSensors[ID_OR].orientation.status = (uint8_t)v; + break; + } + } else if (event.type == EV_SYN) { + if (new_sensors) { + sPendingSensors = new_sensors; + int64_t t = event.time.tv_sec*1000000000LL + + event.time.tv_usec*1000; + while (new_sensors) { + uint32_t i = 31 - __builtin_clz(new_sensors); + new_sensors &= ~(1<<i); + sSensors[i].time = t; + } + return pick_sensor(values); + } + } + } + } +} + +uint32_t sensors_data_get_sensors() { + return SUPPORTED_SENSORS; +} + 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..4432b33 --- /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/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..62cc7a1 --- /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/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..fcea21c --- /dev/null +++ b/vibrator/vibrator.c @@ -0,0 +1,36 @@ +#include <hardware/vibrator.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]; + + 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() +{ + /* constant on, up to maximum allowed time */ + return sendit(-1); +} + +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..68b1a1e --- /dev/null +++ b/wifi/wifi.c @@ -0,0 +1,399 @@ +/* + * 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/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" + +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)); + 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 = 40; /* wait at most 20 seconds for completion */ + + if (check_driver_loaded()) { + return 0; + } + insmod(DRIVER_MODULE_PATH); + property_set("ctl.start", FIRMWARE_LOADER); + while (count-- > 0) { + usleep(500000); + 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; + } + } + property_set(DRIVER_PROP_NAME, "timeout"); + return -1; +} + +int wifi_unload_driver() +{ + if (rmmod(DRIVER_MODULE_NAME) == 0) { + usleep(1000000); + property_set(DRIVER_PROP_NAME, "unloaded"); + return 0; + } else + return -1; +} + +static int control_supplicant(int startIt) +{ + char supp_status[PROPERTY_VALUE_MAX] = {'\0'}; + const char *ctrl_prop = (startIt ? "ctl.start" : "ctl.stop"); + const char *desired_status = (startIt ? "running" : "stopped"); + int count = 20; /* wait at most 20 seconds for completion */ + + if (property_get(SUPP_PROP_NAME, supp_status, NULL) + && strcmp(supp_status, desired_status) == 0) { + return 0; /* supplicant already running */ + } + property_set(ctrl_prop, SUPPLICANT_NAME); + + while (count-- > 0) { + usleep(1000000); + if (property_get(SUPP_PROP_NAME, supp_status, NULL)) { + if (strcmp(supp_status, desired_status) == 0) + return 0; + } + } + 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() +{ + /* 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; + } + return control_supplicant(1); +} + +int wifi_stop_supplicant() +{ + return control_supplicant(0); +} + +int wifi_connect_to_supplicant() +{ + char ifname[256]; + static int cleaned_up = 0; + + 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) { + LOGD("Unable to open connection to supplicant on \"%s\": %s", + ifname, strerror(errno)); + /* + * errno == ENOENT means the supplicant daemon isn't + * running. Take this opportunity to clear out any + * stale socket files that might be left over. Note + * there's a possible race with the command line client + * trying to connect to the daemon, but it would require + * that the supplicant be started and the command line + * client connect to it during the window between the + * error check and the removal of the files. And in + * any event, the remedy is that the user would simply + * have to run the command line program again. + */ + if (!cleaned_up && (errno == ENOENT || errno == EADDRINUSE)) { + cleaned_up = 1; /* do this just once */ + wpa_ctrl_cleanup(); + } + 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); +} |