Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Release powerd 4.0.0-rc1 to the public

  • Loading branch information...
commit fbf56b4a02b74e06a6ab31f30c67cda3fddcbd03 0 parents
@smtodwal smtodwal authored kuta42 committed
Showing with 7,996 additions and 0 deletions.
  1. +25 −0 .gitignore
  2. +136 −0 CMakeLists.txt
  3. +108 −0 README.md
  4. +240 −0 doc/Doxyfile.in
  5. +35 −0 include/powerd-glib.h
  6. +37 −0 include/powerd-lunaservice.h
  7. +75 −0 include/powerd.h
  8. +45 −0 include/private/clock.h
  9. +119 −0 include/private/debug.h
  10. +35 −0 include/private/idler.h
  11. +52 −0 include/private/powerdltp.h
  12. +53 −0 include/private/wait.h
  13. +43 −0 libpowerd/CMakeLists.txt
  14. +163 −0 libpowerd/clock.c
  15. +725 −0 libpowerd/commands.c
  16. +152 −0 libpowerd/init.c
  17. +38 −0 libpowerd/init.h
  18. +28 −0 libpowerd/powerd.pc.in
  19. +217 −0 libpowerd/wait.c
  20. +44 −0 powerd/CMakeLists.txt
  21. +385 −0 powerd/alarms/timeout_alarm.c
  22. +75 −0 powerd/alarms/timeout_alarm.h
  23. +469 −0 powerd/charging/battery.c
  24. +83 −0 powerd/charging/battery.h
  25. +353 −0 powerd/charging/batterypoll.c
  26. +24 −0 powerd/charging/batterypoll.h
  27. +347 −0 powerd/charging/charger.c
  28. +40 −0 powerd/charging/charger.h
  29. +714 −0 powerd/charging/charging_logic.c
  30. +69 −0 powerd/charging/charging_logic.h
  31. +229 −0 powerd/charging/suspend.c
  32. +119 −0 powerd/com_palm_power_lunabus.c
  33. +177 −0 powerd/config.c
  34. +51 −0 powerd/config.h
  35. +100 −0 powerd/etc/event.d/powerd
  36. +162 −0 powerd/main.c
  37. +36 −0 powerd/main.h
  38. +25 −0 powerd/preferences/powerd.conf
  39. +263 −0 powerd/suspend/shutdown.c
  40. +42 −0 powerd/suspend/suspend.h
  41. +270 −0 powerd/suspend/suspend_ipc.c
  42. +219 −0 powerd/timesaver.c
  43. +27 −0 powerd/timesaver.h
  44. +33 −0 powerd/utils/common.h
  45. +157 −0 powerd/utils/init.c
  46. +48 −0 powerd/utils/init.h
  47. +199 −0 powerd/utils/logging.c
  48. +43 −0 powerd/utils/logging.h
  49. +81 −0 powerd/utils/lunaservice_utils.c
  50. +30 −0 powerd/utils/lunaservice_utils.h
  51. +146 −0 powerd/utils/sysfs.c
  52. +30 −0 powerd/utils/sysfs.h
  53. +265 −0 powerd/utils/timersource.c
  54. +38 −0 powerd/utils/timersource.h
  55. +137 −0 powerd/utils/uevent.c
  56. +28 −0 powerd/utils/uevent.h
  57. +33 −0 service/com.palm.power.json.prv
  58. +33 −0 service/com.palm.power.json.pub
  59. +23 −0 service/com.palm.power.service.prv
  60. +23 −0 service/com.palm.power.service.pub
25 .gitignore
@@ -0,0 +1,25 @@
+# @@@LICENSE
+#
+# Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+#
+# 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.
+#
+# LICENSE@@@
+BUILD*
+CMakeCache.txt
+cmake_install.cmake
+CMakeFiles
+doc/Doxyfile
+doc/html
+patches
+libpowerd/*.pc
136 CMakeLists.txt
@@ -0,0 +1,136 @@
+# @@@LICENSE
+#
+# Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+#
+# 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.
+#
+# LICENSE@@@
+
+#
+# powerd/CMakeLists.txt
+#
+
+
+cmake_minimum_required(VERSION 2.6)
+
+project(powerd)
+
+set(POWERD_API_VERSION_MAJOR 4)
+set(POWERD_API_VERSION_MINOR 0)
+set(POWERD_API_VERSION_PATCH 0)
+set(POWERD_LIBRARY_VERSION "${POWERD_API_VERSION_MAJOR}.${POWERD_API_VERSION_MINOR}.${POWERD_API_VERSION_PATCH}")
+set(POWERD_LIBRARY_NAME "${CMAKE_PROJECT_NAME}")
+
+# Make sure the build system's version of this component matches what we're building.
+# The intent is for it to pass in POWERD_COMPONENT_VERSION via the command line.
+if(DEFINED POWERD_COMPONENT_VERSION)
+ if (NOT (POWERD_LIBRARY_VERSION STREQUAL POWERD_COMPONENT_VERSION))
+ message(FATAL_ERROR "Component version from build system (${POWERD_COMPONENT_VERSION}) != library version (${POWERD_LIBRARY_VERSION})")
+ endif()
+endif()
+
+# XXX Why is CMAKE_BUILD_TYPE empty under Ubuntu?
+if(NOT CMAKE_BUILD_TYPE)
+ set (CMAKE_BUILD_TYPE "Release")
+endif()
+
+if(NOT DEFINED ENV{PKG_CONFIG_PATH})
+ set(ENV{PKG_CONFIG_PATH} "${CMAKE_INSTALL_PREFIX}/lib/pkgconfig")
+endif()
+
+if(CMAKE_INSTALL_PREFIX STREQUAL "/usr")
+ set(SYSCONFDIR_FULL "/etc")
+else()
+ set(SYSCONFDIR_FULL "${CMAKE_INSTALL_PREFIX}/etc")
+endif()
+
+message("")
+
+message(STATUS "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}")
+message(STATUS "CMAKE_FIND_ROOT_PATH: ${CMAKE_FIND_ROOT_PATH}")
+message(STATUS "ENV{PKG_CONFIG_PATH}: $ENV{PKG_CONFIG_PATH}")
+message(STATUS "CMAKE_INSTALL_PREFIX: ${CMAKE_INSTALL_PREFIX}")
+
+# Note that TARGET_CORE_OS is no longer used, but keep it around in case it turns out to be needed later.
+set(DEFAULT_TARGET_CORE_OS "ubuntu" CACHE INTERNAL "The default core OS for which to build")
+
+# Should specify a core OS (ubuntu, rockhopper, etc.)
+if(TARGET_CORE_OS)
+ message(STATUS "TARGET_CORE_OS: ${TARGET_CORE_OS}")
+else()
+ set(TARGET_CORE_OS "${DEFAULT_TARGET_CORE_OS}")
+ message(STATUS "No TARGET_CORE_OS value specified -- defaulting to ${TARGET_CORE_OS}")
+endif()
+set(TARGET_CORE_OS ${TARGET_CORE_OS} CACHE STRING "The core OS for which to build")
+
+message("")
+
+
+macro(add_flags flags)
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flags}")
+endmacro()
+
+macro(add_linker_flags flags)
+ # Appending to CMAKE_EXE_LINKER_FLAGS fails to add them to the link command line -- why?
+ # Note that using add_definitions() also fails to add to the link command line.
+ add_flags("${flags}")
+endmacro()
+
+
+include(FindPkgConfig)
+
+# Check that we have glib-2.0
+pkg_check_modules(GLIB2 REQUIRED glib-2.0)
+add_definitions(${GLIB2_CFLAGS})
+
+# Check that we have luna-service2
+pkg_check_modules(LUNASERVICE2 REQUIRED luna-service2)
+add_definitions(${LUNASERVICE2_CFLAGS})
+
+# luna-service2 requires cjson; make sure it's available
+pkg_check_modules(CJSON REQUIRED cjson)
+add_definitions(${CJSON_CFLAGS})
+
+
+# Specifying this causes "warning: 'struct timespec' declared inside parameter list" in libpowerd/clock.h.
+#add_definitions("-std=c99")
+
+# Turn on all useful warnings, but don't specify -Werror -- having warnings break the build makes
+# switching to a new compiler a lengthy and painful ordeal.
+add_definitions("-Wall")
+
+# Specify which symbols are to be exported
+# TODO: Create this
+#add_linker_flags("-Wl,--version-script=${PROJECT_SOURCE_DIR}/src/${POWERD_LIBRARY_NAME}Exports.map")
+
+# Require that all undefined symbols are satisfied by the libraries from target_link_libraries()
+add_linker_flags("-Wl,--no-undefined")
+# XXX_ The libraries that come with gcc fail when --no-allow-shlib-undefined is specified
+#add_linker_flags("-Wl,--no-allow-shlib-undefined")
+
+
+add_subdirectory(libpowerd)
+add_subdirectory(powerd)
+
+
+# This adds a target called "docs" (i.e., make docs). doxygen and dot
+# (from graphviz) are expected to be available.
+# ${PROJECT_BINARY_DIR} is the build directory and ${PROJECT_SOURCE_DIR}
+# is the source directory.
+configure_file(${PROJECT_SOURCE_DIR}/doc/Doxyfile.in
+ ${PROJECT_BINARY_DIR}/doc/Doxyfile)
+
+add_custom_target(docs
+ doxygen ${PROJECT_BINARY_DIR}/doc/Doxyfile
+ SOURCES ${PROJECT_SOURCE_DIR}/doc/Doxyfile.in
+ WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/doc)
108 README.md
@@ -0,0 +1,108 @@
+powerd
+======
+Powerd is one of the primary daemons that is started when webOS boots. It is responsible for monitoring battery parameters like temperature, current, voltage and other inputs, and making decisions about battery charging. It interfaces with the underlying hardware using the Nyx client library, talking to the battery and charger modules for the platform. At the same time it exposes the battery and charging information to the upper layers through the Luna Service Bus. Powerd also has the capability to run the necessary CTIA checks for temperature limits on the platform.
+
+How to Build on Linux
+=====================
+
+## Dependencies
+
+Below are the tools and libraries (and their minimum versions) required to build powerd:
+
+* cmake 2.6
+* gcc 4.3
+* glib-2.0 2.16.6
+* make (any version)
+* openwebos/cjson 1.8.0
+* openwebos/luna-service2 3.0.0
+* openwebos/nyx-lib 2.0.0 RC 2
+* pkg-config 0.22
+
+
+## Building
+
+Once you have downloaded the source, execute the following to build it:
+
+ $ mkdir BUILD
+ $ cd BUILD
+ $ cmake ..
+ $ make
+ $ sudo make install
+
+The header files will be installed under
+
+ /usr/local/include/powerd
+
+the libraries and pkg-config file under
+
+ /usr/local/lib
+
+the daemon under
+
+ /usr/local/sbin
+
+the default preferences file under
+
+ /usr/local/etc/default
+
+and the upstart script under
+
+ /usr/local/etc/event.d
+
+You can install it elsewhere by supplying a value for _CMAKE\_INSTALL\_PREFIX_ when invoking _cmake_. For example:
+
+ $ cmake -D CMAKE_INSTALL_PREFIX:STRING=$HOME/projects/openwebos ..
+ $ make
+ $ make install
+
+will install the files in subdirectories of $HOME/projects/openwebos instead of subdirectories of /usr/local.
+
+Specifying _CMAKE\_INSTALL\_PREFIX_ also causes the pkg-config files under it to be used to find headers and libraries. To have _pkg-config_ look in a different tree, set the environment variable PKG_CONFIG_PATH to the path to its _lib/pkgconfig_ subdirectory.
+
+## Uninstalling
+
+From the directory where you originally ran _make install_, invoke:
+
+ $ sudo xargs rm < install_manifest.txt
+
+## Generating documentation
+
+The tools required to generate the documentation are:
+
+* doxygen 1.6.3
+* graphviz 2.20.2
+
+Once you have run _cmake_, execute the following to generate the documentation:
+
+ $ make docs
+
+To view the generated HTML documentation, point your browser to
+
+ doc/html/index.html
+
+## Linking against libpowerd
+
+If your system has pkg-config then you can just add this to your makefile:
+
+ CFLAGS += $(shell pkg-config --cflags powerd)
+ LDFLAGS += $(shell pkg-config --libs powerd)
+
+# Copyright and License Information
+
+All content, including all source code files and documentation files in this repository are:
+
+ Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+
+All content, including all source code files and documentation files in this repository are:
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this content 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.
+
240 doc/Doxyfile.in
@@ -0,0 +1,240 @@
+# @@@LICENSE
+#
+# Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+#
+# 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.
+#
+# LICENSE@@@
+
+# Doxyfile 1.6.3
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+DOXYFILE_ENCODING = UTF-8
+PROJECT_NAME = @CMAKE_PROJECT_NAME@
+PROJECT_NUMBER = @POWERD_LIBRARY_VERSION@
+OUTPUT_DIRECTORY = .
+CREATE_SUBDIRS = NO
+OUTPUT_LANGUAGE = English
+BRIEF_MEMBER_DESC = YES
+REPEAT_BRIEF = YES
+ALWAYS_DETAILED_SEC = NO
+INLINE_INHERITED_MEMB = NO
+FULL_PATH_NAMES = YES
+STRIP_FROM_PATH = @PROJECT_SOURCE_DIR@
+STRIP_FROM_INC_PATH =
+SHORT_NAMES = NO
+JAVADOC_AUTOBRIEF = YES
+QT_AUTOBRIEF = NO
+MULTILINE_CPP_IS_BRIEF = NO
+INHERIT_DOCS = YES
+SEPARATE_MEMBER_PAGES = NO
+TAB_SIZE = 8
+ALIASES =
+OPTIMIZE_OUTPUT_FOR_C = YES
+BUILTIN_STL_SUPPORT = NO
+DISTRIBUTE_GROUP_DOC = NO
+SUBGROUPING = YES
+TYPEDEF_HIDES_STRUCT = NO
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL = YES
+EXTRACT_PRIVATE = YES
+EXTRACT_STATIC = YES
+EXTRACT_LOCAL_CLASSES = YES
+EXTRACT_LOCAL_METHODS = NO
+EXTRACT_ANON_NSPACES = NO
+HIDE_UNDOC_MEMBERS = NO
+HIDE_UNDOC_CLASSES = NO
+HIDE_FRIEND_COMPOUNDS = NO
+HIDE_IN_BODY_DOCS = NO
+INTERNAL_DOCS = YES
+CASE_SENSE_NAMES = YES
+HIDE_SCOPE_NAMES = NO
+SHOW_INCLUDE_FILES = YES
+FORCE_LOCAL_INCLUDES = NO
+INLINE_INFO = YES
+SORT_MEMBER_DOCS = YES
+SORT_BRIEF_DOCS = NO
+SORT_MEMBERS_CTORS_1ST = NO
+SORT_GROUP_NAMES = YES
+SORT_BY_SCOPE_NAME = NO
+GENERATE_TODOLIST = NO
+GENERATE_TESTLIST = NO
+GENERATE_BUGLIST = NO
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS =
+MAX_INITIALIZER_LINES = 30
+SHOW_USED_FILES = YES
+SHOW_DIRECTORIES = YES
+SHOW_FILES = YES
+SHOW_NAMESPACES = YES
+FILE_VERSION_FILTER =
+LAYOUT_FILE =
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET = YES
+WARNINGS = NO
+WARN_IF_UNDOCUMENTED = NO
+WARN_IF_DOC_ERROR = YES
+WARN_NO_PARAMDOC = NO
+WARN_FORMAT = "$file:$line: $text"
+WARN_LOGFILE =
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT = @PROJECT_SOURCE_DIR@/libpowerd @PROJECT_SOURCE_DIR@/powerd @PROJECT_SOURCE_DIR@/include
+INPUT_ENCODING = UTF-8
+FILE_PATTERNS = *.c *.h
+RECURSIVE = YES
+EXCLUDE =
+EXCLUDE_SYMLINKS = NO
+EXCLUDE_PATTERNS =
+EXCLUDE_SYMBOLS =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH =
+EXAMPLE_PATTERNS =
+EXAMPLE_RECURSIVE = NO
+IMAGE_PATH =
+INPUT_FILTER =
+FILTER_PATTERNS =
+FILTER_SOURCE_FILES = NO
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER = YES
+INLINE_SOURCES = NO
+STRIP_CODE_COMMENTS = YES
+REFERENCED_BY_RELATION = YES
+REFERENCES_RELATION = YES
+REFERENCES_LINK_SOURCE = YES
+USE_HTAGS = NO
+VERBATIM_HEADERS = YES
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX = NO
+COLS_IN_ALPHA_INDEX = 5
+IGNORE_PREFIX =
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML = YES
+HTML_OUTPUT = html
+HTML_FILE_EXTENSION = .html
+HTML_HEADER =
+HTML_FOOTER =
+HTML_STYLESHEET =
+HTML_TIMESTAMP = YES
+HTML_ALIGN_MEMBERS = YES
+HTML_DYNAMIC_SECTIONS = NO
+GENERATE_HTMLHELP = NO
+GENERATE_CHI = NO
+BINARY_TOC = NO
+TOC_EXPAND = NO
+DISABLE_INDEX = NO
+ENUM_VALUES_PER_LINE = 1
+GENERATE_TREEVIEW = YES
+TREEVIEW_WIDTH = 250
+FORMULA_FONTSIZE = 10
+SEARCHENGINE = YES
+SERVER_BASED_SEARCH = NO
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX = NO
+LATEX_OUTPUT = latex
+COMPACT_LATEX = NO
+PAPER_TYPE = a4wide
+EXTRA_PACKAGES =
+LATEX_HEADER =
+PDF_HYPERLINKS = NO
+USE_PDFLATEX = NO
+LATEX_BATCHMODE = NO
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF = NO
+RTF_OUTPUT = rtf
+COMPACT_RTF = NO
+RTF_HYPERLINKS = NO
+RTF_STYLESHEET_FILE =
+RTF_EXTENSIONS_FILE =
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN = NO
+MAN_OUTPUT = man
+MAN_EXTENSION = .3
+MAN_LINKS = YES
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML = NO
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING = YES
+MACRO_EXPANSION = YES
+EXPAND_ONLY_PREDEF = YES
+SEARCH_INCLUDES = YES
+INCLUDE_PATH =
+INCLUDE_FILE_PATTERNS = *.h
+PREDEFINED = "G_BEGIN_DECLS=" "G_END_DECLS="
+EXPAND_AS_DEFINED =
+SKIP_FUNCTION_MACROS = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+TAGFILES =
+GENERATE_TAGFILE =
+ALLEXTERNALS = NO
+EXTERNAL_GROUPS = YES
+PERL_PATH = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS = YES
+MSCGEN_PATH =
+HIDE_UNDOC_RELATIONS = YES
+HAVE_DOT = YES
+DOT_FONTNAME = FreeSans
+DOT_FONTSIZE = 10
+CLASS_GRAPH = YES
+DOT_FONTPATH =
+COLLABORATION_GRAPH = YES
+GROUP_GRAPHS = YES
+UML_LOOK = NO
+TEMPLATE_RELATIONS = YES
+INCLUDE_GRAPH = YES
+INCLUDED_BY_GRAPH = YES
+CALL_GRAPH = NO
+CALLER_GRAPH = NO
+GRAPHICAL_HIERARCHY = YES
+DIRECTORY_GRAPH = YES
+DOT_IMAGE_FORMAT = png
+DOT_PATH =
+DOTFILE_DIRS =
+DOT_GRAPH_MAX_NODES = 44
+MAX_DOT_GRAPH_DEPTH = 0
+DOT_TRANSPARENT = YES
+DOT_MULTI_TARGETS = NO
+GENERATE_LEGEND = NO
+DOT_CLEANUP = YES
35 include/powerd-glib.h
@@ -0,0 +1,35 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+
+#ifndef _LIBPOWERD_GLIB_H_
+#define _LIBPOWERD_GLIB_H_
+
+#include <glib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void PowerdGmainAttach(GMainLoop *mainLoop);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // _LIBPOWERD_GLIB_H_
37 include/powerd-lunaservice.h
@@ -0,0 +1,37 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+
+#ifndef _POWERD_LUNASERVICE_H_
+#define _POWERD_LUNASERVICE_H_
+
+#include <lunaservice.h>
+#include <glib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void PowerdLSHandleAttach(LSHandle *sh);
+void PowerdClientInitLunaService(const char *clientName, LSHandle *sh);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // _POWERD_LUNASERVICE_H_
75 include/powerd.h
@@ -0,0 +1,75 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+
+#ifndef _LIBPOWERD_H_
+#define _LIBPOWERD_H_
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Interface to libpowerd.
+ * See doxygen pages for more information.
+ */
+
+typedef void (*PowerdCallback)(void);
+typedef void (*PowerdCallback_Int32)(int);
+typedef void (*PowerdCallback_Int32_4)(int, int, int, int);
+typedef void (*PowerdCallback_String_Int32)(const char *, int);
+
+void PowerdClientInit(const char *clientName);
+void PowerdClientDeinit(void);
+
+void PowerdDeferIdle(void);
+
+void PowerdForceSuspend(void);
+
+void PowerdSuspendRequestRegister(PowerdCallback callback);
+
+void PowerdSuspendRequestAck(bool allowSuspend);
+
+void PowerdPrepareSuspendRegister(PowerdCallback callback);
+
+void PowerdPrepareSuspendAck(bool finishedSuspend);
+
+void PowerdResumeRegister(PowerdCallback callback);
+
+void PowerdSuspendedRegister(PowerdCallback callback);
+
+void PowerdGetChargerStatusNotification(void);
+
+void PowerdChargerStatusRegister(PowerdCallback_String_Int32 callback);
+
+void PowerdGetBatteryStatusNotification(void);
+
+void PowerdBatteryStatusRegister(PowerdCallback_Int32_4 callback);
+
+int PowerdSetDisplayMode(bool on);
+int PowerdSetBacklightBrightness(int32_t percentBrightness);
+int PowerdSetKeylightBrightness(int32_t percentBrightness);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // _LIBPOWERD_H_
45 include/private/clock.h
@@ -0,0 +1,45 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+
+#ifndef _CLOCK_H_
+#define _CLOCK_H_
+
+#include <stdbool.h>
+#include <time.h>
+#include <glib.h>
+
+void ClockGetTime(struct timespec *time);
+
+bool ClockTimeIsGreater(struct timespec *a, struct timespec *b);
+
+void ClockStr(GString *str, struct timespec *time);
+
+void ClockPrintTime(struct timespec *time);
+void ClockPrint(void);
+
+void ClockDiff(struct timespec *diff, struct timespec *a, struct timespec *b);
+void ClockAccum(struct timespec *sum, struct timespec *b);
+
+void ClockAccumMs (struct timespec *sum, int duration_ms);
+
+long ClockGetMs(struct timespec *ts);
+
+void ClockClear(struct timespec *a);
+
+#endif // _CLOCK_H_
119 include/private/debug.h
@@ -0,0 +1,119 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+
+#ifndef _DEBUG_H_
+#define _DEBUG_H_
+
+
+#include <stdio.h>
+#include <assert.h>
+#include <glib.h>
+#include <string.h>
+#include <stdbool.h>
+
+/* define this to assert when BUG() macro is called */
+#define ASSERT_ON_BUG
+
+#undef G_LOG_DOMAIN
+#define G_LOG_DOMAIN "Powerd"
+
+// TODO use common error codes
+#define FATAL_ERROR -1
+#define ERROR 1
+#define POWERD_ERROR_TIMEOUT 355
+
+/* Set the current log level */
+void SetLogLevel(GLogLevelFlags newLogLevel);
+
+/* Set the destination of the log */
+void SetUseSyslog(int useSyslog);
+
+/* Return the current log level */
+GLogLevelFlags GetLogLevel();
+
+int DebugInit(void);
+
+void _good_assert(const char * cond_str, bool cond);
+
+#ifdef ASSERT_ON_BUG
+#define BUG() { \
+ *( (int*) NULL) = 0; \
+}
+#else
+#define BUG() {}
+#endif
+
+#define _assert(cond) \
+do { \
+ _good_assert(#cond, cond); \
+} while (0)
+
+#define g_critical_once(...) \
+do { \
+ static int seen = 0; \
+ if (!seen) \
+ { \
+ seen = 1; \
+ g_critical(__VA_ARGS__); \
+ } \
+} while(0)
+
+#define g_info(...) \
+ g_log (G_LOG_DOMAIN, \
+ G_LOG_LEVEL_INFO, \
+ __VA_ARGS__)
+
+#define g_perror(...) \
+do { \
+ char buf[512]; \
+ buf[0] = 0; \
+ g_critical(__VA_ARGS__); \
+ strerror_r(errno, buf, 512); \
+ g_error(buf); \
+} while(0)
+
+#define MESSAGE(...) \
+do { \
+ g_message(__VA_ARGS__); \
+} while (0)
+
+#define TRACE(...) \
+do { \
+ g_debug(__VA_ARGS__); \
+} while(0)
+
+#define TRACE_ERROR(...) \
+do { \
+ g_error(__VA_ARGS__); \
+} while(0)
+
+#define TRACE_PERROR g_perror
+
+#define iferr(cond, text, goto_label) \
+do { \
+ if (cond) \
+ { \
+ TRACE_ERROR(text); \
+ goto goto_label; \
+ } \
+} while (0);
+
+void print_trace(void);
+
+#endif //_DEBUG_H_
35 include/private/idler.h
@@ -0,0 +1,35 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+#include <stdbool.h>
+#include <time.h>
+
+void IdlerInit(void);
+void IdlerDeInit(void);
+
+void IdlerEvent(void);
+
+void IdlerForceIdle(void);
+
+/**
+ * @returns true if idled for 'sec' seconds.
+ * @returns false if forced idle.
+ */
+bool IdlerWaitFor(int sec);
+
+bool IdlerIsIdle(int sec, struct timespec *ret_remaining);
52 include/private/powerdltp.h
@@ -0,0 +1,52 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+
+#ifndef _POWERDLTP_H_
+#define _POWERDLTP_H_
+
+#ifdef USE_LTP
+#include <libtestutils.h>
+
+#define LTP_COND(testid, result, fmt...) \
+do { \
+ testPassIfTrue(testid, result, fmt); \
+} while (0)
+
+#define LTP_INFO(fmt...) \
+do { \
+ testInfoMessage(fmt); \
+} while (0)
+
+#else
+
+#define LTP_COND(testid, result, fmt...) \
+do { \
+ printf(fmt); \
+ printf("\n"); \
+} while (0)
+
+#define LTP_INFO(fmt...) \
+do { \
+ printf(fmt); \
+ printf("\n"); \
+} while(0)
+
+#endif // #ifdef USE_LTP
+
+#endif // _POWERDLTP_H_
53 include/private/wait.h
@@ -0,0 +1,53 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+#ifndef _WAITOBJ_H_
+#define _WAITOBJ_H_
+
+#define _GNU_SOURCE
+#include <pthread.h>
+#include <stdbool.h>
+
+typedef struct
+{
+ pthread_condattr_t condattr;
+ pthread_cond_t cond;
+ pthread_mutex_t mutex;
+
+ bool locked;
+} WaitObj;
+
+void WaitObjectInit(WaitObj *obj);
+
+void WaitObjectLock(WaitObj *obj);
+void WaitObjectUnlock(WaitObj *obj);
+
+int WaitObjectWait(WaitObj *obj, int ms);
+int WaitObjectWaitTimeSpec(WaitObj *obj, struct timespec *delta);
+int WaitObjectWaitAbsTime(WaitObj *obj, struct timespec *abstime);
+
+void WaitObjectSignal(WaitObj *obj);
+void WaitObjectSignalUnlocked(WaitObj *obj);
+
+
+void WaitObjectBroadcast(WaitObj *obj);
+void WaitObjectBroadcastUnlocked(WaitObj *obj);
+
+bool WaitObjectIsLocked(WaitObj *obj);
+
+#endif
43 libpowerd/CMakeLists.txt
@@ -0,0 +1,43 @@
+# @@@LICENSE
+#
+# Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+#
+# 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.
+#
+# LICENSE@@@
+
+#
+# powerd/libpowerd/CMakeLists.txt
+#
+
+# Build the libpowerd shared library
+
+include_directories(../include/private ../include .)
+
+add_definitions("-fPIC -DSTACK_GROWS_DOWN")
+
+# Can't use ${POWERD_LIBRARY_NAME} for target name since that's the name of the daemon.
+add_library(libpowerd SHARED clock.c commands.c init.c wait.c)
+target_link_libraries(libpowerd ${GLIB2_LDFLAGS} ${LUNASERVICE2_LDFLAGS} ${CJSON_LDFLAGS} pthread rt)
+
+
+set_target_properties(libpowerd PROPERTIES VERSION ${POWERD_LIBRARY_VERSION} SOVERSION ${POWERD_API_VERSION_MAJOR})
+set_target_properties(libpowerd PROPERTIES OUTPUT_NAME ${POWERD_LIBRARY_NAME})
+
+
+install(FILES ../include/powerd-glib.h ../include/powerd.h ../include/powerd-lunaservice.h DESTINATION "include/${POWERD_LIBRARY_NAME}")
+install(TARGETS libpowerd LIBRARY DESTINATION "lib${LIB_SUFFIX}/")
+
+configure_file(${POWERD_LIBRARY_NAME}.pc.in
+ ${PROJECT_BINARY_DIR}/libpowerd/${POWERD_LIBRARY_NAME}.pc @ONLY)
+install (FILES "${PROJECT_BINARY_DIR}/libpowerd/${POWERD_LIBRARY_NAME}.pc" DESTINATION "lib/pkgconfig")
163 libpowerd/clock.c
@@ -0,0 +1,163 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+
+/**
+ * @file clock.c
+ *
+ * @brief Clock Helper.
+ * Attempts to use monotonic clock as default clock source.
+ */
+
+#include "clock.h"
+
+#include <sys/time.h>
+#include <time.h>
+#include <stdio.h>
+#include <glib.h>
+
+#include "debug.h"
+
+#define NSEC_PER_SEC 1000000000L
+#define NSEC_PER_MSEC 1000000L
+
+#if (_POSIX_C_SOURCE - 0) >= 200112L
+ #define HAVE_PTHREAD_CONDATTR_SETCLOCK
+#else
+ //#error Powerd requires pthread extensions for using monotonic clock.
+ //#error warn Please use glibc >= 2.5
+#endif
+
+void
+ClockGetTime(struct timespec *time)
+{
+ int ret = 1;
+
+#ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
+ ret = clock_gettime(CLOCK_MONOTONIC, time);
+#endif
+ if (ret)
+ {
+ g_critical("Could not obtain monotonic clock.");
+
+ struct timeval tv;
+ gettimeofday(&tv, NULL);
+
+ time->tv_sec = tv.tv_sec;
+ time->tv_nsec = tv.tv_usec * 1000;
+ }
+}
+
+/**
+ * returns true if a > b
+ */
+bool
+ClockTimeIsGreater(struct timespec *a, struct timespec *b)
+{
+ return (a->tv_sec > b->tv_sec) ||
+ (a->tv_sec == b->tv_sec && a->tv_nsec > b->tv_nsec);
+}
+
+void
+ClockPrintTime(struct timespec *time)
+{
+ g_message("%lds.%ldms ", time->tv_sec, time->tv_nsec / NSEC_PER_MSEC);
+}
+
+void
+ClockStr(GString *str, struct timespec *time)
+{
+ g_string_append_printf(str, "%lds.%ldms ",
+ time->tv_sec, time->tv_nsec / NSEC_PER_MSEC);
+}
+
+/**
+ * Pretty print the current time.
+ */
+void
+ClockPrint(void)
+{
+ struct timespec time;
+ ClockGetTime(&time);
+
+ ClockPrintTime(&time);
+}
+
+
+/**
+ * diff = a - b
+ */
+void
+ClockDiff(struct timespec *diff, struct timespec *a, struct timespec *b)
+{
+ diff->tv_sec = a->tv_sec - b->tv_sec;
+ diff->tv_nsec = a->tv_nsec - b->tv_nsec;
+
+ if (diff->tv_nsec < 0)
+ {
+ diff->tv_nsec += NSEC_PER_SEC;
+ diff->tv_sec--;
+ }
+}
+
+/**
+ * sum += b
+ */
+void
+ClockAccum (struct timespec *sum, struct timespec *b)
+{
+ sum->tv_nsec += b->tv_nsec;
+ while (sum->tv_nsec >= NSEC_PER_SEC)
+ {
+ sum->tv_nsec -= NSEC_PER_SEC;
+ sum->tv_sec++;
+ }
+ sum->tv_sec += b->tv_sec;
+}
+
+void
+ClockAccumMs (struct timespec *sum, int duration_ms)
+{
+ int sec = duration_ms / 1000;
+ int nsec = (duration_ms - (sec * 1000)) * NSEC_PER_MSEC;
+
+ sum->tv_nsec += nsec;
+ while (sum->tv_nsec >= NSEC_PER_SEC)
+ {
+ sum->tv_nsec -= NSEC_PER_SEC;
+ sum->tv_sec++;
+ }
+ sum->tv_sec += sec;
+}
+
+long
+ClockGetMs(struct timespec *ts)
+{
+ if (!ts) return 0;
+ return ts->tv_sec * 1000 + ts->tv_nsec / NSEC_PER_MSEC;
+}
+
+/**
+ * a = 0
+ */
+void
+ClockClear(struct timespec *a)
+{
+ a->tv_sec = 0;
+ a->tv_nsec = 0;
+}
725 libpowerd/commands.c
@@ -0,0 +1,725 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+
+/**
+ * @file commands.c
+ *
+ * @brief This file contains APIs for registering new clients with powerd.
+ */
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <lunaservice.h>
+#include <pthread.h>
+#include <string.h>
+#include <assert.h>
+
+#include <cjson/json.h>
+
+#include "powerd.h"
+
+#include "init.h"
+
+#define POWERD_IPC_NAME "com.palm.power"
+#define POWERD_DEFAULT_CATEGORY "/com/palm/power/"
+
+typedef struct CallbackHelper
+{
+ void *callback;
+ LSMessageToken token;
+} CBH;
+
+#define CBH_INIT(helper) \
+CBH helper = {0, 0}
+
+GMainLoop *gMainLoop = NULL;
+bool gOwnMainLoop = false;
+bool gOwnLunaService = false;
+
+static LSHandle *gServiceHandle = NULL;
+
+/**
+* @brief Use your own LSHandle. This MUST be called before PowerdCLientInit()
+*
+* @param mainLoop
+*/
+void
+_LSHandleAttach(LSHandle *sh)
+{
+ if (sh)
+ {
+ gServiceHandle = sh;
+ gOwnLunaService = true;
+ }
+ else
+ {
+ gServiceHandle = NULL;
+ gOwnLunaService = false;
+ }
+}
+
+static void
+SignalCancel(CBH *helper)
+{
+ bool retVal;
+ LSError lserror;
+ LSErrorInit(&lserror);
+
+ retVal = LSCallCancel(gServiceHandle, helper->token, &lserror);
+ if (!retVal)
+ {
+ LSErrorPrint(&lserror, stderr);
+ LSErrorFree(&lserror);
+ }
+
+ helper->token = 0;
+}
+
+static void
+SignalRegister(const char *signalName, LSFilterFunc callback, CBH *helper)
+{
+ bool retVal;
+ LSError lserror;
+ LSErrorInit(&lserror);
+
+ char *payload = g_strdup_printf(
+ "{\"category\":\"/com/palm/power\",\"method\":\"%s\"}",
+ signalName);
+
+ retVal = LSCall(gServiceHandle,
+ "luna://com.palm.lunabus/signal/addmatch", payload,
+ callback, helper, &helper->token, &lserror);
+ if (!retVal)
+ {
+ LSErrorPrint(&lserror, stderr);
+ LSErrorFree(&lserror);
+ }
+
+ g_free(payload);
+}
+
+static void
+SendMessage(LSFilterFunc callback, const char *uri, const char *payload, ...)
+{
+ bool retVal;
+ char *buffer;
+
+ LSError lserror;
+ LSErrorInit(&lserror);
+
+ va_list args;
+ va_start(args, payload);
+ buffer = g_strdup_vprintf(payload, args);
+ va_end(args);
+
+ retVal = LSCall(gServiceHandle, uri, buffer,
+ callback, NULL, NULL, &lserror);
+ if (!retVal)
+ {
+ LSErrorPrint(&lserror, stderr);
+ LSErrorFree(&lserror);
+ }
+
+ g_free(buffer);
+}
+
+static void
+SendSignal(LSFilterFunc callback, const char *uri, const char *payload, ...)
+{
+ bool retVal;
+ char *buffer;
+
+ LSError lserror;
+ LSErrorInit(&lserror);
+
+ va_list args;
+ va_start(args, payload);
+ buffer = g_strdup_vprintf(payload, args);
+ va_end(args);
+
+ retVal = LSSignalSend(gServiceHandle, uri, buffer, &lserror);
+ if (!retVal)
+ {
+ LSErrorPrint(&lserror, stderr);
+ LSErrorFree(&lserror);
+ }
+
+ g_free(buffer);
+}
+
+
+
+/**
+* @brief Common callback used for incoming signals.
+*
+* @param sh
+* @param message
+* @param ctx
+*
+* @retval
+*/
+static bool
+ClientNoParamCallback(LSHandle *sh, LSMessage *message, void *ctx)
+{
+ CBH *helper = (CBH *)ctx;
+ if (!helper || !helper->callback) goto end;
+
+ if (strcmp(LSMessageGetCategory(message), "/com/palm/power") == 0)
+ {
+ ((PowerdCallback)helper->callback)();
+ }
+
+end:
+ return true;
+}
+
+/**
+* @brief User API to register a callback for 'suspendRequest'
+* notification. Client should respond with PowerdSuspendRequestAck().
+*
+* @param callback_function
+*/
+void
+PowerdSuspendRequestRegister(PowerdCallback callback_function)
+{
+ static CBH_INIT(helper);
+ PowerdHandle *handle = PowerdGetHandle();
+
+ helper.callback = (void*)callback_function;
+
+ if (helper.token)
+ {
+ SignalCancel(&helper);
+ }
+
+ if (callback_function)
+ {
+ SignalRegister("suspendRequest", ClientNoParamCallback, &helper);
+
+ handle->suspendRequestRegistered = true;
+ }
+ else
+ {
+ handle->suspendRequestRegistered = false;
+ }
+
+ PowerdClientLock(handle);
+
+ char *message = g_strdup_printf(
+ "{\"register\":%s,\"clientId\":\"%s\"}",
+ handle->suspendRequestRegistered ? "true" : "false",
+ handle->clientId ?: "(null)");
+
+ PowerdClientUnlock(handle);
+
+ SendMessage(NULL, "luna://" POWERD_IPC_NAME POWERD_DEFAULT_CATEGORY
+ "suspendRequestRegister", message);
+
+ g_free(message);
+}
+
+/**
+* @brief User API to register a callback for 'prepareSuspend'
+* notification.
+*
+* @param callback_function
+*/
+void
+PowerdPrepareSuspendRegister(PowerdCallback callback_function)
+{
+ static CBH_INIT(helper);
+ PowerdHandle *handle = PowerdGetHandle();
+
+ helper.callback = (void*)callback_function;
+
+ if (helper.token)
+ {
+ SignalCancel(&helper);
+ }
+
+ if (callback_function)
+ {
+ SignalRegister("prepareSuspend", ClientNoParamCallback, &helper);
+
+ handle->prepareSuspendRegistered = true;
+ }
+ else
+ {
+ handle->prepareSuspendRegistered = false;
+ }
+
+ PowerdClientLock(handle);
+
+ char *message = g_strdup_printf(
+ "{\"register\":%s,\"clientId\":\"%s\"}",
+ handle->prepareSuspendRegistered ? "true" : "false",
+ handle->clientId ?: "(null)");
+
+ PowerdClientUnlock(handle);
+
+ SendMessage(NULL, "luna://" POWERD_IPC_NAME POWERD_DEFAULT_CATEGORY
+ "prepareSuspendRegister", message);
+
+ g_free(message);
+}
+
+/**
+* @brief Register a callback for resume notification when
+* system wakes from sleep.
+*
+* @param callback_function
+*/
+void
+PowerdResumeRegister(PowerdCallback callback_function)
+{
+ static CBH_INIT(helper);
+
+ helper.callback = (void*)callback_function;
+
+ if (helper.token)
+ {
+ SignalCancel(&helper);
+ }
+
+ SignalRegister("resume", ClientNoParamCallback, &helper);
+}
+
+/**
+* @brief Register a callback for suspended notification when
+* the device goes to sleep. There is no guarantee you will
+* receive this message before the system has gone alseep.
+*
+* If you want a message before the system has gone alseep,
+* see PowerdSuspendRequestRegister() or late state
+* PowerdPrepareSuspendRegister().
+*
+* @param callback_function
+*/
+void
+PowerdSuspendedRegister(PowerdCallback callback_function)
+{
+ static CBH_INIT(helper);
+
+ helper.callback = (void*)callback_function;
+
+ if (helper.token)
+ {
+ SignalCancel(&helper);
+ }
+
+ SignalRegister("suspended", ClientNoParamCallback, &helper);
+}
+
+/**
+* @brief Permit or deny suspend execution. This should be called in response
+* to a 'suspendRequest' notification.
+*
+* @param allowSuspend
+* - if true, allows system to prepare to suspend
+* - if false, system stays awake
+*/
+void
+PowerdSuspendRequestAck(bool allowSuspend)
+{
+ char *message;
+
+ PowerdHandle *handle = PowerdGetHandle();
+
+ PowerdClientLock(handle);
+
+ message = g_strdup_printf("{\"ack\":%s,\"clientId\":\"%s\"}",
+ allowSuspend ? "true" : "false",
+ handle->clientId ?: "(null)");
+
+ PowerdClientUnlock(handle);
+
+ SendMessage(NULL, "luna://" POWERD_IPC_NAME POWERD_DEFAULT_CATEGORY
+ "suspendRequestAck", message);
+
+ g_free(message);
+}
+
+/**
+* @brief Late stage permit or deny suspend. This should be called
+* in response to a 'prepareSuspend' notification.
+*
+* @param finishedSuspend
+* - if true, client is ready for suspend
+* - if false, client is not ready for suspend,
+* suspend aborted, and Resume is sent.
+* See PowerdResumeRegister.
+*/
+void
+PowerdPrepareSuspendAck(bool finishedSuspend)
+{
+ char *message;
+
+ PowerdHandle *handle = PowerdGetHandle();
+
+ PowerdClientLock(handle);
+
+ message = g_strdup_printf("{\"ack\":%s,\"clientId\":\"%s\"}",
+ finishedSuspend ? "true" : "false",
+ handle->clientId ?: "(null)");
+
+ PowerdClientUnlock(handle);
+
+ SendMessage(NULL, "luna://" POWERD_IPC_NAME POWERD_DEFAULT_CATEGORY
+ "prepareSuspendAck", message);
+
+ g_free(message);
+}
+
+/**
+* @brief Turn on the backlight.
+*
+* @param on
+*
+* @retval
+*/
+int
+PowerdSetDisplayMode(bool on)
+{
+ const char *message = on ?
+ "{\"state\":\"on\"}" :
+ "{\"state\":\"off\"}";
+
+ SendMessage(NULL, "luna://" POWERD_IPC_NAME "/backlight", message);
+ return 0;
+}
+
+/**
+* @brief Set the brightness of the backlight. Currently not implemented.
+*
+* @param percentBrightness
+*
+* @retval
+*/
+int
+PowerdSetBacklightBrightness(int32_t percentBrightness)
+{
+ g_warning("%s is not implemented", __FUNCTION__);
+ return 0;
+}
+
+/**
+* @brief Set the brightness of the keylight. Currently not implemented.
+*
+* @param percentBrightness
+*
+* @retval
+*/
+int
+PowerdSetKeylightBrightness(int32_t percentBrightness)
+{
+ g_warning("%s is not implemented", __FUNCTION__);
+ return 0;
+}
+
+/**
+* @brief Forces suspend. Called from test code.
+*/
+void
+PowerdForceSuspend(void)
+{
+ SendMessage(NULL, "luna://" POWERD_IPC_NAME POWERD_DEFAULT_CATEGORY
+ "forceSuspend", "{}");
+}
+
+/**
+* @brief Request a battery status notification.
+*/
+void
+PowerdGetBatteryStatusNotification(void)
+{
+ SendSignal(NULL, "luna://" POWERD_IPC_NAME POWERD_DEFAULT_CATEGORY
+ "batteryStatusQuery", "{}");
+}
+
+/**
+* @brief Helper that translates from jsonized message into form for use
+* with callback.
+*
+* @param sh
+* @param message
+* @param ctx
+*
+* @retval
+*/
+static bool
+_ClientBatteryStatusCallback(LSHandle *sh, LSMessage *message, void *ctx)
+{
+ CBH *helper = (CBH *)ctx;
+ if (!helper || !helper->callback) return true;
+
+ const char *payload = LSMessageGetPayload(message);
+ struct json_object *object = json_tokener_parse(payload);
+ if (is_error(object)) {
+ goto end;
+ }
+
+ int percent;
+ int temp_C;
+ int current_mA;
+ int voltage_mV;
+
+ percent = json_object_get_int(
+ json_object_object_get(object, "percent"));
+
+ temp_C = json_object_get_int(
+ json_object_object_get(object, "temperature_C"));
+
+ current_mA = json_object_get_int(
+ json_object_object_get(object, "current_mA"));
+
+ voltage_mV = json_object_get_int(
+ json_object_object_get(object, "voltage_mV"));
+
+ ((PowerdCallback_Int32_4)helper->callback)
+ (percent, temp_C, current_mA, voltage_mV);
+
+end:
+ if (!is_error(object)) json_object_put(object);
+ return true;
+}
+
+/**
+* @brief Register a callback for battery status notifications.
+*
+* @param callback_function
+* Callback is called with the following parameters:
+* callback(percent, temperature, current, voltage);
+*/
+void
+PowerdBatteryStatusRegister(PowerdCallback_Int32_4 callback_function)
+{
+ static CBH_INIT(helper);
+
+ if (helper.token)
+ {
+ SignalCancel(&helper);
+ }
+
+ helper.callback = (void*)callback_function;
+
+ SignalRegister("batteryStatus", _ClientBatteryStatusCallback, &helper);
+}
+
+/**
+* @brief Unimplemented.
+*
+* @param callback_function
+*/
+void
+PowerdGetChargerStatusNotification(void)
+{
+ g_warning("%s: This function is not implemented", __FUNCTION__);
+}
+
+/**
+* @brief Unimplemented.
+* @param callback - Function to be called when charger state changes.
+*
+* @param callback_function
+* Callback is called with the following parameters:
+* callback(source, current_mA).
+*/
+void
+PowerdChargerStatusRegister(PowerdCallback_String_Int32 callback_function)
+{
+ g_warning("%s: This function is not implemented", __FUNCTION__);
+}
+
+static void *
+_PowerdIPCThread(void *ctx)
+{
+ g_main_loop_run(gMainLoop);
+ return NULL;
+}
+
+static bool
+_identify_callback(LSHandle *sh, LSMessage *msg, void *ctx)
+{
+ struct json_object * object =
+ json_tokener_parse(LSMessageGetPayload(msg));
+ if (is_error(object)) goto error;
+
+ bool subscribed = json_object_get_boolean(
+ json_object_object_get(object, "subscribed"));
+ const char *clientId = json_object_get_string(
+ json_object_object_get(object, "clientId"));
+
+ if (!subscribed || !clientId)
+ {
+ g_critical("%s: Could not subscribe to powerd %s.", __FUNCTION__,
+ LSMessageGetPayload(msg));
+ goto end;
+ }
+
+ PowerdHandle *handle = PowerdGetHandle();
+ PowerdSetClientId(handle, clientId);
+
+ char *message = g_strdup_printf(
+ "{\"register\":true,\"clientId\":\"%s\"}", clientId);
+
+ if (handle->suspendRequestRegistered)
+ {
+ SendMessage(NULL, "luna://" POWERD_IPC_NAME POWERD_DEFAULT_CATEGORY
+ "suspendRequestRegister", message);
+ }
+
+ if (handle->prepareSuspendRegistered)
+ {
+ SendMessage(NULL, "luna://" POWERD_IPC_NAME POWERD_DEFAULT_CATEGORY
+ "prepareSuspendRegister", message);
+ }
+
+ g_free(message);
+
+error:
+end:
+ if (!is_error(object)) json_object_put(object);
+ return true;
+}
+
+/**
+* @brief Called to re-register with powerd if powerd crashes.
+*
+* @param sh
+* @param msg
+* @param ctx
+*
+* @retval
+*/
+static bool
+_powerd_server_up(LSHandle *sh, LSMessage *msg, void *ctx)
+{
+ bool connected;
+
+ struct json_object *object = json_tokener_parse(LSMessageGetPayload(msg));
+ if (is_error(object)) goto error;
+
+ connected = json_object_get_boolean(
+ json_object_object_get(object, "connected"));
+
+ if (connected)
+ {
+ g_debug("%s connected was true (powerd is already running)", __FUNCTION__);
+ PowerdHandle *handle = PowerdGetHandle();
+
+ /* Send our name to powerd. */
+ SendMessage(_identify_callback,
+ "luna://com.palm.power/com/palm/power/identify",
+ "{\"subscribe\":true,\"clientName\":\"%s\"}",
+ handle->clientName);
+ }
+
+end:
+ if (!is_error(object)) json_object_put(object);
+ return true;
+
+error:
+ g_critical("%s: Error registering with com.palm.power", __FUNCTION__);
+ goto end;
+}
+
+void
+_PowerdClientIPCRun(void)
+{
+ bool retVal;
+ LSError lserror;
+ LSErrorInit(&lserror);
+
+ if (!gServiceHandle)
+ {
+ retVal = LSRegister(NULL, &gServiceHandle, &lserror);
+ if (!retVal) goto error;
+
+ if (!gMainLoop)
+ {
+ int ret;
+
+ GMainContext *context = g_main_context_new();
+ if (!context) goto error;
+
+ gMainLoop = g_main_loop_new(context, FALSE);
+ g_main_context_unref(context);
+ if (!gMainLoop) goto error;
+
+ pthread_attr_t attr;
+ pthread_attr_init(&attr);
+
+ ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
+ assert(ret == 0);
+
+ pthread_t tid;
+ pthread_create(&tid, &attr, _PowerdIPCThread, NULL);
+ }
+
+ retVal = LSGmainAttach(gServiceHandle, gMainLoop, &lserror);
+ if (!retVal) goto error;
+ }
+
+ retVal = LSCall(gServiceHandle,
+ "luna://com.palm.lunabus/signal/registerServerStatus",
+ "{\"serviceName\":\"com.palm.power\"}", _powerd_server_up,
+ NULL, NULL, &lserror);
+ if (!retVal) goto error;
+
+ return;
+error:
+ LSErrorPrint(&lserror, stderr);
+ LSErrorFree(&lserror);
+ return;
+}
+
+
+/**
+* @brief Cleanup all IPC.
+*/
+void
+_PowerdClientIPCStop(void)
+{
+ if (gMainLoop)
+ {
+ if (!gOwnMainLoop)
+ g_main_loop_quit(gMainLoop);
+
+ g_main_loop_unref(gMainLoop);
+
+ gMainLoop = NULL;
+ gOwnMainLoop = false;
+ }
+
+ if (gServiceHandle && !gOwnLunaService)
+ {
+ bool retVal;
+ LSError lserror;
+ LSErrorInit(&lserror);
+
+ retVal = LSUnregister(gServiceHandle, &lserror);
+ if (!retVal)
+ {
+ LSErrorPrint(&lserror, stderr);
+ LSErrorFree(&lserror);
+ }
+ }
+ gServiceHandle = NULL;
+ gOwnLunaService = false;
+}
152 libpowerd/init.c
@@ -0,0 +1,152 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+#include <assert.h>
+
+#include <stdbool.h>
+#include <stdlib.h>
+#include <pthread.h>
+
+#include <lunaservice.h>
+
+#include "init.h"
+#include "debug.h"
+
+void _PowerdClientIPCRun(void);
+void _PowerdClientIPCStop(void);
+
+void _LSHandleAttach(LSHandle *sh);
+
+extern GMainLoop *gMainLoop;
+extern bool gOwnMainLoop;
+
+static PowerdHandle sHandle =
+{
+ .clientName = "",
+ .clientId = NULL,
+ .suspendRequestRegistered = false,
+ .prepareSuspendRegistered = false,
+ .lock = PTHREAD_MUTEX_INITIALIZER,
+};
+
+static void
+PowerdHandleInit(PowerdHandle *handle)
+{
+ if (handle->clientId)
+ g_free(handle->clientId);
+
+ handle->clientName = "";
+ handle->clientId = NULL;
+ handle->suspendRequestRegistered = false;
+ handle->prepareSuspendRegistered = false;
+}
+
+PowerdHandle*
+PowerdGetHandle(void)
+{
+ return &sHandle;
+}
+
+/**
+* @brief Register as a power-aware client with name 'clientName'.
+*
+* @param clientName
+*/
+void
+PowerdClientInit(const char *clientName)
+{
+ PowerdHandleInit(&sHandle);
+
+ sHandle.clientName = clientName;
+
+ _PowerdClientIPCRun();
+}
+
+/**
+* @brief Register as a power-aware client using the existing
+* LunaService handle.
+*
+* @param clientName
+* @param sh
+*/
+void
+PowerdClientInitLunaService(const char *clientName, LSHandle *sh)
+{
+ _LSHandleAttach(sh);
+ PowerdClientInit(clientName);
+}
+
+/**
+* @brief Use this mainloop instead of creating a powerd IPC
+* thread automatically. This MUST be called before PowerdClientInit()
+* if you wish to use your own mainloop.
+*
+* @param mainLoop
+*/
+void
+PowerdGmainAttach(GMainLoop *mainLoop)
+{
+ if (mainLoop)
+ {
+ gMainLoop = g_main_loop_ref(mainLoop);
+ gOwnMainLoop = true;
+ }
+ else
+ {
+ gMainLoop = NULL;
+ gOwnMainLoop = false;
+ }
+}
+
+void
+PowerdClientLock(PowerdHandle *handle)
+{
+ int ret = pthread_mutex_lock(&sHandle.lock);
+ assert(ret == 0);
+}
+
+void
+PowerdClientUnlock(PowerdHandle *handle)
+{
+ int ret = pthread_mutex_unlock(&sHandle.lock);
+ assert(ret == 0);
+}
+
+void
+PowerdSetClientId(PowerdHandle *handle, const char *clientId)
+{
+ PowerdClientLock(handle);
+
+ if (handle->clientId) g_free(handle->clientId);
+ handle->clientId = g_strdup(clientId);
+
+ PowerdClientUnlock(handle);
+}
+
+/**
+* @brief Stop being a powerd client.
+* Implicit in this is we disconnect from any communications
+* from powerd.
+*/
+void
+PowerdClientDeinit(void)
+{
+ PowerdHandleInit(&sHandle);
+ _PowerdClientIPCStop();
+
+}
38 libpowerd/init.h
@@ -0,0 +1,38 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+#ifndef _POWERD_INIT_H_
+#define _POWERD_INIT_H_
+
+typedef struct
+{
+ const char *clientName;
+ char *clientId;
+ bool suspendRequestRegistered;
+ bool prepareSuspendRegistered;
+ pthread_mutex_t lock;
+} PowerdHandle;
+
+PowerdHandle* PowerdGetHandle(void);
+
+void PowerdSetClientId(PowerdHandle *handle, const char *clientId);
+
+void PowerdClientLock(PowerdHandle *handle);
+void PowerdClientUnlock(PowerdHandle *handle);
+
+#endif // _POWERD_INIT_H_
28 libpowerd/powerd.pc.in
@@ -0,0 +1,28 @@
+# @@@LICENSE
+#
+# Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+#
+# 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.
+#
+# LICENSE@@@
+
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${exec_prefix}/lib
+includedir=${prefix}/include/@POWERD_LIBRARY_NAME@
+
+Name: @POWERD_LIBRARY_NAME@
+Description: Powerd Library
+Version: @POWERD_LIBRARY_VERSION@
+Libs: -L${libdir} -l@POWERD_LIBRARY_NAME@
+Cflags: -I${includedir}
217 libpowerd/wait.c
@@ -0,0 +1,217 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+
+/**
+ * @file init.c
+ *
+ * @brief Utility for doing timed waits with a monotonic clock.
+ */
+
+#include <assert.h>
+
+#include <sys/time.h>
+#include <time.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <glib.h>
+
+#include "wait.h"
+#include "clock.h"
+#include "debug.h"
+
+#if !defined(_GNU_SOURCE)
+#endif
+
+#if (_POSIX_C_SOURCE - 0) >= 200112L
+ #define HAVE_PTHREAD_CONDATTR_SETCLOCK
+#else
+ //#error Powerd requires pthread extensions for using monotonic clock.
+ //#error warn Please use glibc >= 2.7
+#endif
+
+void
+WaitObjectInit(WaitObj *obj)
+{
+ assert(obj != NULL);
+
+ pthread_mutex_init(&obj->mutex, NULL);
+
+ pthread_condattr_init(&obj->condattr);
+
+#ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
+ pthread_condattr_setclock(&obj->condattr, CLOCK_MONOTONIC);
+#endif
+
+ pthread_cond_init(&obj->cond, &obj->condattr);
+}
+
+void
+WaitObjectLock(WaitObj *obj)
+{
+ pthread_mutex_lock(&obj->mutex);
+}
+
+void
+WaitObjectUnlock(WaitObj *obj)
+{
+ pthread_mutex_unlock(&obj->mutex);
+}
+
+/**
+ * Wait up to ms milliseconds on WaitObj's condition variable.
+ *
+ * This function requires that wait object be locked.
+ *
+ * @returns 0 if woken by cond signal
+ * @returns 1 if timed-out
+ *
+ * Warning the resolution level is that of system jiffies.
+ */
+int
+WaitObjectWait(WaitObj *obj, int ms)
+{
+ struct timespec time;
+
+ if (ms < 0)
+ {
+ time.tv_sec = -1;
+ time.tv_nsec = 0;
+ }
+ else
+ {
+ time.tv_sec = ms/1000;
+ time.tv_nsec = (ms % 1000) * 1000000000;
+ }
+
+ return WaitObjectWaitTimeSpec(obj, &time);
+}
+
+int
+WaitObjectWaitTimeSpec(WaitObj *obj, struct timespec *delta)
+{
+ int ret = 1;
+ struct timespec time;
+
+ // wait object must be locked before use.
+ g_assert(WaitObjectIsLocked(obj));
+ g_assert(delta != NULL);
+
+ if (-1 == delta->tv_sec) // wait forever
+ {
+ ret = pthread_cond_wait(&obj->cond, &obj->mutex);
+ return (ret != 0);
+ }
+
+#ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
+ ret = clock_gettime(CLOCK_MONOTONIC, &time);
+#endif
+ if (ret)
+ {
+ TRACE("%s: Error getting monotonic clock, "
+ "using realtime clock instead.\n", __FUNCTION__);
+
+ struct timeval tv;
+ gettimeofday(&tv, NULL);
+
+ time.tv_sec = tv.tv_sec;
+ time.tv_nsec = tv.tv_usec * 1000;
+ }
+
+ // time += delta
+ ClockAccum(&time, delta);
+
+ return WaitObjectWaitAbsTime(obj, &time);
+}
+
+int
+WaitObjectWaitAbsTime(WaitObj *obj, struct timespec *abstime)
+{
+ // wait object must be locked before use.
+ g_assert(WaitObjectIsLocked(obj));
+ g_assert(abstime != NULL);
+
+ int ret = pthread_cond_timedwait(&obj->cond, &obj->mutex, abstime);
+
+ if (ETIMEDOUT == ret)
+ {
+ // we timed-out
+ return 1;
+ }
+ else if (0 == ret)
+ {
+ // we were awoken
+ return 0;
+ }
+ else
+ {
+ // Ubuntu 9.04 toolchain didn't like TRACE_PERROR
+ g_error("%s pthread_cond_timedwait failed (ret = %d).\n", __FUNCTION__, ret);
+
+ return -1;
+ }
+}
+
+void
+WaitObjectSignal(WaitObj *obj)
+{
+ WaitObjectLock(obj);
+
+ pthread_cond_signal(&obj->cond);
+
+ WaitObjectUnlock(obj);
+}
+
+void
+WaitObjectSignalUnlocked(WaitObj *obj)
+{
+ pthread_cond_signal(&obj->cond);
+}
+
+void
+WaitObjectBroadcast(WaitObj *obj)
+{
+ WaitObjectLock(obj);
+
+ pthread_cond_broadcast(&obj->cond);
+
+ WaitObjectUnlock(obj);
+}
+
+void
+WaitObjectBroadcastUnlocked(WaitObj *obj)
+{
+ pthread_cond_broadcast(&obj->cond);
+}
+
+bool
+WaitObjectIsLocked(WaitObj *obj)
+{
+ int ret;
+
+ ret = pthread_mutex_trylock(&obj->mutex);
+ if (ret == EBUSY)
+ {
+ return true;
+ }
+ else
+ {
+ pthread_mutex_unlock(&obj->mutex);
+ return false;
+ }
+}
44 powerd/CMakeLists.txt
@@ -0,0 +1,44 @@
+# @@@LICENSE
+#
+# Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+#
+# 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.
+#
+# LICENSE@@@
+
+#
+# powerd/powerd/CMakeLists.txt
+#
+
+# Build the powerd executable
+
+include_directories(../include/private ../include . ./utils ./alarms ./suspend)
+
+# Check that we have nyx-lib
+pkg_check_modules(NYXLIB REQUIRED nyx)
+add_definitions(${NYXLIB_CFLAGS})
+
+aux_source_directory(alarms alarms_files)
+aux_source_directory(charging charging_files)
+aux_source_directory(suspend suspend_files)
+aux_source_directory(utils utils_files)
+
+add_executable(powerd ${alarms_files} ${charging_files} ${suspend_files} ${utils_files} main.c config.c com_palm_power_lunabus.c timesaver.c)
+target_link_libraries(powerd ${GLIB2_LDFLAGS} ${LUNASERVICE2_LDFLAGS} ${CJSON_LDFLAGS} ${NYXLIB_LDFLAGS})
+
+set_property(TARGET powerd PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE)
+
+
+install(TARGETS powerd DESTINATION "sbin")
+install(FILES ./preferences/powerd.conf DESTINATION "${SYSCONFDIR_FULL}/default")
+install(PROGRAMS ./etc/event.d/powerd DESTINATION "${SYSCONFDIR_FULL}/event.d")
385 powerd/alarms/timeout_alarm.c
@@ -0,0 +1,385 @@
+/* @@@LICENSE
+*
+* Copyright (c) 2007-2012 Hewlett-Packard Development Company, L.P.
+*
+* 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.
+*
+* LICENSE@@@ */
+
+
+
+/**
+ * @file timeout_alarm.c
+ *
+ * For eg: If a caller calls luna://com.palm.power/timeout/set {...}, the call will reach the powerd
+ * alarms interface , which will take the whole message ,and send it over to
+ * luna://com.palm.sleep/timeout/set {...}. Similarly com.palm.power/timeout/set sends the response
+ * from com.palm.sleep/timeout/set back to the original caller.
+ *
+ */
+
+#include <lunaservice.h>
+#include <glib.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+#include <cjson/json.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "main.h"
+
+#include "logging.h"
+#include "timesaver.h"
+
+#include "lunaservice_utils.h"
+
+#include "utils/init.h"
+#include "utils/uevent.h"
+#include "utils/timersource.h"
+
+#include "powerd.h"
+
+#include "timeout_alarm.h"
+
+#define LOG_DOMAIN "POWERD-TIMEOUT: "
+
+static LSPalmService *psh = NULL;
+
+/**
+ * @defgroup SleepdCalls Calls redirected to Sleepd component
+ * @ingroup Powerd
+ */
+
+
+/**
+ * @defgroup Alarms Alarms
+ * @ingroup SleepdCalls
+ * @brief Alarms for RTC wakeup.
+ */
+
+/**
+ * @addtogroup Alarms
+ * @{
+ */
+
+
+/**
+ * @brief Callback function called whenever there is a response from sleepd method call for any of the alarms
+ * interface calls like alarmAdd, timeout/set.
+ *
+ * @retval
+ */
+static bool
+alarms_timeout_cb(LSHandle *sh, LSMessage *message, void *ctx)
+{
+ bool retVal;
+ LSMessage *replyMessage = (LSMessage *)ctx;
+
+ POWERDLOG(LOG_INFO,"%s: response with payload %s", __FUNCTION__, LSMessageGetPayload(message));
+ if(replyMessage && LSMessageGetConnection(replyMessage))
+ {
+ retVal = LSMessageReply(LSMessageGetConnection(replyMessage), replyMessage, LSMessageGetPayload(message), NULL);
+ if (!retVal)
+ {
+ POWERDLOG(LOG_WARNING, "%s could not send reply.", __FUNCTION__);
+ }
+ LSMessageUnref(replyMessage);