Wednesday, May 23, 2012

How to Create a Horizontal Dropdown Menu with HTML, CSS and jQuery

The Basics

 

Let's start with the basic HTML structure of the menu:
1
2
3
4
5
6
7
<ul id="coolMenu">
<li><a href="#">Lorem</a></li>
<li><a href="#">Mauricii</a></li>
<li><a href="#">Periher</a></li>
<li><a href="#">Tyrio</a></li>
<li><a href="#">Quicumque</a></li>
</ul>
A menu consists of an unordered list, and each list item contains a link with the text. Don’t create unnecessary divs. You don’t need any.
To add a sub menu simply nest another unordered list inside the item that's going to have the sub menu, like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<ul id="coolMenu">
    <li><a href="#">Lorem</a></li>
    <li><a href="#">Mauricii</a></li>
    <li>
        <a href="#">Periher</a>
        <ul>
            <li><a href="#">Hellenico</a></li>
            <li><a href="#">Genere</a></li>
            <li><a href="#">Indulgentia</a></li>
        </ul>
    </li>
    <li><a href="#">Tyrio</a></li>
    <li><a href="#">Quicumque</a></li>
</ul>
As you can see, creating the structure is very simple. This is how it should look in your browser at this stage:


There are multiple ways to set up the CSS for a horizontal menu. After many years I found that this is the quickest and cleanest way to do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#coolMenu,
#coolMenu ul {
    list-style: none;
}
#coolMenu {
    float: left;
}
#coolMenu > li {
    float: left;
}
#coolMenu li a {
display: block;
    height: 2em;
    line-height: 2em;
    padding: 0 1.5em;
    text-decoration: none;
}
#coolMenu ul {
    position: absolute;
    display: none;
z-index: 999;
}
#coolMenu ul li a {
    width: 80px;
}
#coolMenu li:hover ul {
    display: block;
}
  • I decided to float the whole menu to contain it but you can use overflow hidden or even set a fixed width for the same purpose.
  • It is important to float the list elements rather than the links.
  • The links should be displayed as blocks, otherwise, they won’t behave as expected.
  • Absolute position the submenu and hide it to remove it from the regular flow and make it invisible. Also, set a high z-index to prevent the submenu from showing behind other elements.
  • Set a height for the link elements and the line-height equal to the height to center the text vertically. By specifying a fixed height instead of just using padding you avoid flickering problems with jQuery animations later on.
  • Even though it’s not necessary to set a fixed width for the submenu items, it’s always a good practice. It allows you to style them more consistently later on.
  • Notice that the hover state is set on the list element and not the link.
With all this set, the menu should be already working. Try opening it in your browser and hovering over the third option to show the sub menu.

 

Improving Usability

 

This step will cover how to style the menu with some basic CSS to make it more accessible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* Main menu
------------------------------------------*/
#coolMenu {
    font-family: Arial;
    font-size: 12px;
    background: #2f8be8;
}
#coolMenu > li > a {
    color: #fff;
    font-weight: bold;
}
#coolMenu > li:hover > a {
    background: #f09d28;
    color: #000;
}
 
/* Submenu
------------------------------------------*/
#coolMenu ul {
    background: #f09d28;
}
#coolMenu ul li a {
    color: #000;
}
#coolMenu ul li:hover a {
    background: #ffc97c;
}
Keep in mind this is very basic, and is meant to be just an example. You can style this however you want. The important thing to remember here is, as I mentioned before that the hover states, are styled in the list items and not the links.

 

Thursday, May 10, 2012

Open Source Java GPS Map Application Framework

The dinopolis gpstool package is an open source (LGPL) Java GPS application. It consists of different modules that may be used as a programmer's framework or as an application. The main application is GPSylon. A smaller command line tool (demonstration of the gpsinput library) is named GPSTool. The library that is used to communicate with the gps device can be used independently and is provided as a separate jar file (since version 0.5).

Short Description of GPSylon

GPSylon is able to show maps downloaded from the expedia map servers. It may connect to a gps device and track your position on the maps. At the moment, it is able to read gpsdata in the NMEA standard from a serial gps device, a file or a gps daemon across a network.
The main feature is the display of various maps. GPSylon allows the user to navigate around like in a digital atlas. It shows maps of different scales, so missing maps of one scale do not result in a black screen, but show the next larger scale.
It allows the download of a single map or for a given location or for multiple maps in a given rectangular area from mapblast or expedia map servers. In the download mouse mode the user may choose a single map or by dragging a rectangle with the mouse, the user may choose to download maps for a larger area. This functionality allows the user to download maps in a given scale for a larger area. Please only download maps you need and be careful not to download thousands of maps, as the map providers will discontinue their service when it is misused!
It uses the open source library openmap for various cartographic things.

Features

The following features are implemented.
  • Display different maps from mapblast or expedia server (also for maps of different scale).
  • Display current position (gps position).
  • Read gps data from serial device, file, or gpsd (daemon).
  • Uses the following NMEA sentences: GLL, HDG, RMC, GGA, GSV, DBT, VTG, HTD.
  • Display a track from gps data.
  • Save the track.
  • Load a track created from GPSylon or from gpsdrive.
  • Import maps from gpsdrive.
  • Download a map for a given position.
  • Download maps for an area.
  • Measure distance (ruler).
  • Read and display shape files (very basic, not well tested!).
  • display graticule lines
  • window to display the raw nmea data
  • Location Marker support: (creating markers, load markers from files (comma or space separated (name, latitude, longitude [,category]) - in that order!)), export markers to csv files, icons for categories, import geonet data (available from http://164.214.2.59/gns/html/index.html)
  • Database support for Location Markers - selection of categories to display.
    Different databases are supported (derby and hsqldb (both pure java, zero configuration), mysql and postgresql) - the database and all tables are created automatically
  • Level Of Detail: depending on the chosen scale, not all location markers are displayed. The level of detail is increased when the user zooms in or chooses to override the level of detail. This behaviour might be tricky, when the user creates a location marker in a category that does not show due to its higher level of detail. So the user may not see the newly created marker.
  • Search for location markers and set the center of the map to a search result. This is extremely useful in combination with the geonet data. So, after importing the geonet data, one is able to search for very small villages or other points of interest. When using mysql or postgresql as a database, the lookup for names of location markers is very fast, the (default) hsql database is about 5 to 10 times slower (but also works perfectly, just slower :-). So if one or more geonet files should be imported, I recommend mysql or postgresql (see in the installation section for configuration details).

Supported GPS Devices

In general, all gps devices that support NMEA communication should work. Garmin protocol support is built in.
There were reports of the following devices to work with GPSylon:
  • Garmin Etrex Summit/Legend (NMEA/garmin modes) tested by myself)
  • Garmin eMap (NMEA/garmin modes) (reported by Thomas Müller))
  • Trimble Lassen SK8 (NMEA mode) (reported by Didier Donsez)
  • Garmin 35 (NMEA mode) (reported by Antonio)
  • Conexant '99 embedded module (NMEA mode) (reported by Antonio)
  • LeadTek Gps-9543 embedded module (NMEA mode) (reported by Antonio)
  • Garmin Geko 201 (garmin mode) (reported by Frank Wilhelm)
  • GlobalSat Bluetooth GPS BT-338 (tested by myself)
  • Navilock NL-303P PDA-GPS-Receiver with Serial/USB converter (tested by Silverbullet)
Linux users please note: serial ports must be like /dev/ttySXX, as otherwise rxtx does not recognize the port. So for bluetooth or USB devices, a symlink is needed!
For bluetooth connection, I used the following commands under linux to create a serial connection with bluetooth. First, find the id of your bluetooth device. I used hcitool for this:
            hcitool scan
            output:
            Scanning ...
            00:0B:5D:13:91:49       BEGRZ9001001
            00:0D:B5:30:3C:0A       BT-GPS-303C0A
            
The first id is my bluetooth dongle on the pc, the second is the gps device. So, with this id, we can create a virtual serial port using rfcomm:
            rfcomm bind /dev/ttyS50 00:0D:B5:30:3C:0A
            
As rxtx does not allow /dev/rfcomm0 as serial device, I used /dev/ttyS50 (all ttys below 50 were already existent in my installation). A symlink from ttyS50 to rfcomm0 also works! After this, I set some port parameter (I'm not sure, if this is really needed!):
            stty -F/dev/ttyS50 -raw -onlcr
            
Now, GPSTool or GPSylon can use the serial port /dev/ttyS50 for communication with the nmea bluetooth gps device. After closing the application, one should release the bluetooth serial port:
            rfcomm release /dev/ttyS50
            
Please note, that all these commands (except for the application start) need to be run as root!

Installation

No installation of GPSylon itself is needed. Nevertheless, some dependencies exist:
  • Java in Version 1.4 (or better) is needed. It can be obtained from Sun's Website. Development is currently done with version 1.5, but tests are done for version 1.4. Java version 1.3 will NOT work!
  • Starting from Gpsylon V0.5.2, NO installation of the Java serial libraries are needed anymore! The native libraries are shipped with Gpsylon and start scripts are provided (for Linux and Windows) for Gpsylon and Gpstool (ther command line application). So just unpack the archive, and run (or double click) gpsylon.cmd, gpstool.cmd (for Windows) respectivly gpsylon.sh, gpstool.sh for Unix (Native Libraries for Linux, Sun Solaris and MacOSX are provided). As there is no Apple computer around for testing, I am not sure, if the unix scripts will work. Feedback is welcome!
    Jan van Haarst reported that comfoolery can be used to forward the serial data to a network socket. GPSylon may connect to this socket when it is configured to use gpsd instead of the serial device.

Database for Location Markers

GPSylon is able to store and retrieve location markers from relational databases via JDBC. By default it uses the pure java open source Hypersonic DB (hsqldb). It has the advantage that no installation is needed and GPSylon creates a database on demand without any hassle.
As the geonet dataset is quite large (e.g. Austria 50 thousand entries, Germany 170 thousand entries), hsqldb seemed quite slow. So I gave it a try with mysql and it seems to be faster! Especially searching for location markers is faster by a factor 5 to 10! So I added a script that creates the table(s) needed (syntax differs slightly from the hsqldb syntax). The following steps are needed to use a mysql database instead of the built in hsqldb:
  • Install MySQL :-)
  • Create the database: e.g. with the command mysqladmin create gpsmap
  • Start GPSylon and edit database settings in the preferences (Location Marker tab):
    • JDBC Url: jdbc:mysql://localhost/gpsmap
    • JDBC Driver: com.mysql.jdbc.Driver
    • SQL Script to create the Database: sql/create_loation_mysql.sql
  • quit GPSylon
  • on the next start, GPSylon tries to access the new database, but cannot (as the tables are missing). It asks for administrators username/password (try "root" and empty password :-) so it can create the table(s). It will also add a user "sa" with no password for normal usage (access limited to gpsmap database).
  • That should be it! From now on, all location markers are stored and retrieved from the MySQL database.
For Postgresql support use the following configuration:
  • JDBC Url: jdbc:postgresql://localhost/gpsmap
  • JDBC Driver: org.postgresql.Driver
  • SQL Script to create the Database: sql/create_loation_postgresql.sql
The rest of the postgresql configuration is similar to the mysql configuration (install database, create a gpsmap database, create user and user rights, ...)

Run GPSylon

To start GPSylon, download the gpstool-archive, unpack it and call
java -jar gpssylon.jar
or if your environment is setup to handle jar-archives correctly, simply double click on the jar-archive (should work under windows). All needed classes are contained in the jar file. If you have the ant environment installed, call ant run.
For commandline arguments (everything may be configured in the application as well!), call
java -jar gpsylon.jar --help

Mouse Modes

GPSylon supports different mouse modes. Mouse modes may be added as plugins. At the moment, two mouse modes are available:
  • Navigation Mode: click anywhere in the map to zoom in and center at the clicked position. If the shift-key is held, a click zooms out. More navigational functionality will be implemented soon (pan, ...)
  • Download Mode: If the download mode is used, a window opens that displays some information about the map(s) to download. In the map window, a red rectangle (with crossed lines) shows the current location and size (size may not be exact and varies slightly from one internet map server to another). The user may change the location either by clicking in the map or by changing the coordinates in the download window. The coordinates may be entered in different formats (decimal, using the degree sign, etc.). The user may click and drag in the map to draw a rectangle. If the rectangle is larger that a single map, more than one rectangle is shown and the number of maps to download is shown in the download window. Please do not download maps excessively, as the companies that provide the maps do not like that and will stop their service if it is misused!

Plugins

GPSylon supports plugins of various kinds. The plugin-jars are used without the need to set the CLASSPATH. All jars in the directories [home]/.gpsylon/plugins and in the plugins directory of the applicaton are used.

Download

Please download the latest distribution of GPSylon at the download page on sourceforge.

Status

GPSylon is in beta-status. It runs quite stable, but many features are not implemented yet.

Articles about GPSylon

Elliotte Rusty Harold, the author of quite a few books about Java, mentioned GPSylon in his Cafe au Lait blog.

Other Projects

Other projects that use parts of the gpsinput/gpsylon code are:
  • GPS Position Producer
Projects that are somehow related to this project:
  • Gpsdrive was the main inspiration to write gpsylon.
  • MapGeneration tries to create free vector data from NMEA streams - this was one of the goals gpsylon was written for!
  • Maps4Free tries to do the same as a community project.

To Do List

urgent:
  • option to use always info from gpsdrive
  • optionally draw rectangle for small scale maps that do not show (done (map manager plugin)): done
  • download maps also larger than 1280x1024
  • use repaint(int,int,int,int): mostly done
  • are there GPS devices, that do not send RMC (for gps speed)??
  • check for speed sent from gps (calculation of distance s=v*t) (tachometer)
  • window showing NMEA data: done
Todo (wishlist):
routes
  • define route with mouse (like distant mouse mode)
  • name route
  • show table with available routes
  • download maps for a given route in a given scale (and image size)
  • follow a given route with gps
waypoints
  • different lists of waypoints: done, categories should do the job
  • display different list of waypoints: done, categories should do it
  • different symbols for waypoints: done, for a couple of categories, more to come
  • store waypoints in database (hsqldb, mysql): done
overlays
  • show major cities (CSV), use them as waypoints
  • shape files: done (experimental)
  • GML
location database (GNR)
  • search for name in GNR (zipped files) (done, when gnr is imported)
  • goto location (done)
GPS Device
  • upload/download waypoints
  • download Tracks: download is done
  • upload Tracks
gps tracking
  • pursuit mode: done, cdaller 2002/09/06
  • as soon as manual navigation on screen, disable pursuit mode.
  • different color for height or speed
  • save gps tracks: done
  • load gps tracks from gps device: done
  • load gps tracks from file: done for own tracks, track of gpdsrive and gml tracks
  • autoscale (set scale, depending on speed)
vectorize tracks
  • define nodes (crossings) and arcs between nodes
  • define type of arcs (highway, smaller road, bicycle path)
  • export as GML
  • import as GML
communication to other applications
  • import/export maps, tracks, waypoints to gpsdrive, gpspoint (partly done)
  • option to leave maps there or copy them to .gpsylon/maps directory
maps
  • import scanned maps
  • download from different servers (expedia, mapblast, ...): done
  • allow proxy authentication: done
  • show table of maps (allow to delete, rename?, ...): partly done
  • download an area of maps: done<
autoroute calculation
    need vector data for this!
speech
  • output
  • input
distance notification
  • provide notifications for specific points (e.g. radar warning)
context menus (right mouse) / one button mouse (touchscreen) support????
  • set position
  • set destination
  • set waypoint
  • let each layer add menu for this

Compile Source Distribution

To compile the source distribution, the java make tool Ant from the apache project is needed. When correctly installed, a ant compile should be enough to compile the source.
ant help gives all ant-tasks.

Commandline tool GPSTool

GPSTool is a small command line application that demonstrates the usage of the classes to read data from a gps device. The main class is org.dinopolis.gpstool.GPSTool and it may be started using the provided gpstool-<version>.jar file (execute in a command window java -jar gpsylon-<version>.jar - double click does not make much sense, as it is a commandline application). Use "--help" to see all commandline switches.
The following features are implemented in GPSTool:
  • Show current position/altitude/speed/heading/info about satellites.
  • Use NMEA or Garmin protocol.
  • Download tracks, routes, and/or waypoints and print them in GPX format.
  • Make screenshots from the display of the gps device. This is tested with the following models: Garmin eTrex Summit, eTrex Legend, eMap, Geko201, Streetpilot III (partly, needs more work - could not finish due to the device powered down after sending the 10th line of the image).
  • Supprts Velocity templates to print tracks, routes, waypoints. These templates are easy to write. Use command line switch " --printdefaulttemplate" to show the gpx template. Other templates are provided in the auxiliary directory. 

Link: http://www.tegmento.org/gpsylon/

Monday, May 7, 2012

Reading Google Map pointers from a MySQL database

This is what how you can plot points on a google map using the google maps API, combined with a MySQL database.
The basic premise is that you have a MySQL database containing a series of latitudes and longitudes, and you need to read the latitudes/longitudes from the database and plot them onto the google map.

First thing first, create a a simple database table with a column for both latitude and longitude, you would of course have other fields depending on what data you are using the google map to represent. For simplicities sake, I’ve called them ‘lat’ and ‘lon’:

CREATE TABLE `map` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`lat` DECIMAL( 10, 6 ) NOT NULL ,
`lon` DECIMAL( 10, 6 ) NOT NULL ) ENGINE = MYISAM

We have set the lat and long as DECIMAL(10,6) to enable us to use decimal points due to how lat/long is represented (i.e 52.132633 is a latitude). We’ve also thrown in a auto incrementing ID for the primary key.
Now we have the MySQL table, we need to populate it, so go ahead and throw some latitudes and longitudesinto it. If you are feeling adventurous you can take a stab at Geocoding some locations using the API (I will be covering Geocoding in another article shortly). You can grab some latitudes and longitudes using maporama to search for a location, and you will find the lat/long on the bottom left corner of your screen.

Now onwards with the code.

First we need to connect to the database:
 
mysql_select_db(“dbname”, $db); ?&gt;

Next, we will need to include the google maps API key in the headof your page.


So, in the header of your page, enter this bit of script, with your API key placed where it says so:

<script src=“http://maps.google.com/maps?file=api&amp;v=2&amp;key=ENTERYOURKEYHERE” type=“text/javascript”></script>

Now we have set up access to the DB and linked to our google maps API, we can continue with the creation of the map.

Still in the of the page, create some javascript that will create the points. In this instance we want the points clickable so when you click on the point on the map, it will go to another webpage. For this we use the GEvent.addListener function, which will direct the user to the new page when they click on the point. We are directing people to a PHP page that will take the point as a variable from the address bar (using GET) and then display some sort of information depending on what is required.

<script type=“text/javascript”>// <![CDATA[
        function createMarker(point,html) {         var marker = new GMarker(point);
       GEvent.addListener(marker,"click",function(){ top.location = "http://www.websiteaddress.com/page.php?point="+point });
       return marker;
      }
// ]]></script>
Now we need to initialize the map:

<script type=“text/javascript”>// <![CDATA[
         function initialize() {
        if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"),{ size: new GSize(580,400) } );
              map.removeMapType(G_HYBRID_MAP);
                map.setCenter(new GLatLng(-3.703250,40.416741,0), 1);
                var mapControl = new GMapTypeControl();
                map.addControl(mapControl);
                map.addControl(new GLargeMapControl());
 
This is only half the code, but I thought I'd halt there for a second and explain what's happening, We are creating a new map, and placing it in the DIV on our page called 'map_canvas'. We can specifiy the size of the map you want, and what type of map you want(i,e satellite, street,hybrid etc). The size is controlled by the 'size:' command, and the type of map by the 'map.removeMapType', which will remove any type of map button you don't want. You also set the the starting point of the map by using the 'map.setCenter' function.

You finally add the controls onto the map, i.e if you want the zoom, and the directional cursors for navigating.
After initializing the map, and in the same script and function (notice how the above piece of javascript isn't closed by a

// ]]> tag, and the function isn't closed either with curly bracket), we need to now plot our points onto the map from our MySQL table. To do this we use PHP to perform a query on the database and extract the lat and long, assign them to variables and output each one in the javascript as a point. Simple (err..)!
$result_map = mysql_query($exe_map, $db)or die(mysql_error());
while(list($lat,$long) = mysql_fetch_row($result_map)){ echo "n var point = new GLatLng(".$lat.",".$long.");n";
echo "var marker = createMarker(point,'');n";
echo "map.addOverlay(marker);n";
echo "n";
}
?&gt;
And don't forget to close the function,'if' statement and script:
}
}
This basically gets all latitudes and longitudes from the database, row by row, and creates a point on the map by assigning the lat/long variables to a javascript variable called 'point'. A google map marker called 'marker' is then created with the coordinates assigned to 'point'. Finally the marker is added to the map. This is repeated for all points in the database table.

And that's the hard part done. We have read out our points from the database and added them to the google map. All we need to do is create All we need to do is put the google map in the place on the page we said we would ("map_canvas"), and initialize the javascript when the page loads, otherwise the map won't show up.

Make sure your body tag has these javascript fucntions included:
 Link: http://www.1stwebdesigner.com/tutorials/interactive-travel-map-google-maps-api/

Sunday, May 6, 2012

BlueCove JSR-82 Emulator module

BlueCove JSR-82 Emulator module

bluecove-emu is additional module for BlueCove to simulate Bluetooth stack.
bluecove-emu is a pure Java implementation of JSR-82 without Bluetooth hardware. Fully tested using TCK JSR-82 TCK test results
bluecove-emu requires Java 5 Standard Edition and uses RMI for inter process communication.
N.B. This is experimental module and have no monitoring GUI. Another module bluecove-emu-gui is in developement. Help us make it .

Usage

Start local bluetooth air simulator server
java -cp bluecove-2.1.0.jar;bluecove-emu-2.1.0.jar com.intel.bluetooth.emu.EmuServer
Start jsr-82 application that connects to air simulator server
java -Dbluecove.stack=emulator -cp bluecove-2.1.0.jar;bluecove-emu-2.1.0.jar;yourApp.jar org.your.app.Main
Start MIDP jsr-82 application that connects to air simulator server
java -Dbluecove.stack=emulator -cp microemulator.jar;bluecove-2.1.0.jar;bluecove-emu-2.1.0.jar org.microemu.app.Main btApp.jad

Emulator in Unit tests

Emulator has been designed to be used during unit test to help in automation of tests for JSR-82 applications.
For unit tests air simulator server can be started as in process server. EmulatorTestsHelper.startInProcessServer()
Documentation for BlueCove API that enables the use of Multiple Adapters and Bluetooth Stacks in parallel in the same JVM can be found here .
Complete JUnit test example can be found here ExampleTest

Configuration options

System properties:
  • `bluecove.stack=emulator` force BlueCove to use Emulator instead of real Bluetooth stack
  • `bluecove.deviceID=1` bluecove supports multiple local devices, this will force it to select second one.
  • `bluecove.deviceAddress=btaddr` select local devices by Bluetooth address
  • `bluecove.emu.rmiRegistryHost=localhost` air simulator server can be on remote computer
  • `bluecove.emu.rmiRegistryPort=8090` air simulator server listen on different port. Use 0 on the client to enable in process server (no rmi)
  • `bluecove.emu.rmiRegistry=true` air simulator server and RMI registry can be started inside client JVM
Emulator Configuration properties:
This is the resource file 'bluecove.emulator.properties' loaded by air simulator server. Defines devices address and names assignment. It also can define LocalDevice properties returned to the client application.

 Link:  http://bluecove.org/bluecove-emu/

Thursday, May 3, 2012

Free Java ME GPS Tracking Software

FollowMe 1.2 - Free Java ME GPS Tracking Software

 FollowMe 1.2 Free Open Source GPS tracking software for MIDP 2.0+ phones

FollowMe is the new name for Silent Software's LocateMe, this small (45K) application requires a mobile phone with an integrated GPS or a separate Bluetooth GPS and will show you the direction to given locations ("targets") without maps, using a pulsing direction arrow. You can request the location of other FollowMe users by text message, send your own position, or just simply save locations ("targets") for directions back to them later. Targets can even later be imported into Google Earth or Maps.


The Features

  • "Target" other FollowMe users' positions via a text message
  • Save multiple locations (targets "waypoints") with names (NEW for 1.2)
  • Stores your targets as Google Earth/Maps KML (NEW for 1.2)
  • Send your current position to other FollowMe users via text message
  • Connects to any mobile phone integrated GPS or Bluetooth GPS
  • View all the satellites around you on a "radar" style view
  • Display RAW GPS data (suitable for testing)
  • Complete integrated GPS support (some features may not be available depending on phone GPS capability).

For developers the fully commented source code provides
  • Design patterns, i.e. lazy initialization, command, strategy patterns
  • An example of a 2 tier system
  • How to use PushRegistry and File Connector (JSR 118)
  • How to use the Record Store (JSR 118)
  • How to use Bluetooth (JSR 82)
  • How to use Text Messaging (JSR 120)
  • How to use the PIM (and hack to minimise the security notices - JSR 75)
  • How to use the Location Based API (JSR 179 - Nokia lapi.jar included for use on non GPS integrated phones)
  • How to use simple graphics (not using a Game Canvas however)
  • How to multi thread effectively
  • How to process raw NMEA GPS data
  • Basic usage of the NanoXML parser
  • Basic understanding of graphical and GPS trigonometry

 Known Issues
  • The application is not security signed (this costs money!), so you will be shown numerous security popups when you start it.
  • As your phone is not a compass the direction target arrow will only point to the correct direction once you start walking, and the phone can determine which way relative to North you are going, i.e. when you are stood still your phone doesn't know which direction you are facing! :) On startup, until the GPS gets an accurate fix, the direction arrow to the target WILL NOT BE SHOWN.
  • On first run there can be some delay discovering the Bluetooth devices in busy areas (i.e. it may display "Waiting for GPS..." on first run for some time). This is down to the Bluetooth device discovery picking up a large number of devices and querying them. Once you have located your GPS, future connections to the GPS do not require this discovery period and will be relatively quick.

Compatibility
This software has been tested on Nokia Series 40 3rd edition phones at a minimum resolution of 128x128 pixels and Sun WTK emulator at 240x320. It has also been successfully tested on a Nokia N95 and Nokia 6650 with integrated GPS', and the INQ1 phone with separate Bluetooth GPS.

Link: http://silentdevelopment.blogspot.com/

Thursday, April 26, 2012

J2ME Bluetooth GPS Guide

J2ME Bluetooth GPS Guide

 

Bluetooth API JSR-82

The Java APIs for Bluetooth define the following package that depends on the CLDC javax.microedition.io package:
  • javax.bluetooth: core Bluetooth API
The above package is a separate optional package, which means that a CLDC implementation can include either package or both. MIDP-enabled devices are expected to be the kind of devices to incorporate this specification.

Application Programming

The anatomy of a Bluetooth application has five parts: stack initialization, device management, device discovery, service discovery, and communication.

Stack Initialization

The Bluetooth stack is responsible for controlling the Bluetooth device. The initialization process comprises a number of steps whose purpose is to get the device ready for wireless communication.

Device Management

The Java Bluetooth APIs contain the classes LocalDevice and RemoteDevice, which provide the device-management capabilities defined in the Generic Access Profile. LocalDevice depends on the javax.bluetooth.DeviceClass class to retrieve the device's type and the kinds of services it offers. The RemoteDevice class represents a remote device (a device within a range of reach) and provides methods to retrieve information about the device, including its Bluetooth address and name. The following code snippet retrieves that information for the local device:
...
// retrieve the local Bluetooth device object
LocalDevice local = LocalDevice.getLocalDevice();
// retrieve the Bluetooth address of the local device
String address = local.getBluetoothAddress();
// retrieve the name of the local Bluetooth device
String name = local.getFriendlyName();
...
You can get the same information about a remote device:
...
// retrieve the device that is at the other end of
// the Bluetooth Serial Port Profile connection,
// L2CAP connection, or OBEX over RFCOMM connection
RemoteDevice remote =
    RemoteDevice.getRemoteDevice(
        javax.microedition.io.Connection c);
// retrieve the Bluetooth address of the remote device
String remoteAddress = remote.getBluetoothAddress();
// retrieve the name of the remote Bluetooth device
String remoteName = local.getFriendlyName(true);
...
The RemoteDevice class also provides methods to authenticate, authorize, or encrypt data transferred between local and remote devices.

Device Discovery

Because wireless devices are mobile they need a mechanism that allows them to find other devices and gain access to their capabilities. The core Bluetooth API's DiscoveryAgent class and DiscoveryListener interface provide the necessary discovery services.
A Bluetooth device can use a DiscoveryAgent object to obtain a list of accessible devices, in any of three ways:
The DiscoveryAgent.startInquiry method places the device into an inquiry mode. To take advantage of this mode, the application must specify an event listener that will respond to inquiry-related events. DiscoveryListener.deviceDiscovered is called each time an inquiry finds a device. When the inquiry is completed or canceled, DiscoveryListener.inquiryCompleted is invoked.
If the device doesn't wish to wait for devices to be discovered, it can use the DiscoveryAgent.retrieveDevices method to retrieve an existing list. Depending on the parameter passed, this method will return either a list of devices that were found in a previous inquiry, or a list of pre-known devices that the local device has told the Bluetooth Control Center it will contact often.
These three code snippets demonstrate the various approaches:
...
// retrieve the discovery agent
DiscoveryAgent agent = local.getDiscoveryAgent();
// place the device in inquiry mode
boolean complete = agent.startInquiry();
...
...
// retrieve the discovery agent
DiscoveryAgent agent = local.getDiscoveryAgent();
// return an array of pre-known devices
RemoteDevice[] devices =
   agent.retrieveDevices(DiscoveryAgent.PREKNOWN);
...
...
// retrieve the discovery agent
DiscoveryAgent agent = local.getDiscoveryAgent();
// return an array of devices found in a previous inquiry
RemoteDevice[] devices =
    agent.retrieveDevices(DiscoveryAgent.CACHED);
...

Service Discovery

Once the local device has discovered at least one remote device, it can begin to search for available services - Bluetooth applications it can use to accomplish useful tasks. Because service discovery is much like device discovery, DiscoveryAgent also provides methods to discover services on a Bluetooth server device, and to initiate service-discovery transactions. Note that the API provides mechanisms to search for services on remote devices, but not for services on the local device.

Communication

For a local device to use a service on a remote device, the two devices must share a common communications protocol. So that applications can access a wide variety of Bluetooth services, the Java APIs for Bluetooth provide mechanisms that allow connections to any service that uses RFCOMM, L2CAP, or OBEX as its protocol. If a service uses another protocol (such as TCP/IP) layered above one of these protocols, the application can access the service, but only if it implements the additional protocol in the application, using the CLDC Generic Connection Framework.

Serial Port Profile

The RFCOMM protocol, which is layered over the L2CAP protocol, emulates an RS-232 serial connection. The Serial Port Profile (SPP) eases communication between Bluetooth devices by providing a stream-based interface to the RFCOMM protocol. Some capabilities and limitations to note:
  • Two devices can share only one RFCOMM session at a time.
  • Up to 60 logical serial connections can be multiplexed over this session.
  • A single Bluetooth device can have at most 30 active RFCOMM services.
  • A device can support only one client connection to any given service at a time.
For a server and client to communicate using the Serial Port Profile, each must perform a few simple steps.
As the following code snippet demonstrates, the server must:
  1. Construct a URL that indicates how to connect to the service, and store it in the service record
  2. Make the service record available to the client
  3. Accept a connection from the client
  4. Send and receive data to and from the client
The URL placed in the service record may look something like:
btspp://102030405060740A1B1C1D1E100:5
This says that a client should use the Bluetooth Serial Port Profile to establish a connection to this service, which is identified with server channel 5 on a device whose address is 102030405060740A1B1C1D1E100.
...
// assuming the service UID has been retrieved
String serviceURL =
    "btspp://localhost:"+serviceUID.toString());
// more explicitly:
String ServiceURL =
    "btspp://localhost:10203040607040A1B1C1DE100;name=SPP
        Server1";
try {
    // create a server connection
    StreamConnectionNotifier notifier =
      (StreamConnectionNotifier) Connector.open(serviceURL);
    // accept client connections
    StreamConnection connection = notifier.acceptAndOpen();
    // prepare to send/receive data
    byte buffer[] = new byte[100];
    String msg = "hello there, client";
    InputStream is = connection.openInputStream();
    OutputStream os = connection.openOutputStream();
    // send data to the client
    os.write(msg.getBytes());
    // read data from client
    is.read(buffer);
    connection.close();
} catch(IOException e) {
  e.printStackTrace();
}
...
At the other end, as the next code snippet shows, to set up an RFCOMM connection to a server the client must:
  1. Initiate a service discovery to retrieve the service record
  2. Construct a connection URL using the service record
  3. Open a connection to the server
  4. Send and receive data to and from the server
...
// (assuming we have the service record)
// use record to retrieve a connection URL
String url =
    record.getConnectionURL(
        record.NOAUTHENTICATE_NOENCRYPT, false);
// open a connection to the server
StreamConnection connection =
    (StreamConnection) Connector.open(url);
// Send/receive data
try {
    byte buffer[] = new byte[100];
    String msg = "hello there, server";
    InputStream is = connection.openInputStream();
    OutputStream os = connection.openOutputStream();
    // send data to the server
    os.write(msg.getBytes);
    // read data from the server
    is.read(buffer);
    connection.close();
} catch(IOException e) {
  e.printStackTrace();
}
...
How to read GPS data from Bluetooth stream

Code snippet
readBluetoothBuffer()
{
data = readAllAvailableBytes()
if (data.length == 0)
Bluetooth connection not there
else
Bluetooth seems OK
bytesRead = readBytes();
if (no bytesRead)
read error
else
START Loop
find newLine()
{
                    //figure out whether it's RMC or GGA
                    String candidate = readBuffer
                
                    //figure out whether RMC or GGA
                    if (candidate is $GPRMC....)
                   {
                        Store candidate as RMC
                    }
                    else if (candidate is $GPGGA)
                    {
Store candidate as GGA
                    }
            }
            END Loop
}
Common NMEA Sentence types
The following information describes the NMEA-0183 sentences transmitted by TeleType GPS receivers.
Sentence Description
$GPGGA Global positioning system fixed data
$GPGLL Geographic position - latitude / longitude
$GPGSA GNSS DOP and active satellites
$GPGSV GNSS satellites in view
$GPRMC Recommended minimum specific GNSS data
$GPVTG Course over ground and ground speed

Link : http://developer.att.com/developer/forward.jsp?passedItemId=3400032

 

Wednesday, April 4, 2012

Faster Data Transfer With Bluetooth and Contactless Communication

Faster Data Transfer With Bluetooth and Contactless Communicatio

 

Bluetooth technology allows two devices near each other to communicate at a maximum speed of 3 Mb per second. In the grand scheme of wireless communication, Bluetooth is roughly two times faster than the data throughput of a 3G wireless phone but still 10 to 20 times slower than today's Wi-Fi speeds.

More than one billion Bluetooth-enabled devices are currently on the market, and Bluetooth does a good job of transferring files that are smaller than 10 MB in size. However, due to the inherent nature of most wireless communication protocols, Bluetooth devices need to discover other Bluetooth devices, even if both devices are right next to each other. Finding a remote Bluetooth device is great, but what services does that remote Bluetooth device offer? If the remote device is a printer, does it offer the commonly used Basic Printing Profile (BPP) or the more advanced printing service known as the Hard Copy Cable Replacement Profile (HCRP)?
To find the available services on a remote Bluetooth device, you also need to search for a service. Bluetooth device-discovery and service-searching capabilities are great when you are trying to find any remote Bluetooth device in the vicinity that can suit your needs.
But device discovery and service searching are extremely time-consuming and frustrating to use when you're trying to communicate with a device that's right in front of you. This article shows you how to get Bluetooth applications to completely bypass the device-discovery and service-searching processes simply by using Near-Field Communication (NFC) technology and JSR 257: Contactless Communication API.
Contents

- Introduction to NFC Technology
- Introducing JSR 257: Contactless Communication API
- Basic Bluetooth or NFC + Bluetooth: Which Is Faster?
- Do Things Faster: Add NFC to the Picture
- Conclusion
- For More Information

Introduction to NFC Technology

What exactly is NFC technology? NFC is a radio communication standard that enables wireless data transfer between two devices at a very short distance -- less than 10 centimeters. NFC devices include a certain class of radio-frequency identification (RFID) tags and contactless smart cards. NFC devices operate within the 13.56 MHz frequency range, and they support extremely low data rates -- a maximum of 0.42 Mb per second.
Compared to Bluetooth and Wi-Fi, NFC technology operates at drastically reduced transfer rates and only within a very small proximity. If that's the case, why use NFC technology? Here are three reasons:
  • Setup time. NFC devices communicate instantly -- in less than 100 milliseconds -- when placed within range.
  • Power consumption. NFC tags and cards do not consume power, so their lifespan can be unlimited.
  • Cost. NFC tags and cards are inexpensive to manufacture compared to other wireless technologies.
NFC technology has easily met the need for certain use cases in the industry, such as the following:
  • Wireless payments. Traditional smart cards have been used for cashless payments for years. The short setup time for NFC devices allows mobile payments to be even easier.
  • Smart magazines and posters. Want to get more information about something you read in a magazine or see on a poster on the street? Just tap the page to get more information, or get the URL to store the bookmark for later use.
  • Transit tickets. When used in scenarios for mass transit, NFC-enabled phones are simple and convenient.
  • Business-card exchange. Because setup times for communication between NFC devices are very short, NFC devices are ideal for business-card exchanges.
Table 1 compares NFC with other wireless communication technologies.

Table 1: A Comparison of Wireless Communication Standards

International Standard
Operating Frequency
Maximum Data Rate
Maximum Distance
Power Consumption Rate
Bluetooth 3.0
IEEE 802.15.1
2.4 GHz
22 Mb/s
100 m
hours/days
Bluetooth 2.1
IEEE 802.15.1
2.4 GHz
3 Mb/s
100 m
days
NFC
ISO 14443
13.56 MHz
0.42 Mb/s
10 cm
∞
Wi-Fi B
IEEE 802.11b
2.4 GHz
11 Mb/s
100 m
hours
Wi-Fi G
IEEE 802.11g
2.4 GHz
54 Mb/s
100 m
hours
Wi-Fi N
IEEE 802.11n
5 / 2.4 GHz
144 Mb/s
100 m
hours
ZigBee
IEEE 802.15.4
2.4 GHz
0.25 Mb/s
100-1200 m
months/years

As you can see, NFC technology is definitely not suited to transferring large amounts of data over long distances -- that is definitely a job for other wireless communication protocols such as any of the flavors of Wi-Fi.
But if you want to provide a small amount of information in a very short amount of time, then NFC may be for you. And a Java technology API is available that allows developers to interact with NFC devices: the JSR 257 API.

Introducing JSR 257: Contactless Communication API

JSR 257, the Contactless Communication API, is the Java ME API that allows mobile phones to communicate with a variety of devices within proximity. The Contactless Communication API allows your Java ME MIDlets to read and write data to the following entities:
  • External contactless smart cards
  • NFC tags
  • Generic RFIDs
  • 2D barcodes
  • Other NFC-capable phones
  • Internal secure elemen
Link: http://java.sun.com/developer/technicalArticles/javame/nfc_bluetooth/