\chapter{Android Implementation}
Because Java programming language is platform independent, we have chosen to develop an application for Android operating system. It is Linux based open-source system developed by Google company. The system is run on Samsung Galaxy Tab machine, which embeds Samsung~S5PC~110 1~GHz processor, 512~Mb RAM, 16~Gb hard-drive and offers also tactile 7~inch screen, wi-fi, gps and 3G connection.

In the current development state, the application uses Google Maps V3 API and enables to get driving directions while optimizing energy consumption of the journey. Once the processing is finished, user obtains driving directions provided by Google and final battery state of charge prediction. The power profile is calculated from distance, duration and altitude samples within the cycle. After obtaining this information from Google, we can locally optimize the energy in order to obtain the optimal power-split-ratio between batteries and super-capacitors for the whole cycle. For now, Google Maps data are used, however there are more payed or free map data available on the market like Navteq~\cite{navteq} or CloudMade~\cite{cloudmade}. The graphic user interface screen after energy optimization is shown in figure~\ref{fig:gui}.

\begin{figure}[ht]
    \center
    \includegraphics[width=15cm]{images/android/gui_galaxy.png}
    \caption{Application user graphic interface displaying route, battery and super-capacitors actual and final states-of-charge embedded in Samsung Galaxy Tab device.}
    \label{fig:gui}
\end{figure}

%\begin{figure}[ht]
%    \center
%    \includegraphics[width=15cm]{images/android/map3d.png}
%    \caption{3D visualization of a planned route.}
%    \label{fig:map3d}
%\end{figure}

\section{Application Structure and Description}
In Android operating system, the application can be composed from more other dependent or not sub-applications. These sub-applications are called activities. In figure~\ref{fig:android_uml} is shown the main structure of our application. It is composed from four activities which pass data between them.

\begin{figure}[ht]
    \center
    \includegraphics[width=10cm]{images/android/android_uml.png}
    \caption{Android application structure and parameters passing.}
    \label{fig:android_uml}
\end{figure}

The first activity is GMapView.java which is responsible only to show the Google maps and to get user current location. You can also switch map type to hybrid. In next version, location search function should be added.

As you can see from diagram~\ref{fig:android_uml}, the GMapView passes actual device location to Directions.java activity. This activity is only intermediate and asks user to fill in the route's start and destination locations. It is possible, that one of the locations is ``My Location'' of the device. Once the information is filled in, it is passed to the CycleView.java activity.

CycleView activity sends HTTP request to Google server, to obtain directions and altitude samples of the route. After obtaining response data, the activity renders the route into the map, calculates the power profile for the electric vehicle and finally optimizes the power-split-ratio between battery and super-capacitors during the journey. That is how also the final battery state of charge is predicted and displayed. A screen-shot of this activity is shown in figure~\ref{fig:gui}.

The last activity is PlotsView.java which is supposed to show some basic plots concerning the route and the power profile. These plots are only for analysis purposes and won't be accessible for the final user. It is possible to display altitude, distance, duration, velocity, power profile, battery and SC power, battery and SC SoC and PSR plots.

\subsection{WebView and JavaScript}
There are more ways how to show a map in an Android application. Google Maps API is available for Android Java developers. However, this API enables only some basic map features like map display and control, map tiles precaching and map overlays. This means, that the public part of this API does not include navigations services.

That is why, we had to embed our application in a web page and use Google Maps JavaScript V3 API which offers Directions, Elevations and Geocoding services.

An Android activity can display easily a web page using a WebView component which is basically a Webkit core browser embedded in your application. To communicate between Android activity and the web page, it is possible to bind Java methods to JavaScript functions so you can execute Android methods directly from the web page or vice-versa you can call JavaScript functions from you Android activity.

For that purpose, a web page gmapview.html was developed in order to display and control map and request directions, geocoding and elevations information from google services.


\subsection{Flot Graph Library}
To render the graphs in PlotsView activity, the Flot Graph library is used~\cite{flot}. Flot is a pure JavaScript plotting library for jQuery. It produces graphical plots of arbitrary datasets on-the-fly client-side. It is a free redistributable open-source software under MIT license.

Hence it is a JavaScript library, the graphs are embedded in a web page. In the Android activity, we use WebView to show the graphs and Java to JavaScript binding to pass plotting data in JSON format.

In figures~\ref{fig:distance}, \ref{fig:duration} and \ref{fig:altitude} are shown plots generated by Flot library.


\subsection{Localization}
Localization can be difficult and complex task, because the location reading can contain errors or can be inaccurate. That is why, the location determination should be a data fusion of more location sources. On Android system, there are principally three sources - GPS, Cell-ID and Wi-fi (network provider). Than it is a compromise between accuracy, speed and device battery-efficiency to make the best location estimation.

In our application, only network provider and GPS sources are used. In preference, the GPS position is used. When the GPS module is unavailable it is replaced by the network provider location. In the future, more sophisticated location estimation method should be implemented. The whole localization process is described in~\cite{android}.


\subsection{CycleView Activity}
CycleView activity represents the most important part of the whole application. It sends google HTTP requests and gets information about the driving cycle. Once the google server response is received, this activity renders the route and calculates the driving cycle power profile of the electric vehicle and optimizes the power-split-ratio between the battery and the super-capacitors.

In figure~\ref{fig:cycle_view__coll__graph} is shown brief CycleView activity call graph. This class inherits from Activity class and implements LocationListener interface. When the activity is created, it saves the passed parameters from Directions activity, which are current latitude and longitude and start and destination locations names defined by user. Also, the progress dialog is shown at the beginning of the calculation process (you can see the ProgressDialog class in the call graph). After, a LocationManager class is used to get information about current location, in the case the device position changes, and it is save in mostRecentLocation instance of Location class (c.f. the call graph).

Now, we have all the necessary information to request the server. Fist, we have to load our map displaying and directions resolving web page into WebView and pass the start and destination locations to our JavaScript function.

\lstset{language=Java, caption=Calling WebView JavaScript directions function from Android activity., label=lst:WebView}
\begin{lstlisting}
	// Define command string
	String urlRoute = "javascript:calcRoute(1,{'origin':'Paris', 'destination':'Lognes', 'waypoints': null})";
	// Associate webView instance with our initialized WebView
	WebView webView = (WebView) findViewById(R.id.cycle_webview);
	// Call the JavaScript function
	webView.loadUrl(urlRoute);
\end{lstlisting}

A code sample is in ~\ref{lst:WebView}. It shows the way how to compose the command string for the web page. First, we use the keyword javascript and after colon, we add the function name with parameters. Here, the first parameter, it the id of overloaded function, and the second parameter is a JavaScript object in JSON string format which describes origin location, destination location and the waypoints between them (they are undefined in this example).

This function requests Google server for the driving directions. Once the server returns the directions response object, we save distance and duration information about every leg of the driving cycle to our Android application and also, we use the route's path returned by the server to request the elevations within this path. Google server responses with the altitude samples within our driving path and than, we can save it into the Android application.

After having all these data, we can calculate power profile from average driving velocities and sampled altitudes and optimize the power-split-ratio for all the driving cycle.

The InputStream class in the call graph represents a stream with xml vehicle configuration file which is passed to the optimization method.

\begin{figure}[ht]
    \center
    \includegraphics[width=16cm]{images/android/cycle_view__coll__graph.png}
    \caption{CycleView activity call graph.}
    \label{fig:cycle_view__coll__graph}
\end{figure}

\section{Resources}
Our Android application uses some local resources. These are particularly web pages for map processing and data plotting and their respective JavaScript files and also the XML configuration file config.xml. The goal of the local resources is, that the final user cannot access them, modify them and corrupt the application. Also, every necessary file is local and there is no need of internet connection (however the maps data are not local and they are provided by Google).

\subsection{Replacing Configuration File}
We have implemented the external configuration file, because now we can easily change the vehicle parameters with no need of application recompilation. The configuration file is included in application installation package. This package with apk extension is in reality just a zip file with an internal folder structure. The configuration file config.xml is located in /res/raw/ folder. To change the vehicle parameters, we need to replace the configuration file. However, we must also re-sign the application so it can be installed. One of the approaches is to use free APK Edit application available on the internet. This program enables to edit apk installation files with automatic re-signing. 


\section{Google Maps JavaScript API V3}
This text is not supposed to document all the Google Maps API. In this chapter, it is going to be summarized only the most important features and characteristics we need to know to understand our application. Complete documentation is available on-line~\cite{googleApi}.

\subsection{Directions}
Google Directions services calculates directions using DirectionsService object. Accessing the directions service is asynchronous, so a callback method processing the result must be used. To initiate a request, DirectionsRequest object shall be passed from the callback method.

\lstset{language=Java, caption=DirectionsRequest object fields., label=lst:DirReq}
\begin{lstlisting}
{
  origin: LatLng | String,
  destination: LatLng | String,
  travelMode: DirectionsTravelMode,
  unitSystem: DirectionsUnitSystem,
  waypoints[]: DirectionsWaypoint,
  optimizeWaypoints: Boolean,
  provideRouteAlternatives: Boolean,
  avoidHighways: Boolean,
  avoidTolls: Boolean
  region: String
}
\end{lstlisting}

In listing~\ref{lst:DirReq} is shown a complete DirectionsRequest object fields list. Only the first three elements are required - origin: the start location from which the route is calculated, destination: end location to which the route is calculated and travelMode: mode of transport. Currently, there are three types of transport available. Driving, walking and bicycling (bicycling is supported in US only for now). In our application, only driving is used. 

The other fields of the DirectionsRequest are optional. It is possible to specify more intermediate waypoints or add restrictions to avoid highways or tolls. If provideRouteAlternatives is true, the Google service can response with more than one route alternatives. However, there is no rule concerning the order described in the Google API documentation. Also, it can increase server's response time. 

If the directions query status is ``OK'', we will receive DirectionsResult object which contains an array of DirectionsRoute objects of size greater than zero. Each DirectionsRoute object contains more fields. The most important are ``overview\_path'' which defines an array of LatLngs (latitude and longitude object) that represent an approximate (smoothed) path of the resulting directions. Also, it contains legs of the route array. Every leg represent route between two intermediate waypoints. Finally, a leg contains information about different steps of the route which are especially duration in seconds and distance in meters. It is important to know, that both duration and distance fields may be undefined if they are unknown. 

In figures~\ref{fig:distance} and \ref{fig:duration} are plotted data returned from Google server about distances and durations of route's legs. It is a route between ESIEE Paris and Noisy-le-Grand, rendered also in figure~\ref{fig:gui}. You can see, that the route contains 10 legs of different durations and distances.

\begin{figure}[ht]
    \center
    \includegraphics[width=12cm]{images/android/distance.png}
    \caption{Distances of route's legs (route from ESIEE Paris to Noisy-le-Grand).}
    \label{fig:distance}
\end{figure}

\begin{figure}[ht]
    \center
    \includegraphics[width=12cm]{images/android/duration.png}
    \caption{Durations of route's legs (route from ESIEE Paris to Noisy-le-Grand).}
    \label{fig:duration}
\end{figure}

Finally, to render the route, we used DirectionsRenderer object provided by Google which automatically renders the smoothed route (figure~\ref{fig:gui}).

Use of the Google Directions API is subject to a query limit of 2,500 directions requests per day. Individual directions requests may contain up to 8 intermediate waypoints in the request. Google Maps Premier customers may query up to 100,000 directions requests per day, with up to 23 waypoints allowed in each request.

\subsection{Elevations}
Once we have received Directions results, we use sampled path elevation request to get all the altitudes of the route. The elevation request is composed from path, which is an array of LatLng objects (latitudes and longitudes) and from number of samples. As the path, we pass the ``overview\_path'' array obtained from DirectionsResult object, which contains smoothed approximative path of the route. 

The server's response contains altitude samples within the route. In figure~\ref{fig:altitude} are shown the altitude samples within the same route as in the plots above.

\begin{figure}[ht]
    \center
    \includegraphics[width=12cm]{images/android/altitude.png}
    \caption{Altitude samples within the route (sample every 20 meters, route from ESIEE Paris to Noisy-le-Grand).}
    \label{fig:altitude}
\end{figure}

Use of the Google Elevation API is subject to a limit of 2,500 requests per day (Premier users may send up to 100,000 requests per day). In each given request you may query the elevation of up to 512 locations, but you may not exceed 25,000 total locations per day (1,000,000 for Premier users).

\subsection{Traffic}
Unfortunately, Google Maps JavaScript API V3 does not provide public traffic service API. For now, the only way how to get the traffic information is a map overlay which display a color coded routes based on a traffic situation (green route is fast traffic, red route is slow traffic). Additionally, not in all countries and cities the traffic situation is supported. 

Google can provide the traffic information only if there is enough speed and position data available. These data are furnished by traffic sensors and especially by GPS Google navigations. That is why, the traffic situation can be available only in specific hours.

\section{Altitude and Power Sampling}
The maximal number of altitude samples within a path is 512. In our application, we determine the overall distance of the route and than calculate number of samples for discretization every 20 meters. If the number is greater than 512 (the route is longer than 10240 meters), we use the maximal samples number 512. Otherwise we use the calculated samples number in order to take an altitude sample every 20 meters. In the next version, we could request altitude samples for more smaller parts of the route, so if the route is longer than 10240 meters, we could still sample every 20 meters. However, in the case of Google API, we must count with longer server response times and also with server requests limitations.

The power sampling is used only with Dynamic Programming algorithm. For now, the discretization interval of the power profile is hard-coded in the CycleView.java file in energyOptimization method. Nevertheless, in the next version, some dynamic discretization based on power variation and amplitude could be implemented.

