Patch webOS GPS Tracking

From WebOS Internals
Revision as of 00:19, 19 December 2010 by Bulldozer2003 (talk | contribs) (→‎Reply with Maps Link and Delete Messages)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search


Here is my super happy awesome tracker script!

Script code

SECRET=make up any secret code here
DEST=put your e-mail address here

track()
{
        export IFS=$'\n'
        for loc in $(luna-send -n 3 palm://com.palm.location/startTracking '{"appId": "ILovePalm", "subscribe": true}' 2>&1); do
                send $(echo $loc|cut -f3- -d,)
        done
}

send()
{
        echo "Sending Message: $1"
        msg=$(echo $1| sed s/\"/\\\\\"/g)
        luna-send -n 1 palm://com.palm.messaging/sendMessageFromCompose '{"recipientJSONArray": [{"value": "'${DEST}'", "contactDisplay": "'${DEST}'", "prefix": "to$A", "identifier": "palm_anon_element_8"}], "messageText": "'"$msg"'"}'
}

checkmsg()
{
        echo ".timeout 30000" > /tmp/trackersql
        cmd='SELECT messageText FROM com_palm_pim_FolderEntry WHERE timeStamp > (strftime("%s000", "now")-600000);'
#       output=$(echo $cmd|sqlite3 /var/luna/data/dbdata/PalmDatabase.db3)
        output=$(echo $cmd|sqlite3 -init /tmp/trackersql /var/luna/data/dbdata/PalmDatabase.db3)
        echo $output|grep $SECRET 2> /dev/null > /dev/null
        status=$?

        if [ $status = 0 ]; then
                track
        fi
}

checkmsg

Installation

  1. mkdir -p /home/scripts
  2. Let's say you put the script in /home/scripts/track.sh
  3. rootfs_open -w
  4. Go here to enable crond.
  5. Add the following line to /etc/cron/crontabs/root
    */5 * * * * /home/scripts/track.sh
  6. Now just send the secret code you set in the script to $YOURNUMBER@messaging.sprintpcs.com (without dollar sign but as a ten digit number with area code prefix)

> Ex: 3335554444@messaging.sprintpcs.com where 333 is your area code, and 5554444 the rest of your phone number. and it will send $DEST the GPS data for the device.

Now, just take the latitude and longitude data and generate the URL. As to the other GPS parameter data available we'll have to investigate to see if Google Maps can take those parameters and how they map to the URL. ~Robi

luna-send -n 1 palm://com.palm.location/getCurrentPosition {}
** Message: serviceResponse Handling: 2, {"errorCode":0,"timestamp":1.245799702311E12,"latitude":37.48660683631897,"longitude":-122.23269581794739,"horizAccuracy":37.947330474853516,"heading":178,"velocity":0.75,"altitude":-13,"vertAccuracy":24}

which means we can transpose some of that to a Google Maps link:

http://maps.google.com/?ie=UTF8&q=37.48660683631897,-122.23269581794739+(Heading:%20178%0DSpeed:%200.75%20mph)

If you know more about the GPS parameters, let us know by updating the page. ~Robi

  • The velocity, altitude, and accuracy parameters are specified in meters
  • Added heading and speed parameters to the URL. If you hover over the pinpoint on the google map, you can see the information, as well as in the info window if you click on the pinpoint. -xluryan

"If [ll=] is used without a query, then the map is centered at the point but no marker or info window is displayed." To get around this, use q=[Lon,Lat] instead of ll=[Lon,Lat]. I changed the maps link above. -hopspitfire


Troubleshooting Tip: Make sure track.sh has the correct file permissions set. To encompass all possibilities, try 'chmod 755 /home/scripts/track.sh'. You can restrict permissions later if you wish. On Windows it's probably easiest to do this through WinSCP (right click>Properties>Permissions).

Development Ideas

1. Send response as a google maps link that clicked on shows the phones position on a map. 2. Find a way to put a hook into message reception so that messages don't have to be checked with a cron job. Even better if the message could be intercepted before appearing on the phone, it would be a useful way to track a stolen phone. 3. After implementing the script that emails me every 20 minutes, it occured to me that the following would be great:

 3a. The ability to log the entries instead of just sending an email, and maintain a preset number of logged entries (say the last 24 entries).
 3b. Using the original implementation - send a message to the device to have the logged information emailed. This would show a "track" of where the device has been.
 3c. Control of the number of log entries, and the frequency.

Another Simple Method

Why not use this script:

#!/bin/sh

pos=$(luna-send -n 2 palm://com.palm.location/startTracking '{"appId": "ILovePalm", "subscribe": true}' 2>&1 | tail -1 | cut -d, -f4,5,8 | sed -r 's/[^-\.0-9,]//g')

lat=$(echo $pos | cut -d, -f1)
lon=$(echo $pos | cut -d, -f2)
spd=$(echo $pos | cut -d, -f3)
bat=$(grep BATTERY_IPC: /var/log/messages | tail -1 | awk '{print $9}' | sed 's/%,//')

ret=$(wget -qO- "http://yoursite.com/trackme/$1/requests.php?lat=$lat&lon=$lon&speed=$spd&batt=$bat" | egrep -o '[0-9]+$')
exit $ret

I have a web server setup with //requests.php// taking //lat//, //lon//, //speed//, and //batt// arguments. Then it writes them to a file. Use the data however you want. I have mine plug into a google map and show me the data.

Just set up a cron job to call the script every 20 minutes or so. Hardly effects battery life at all :)

Credit to ddoc for info on how to grab battery status. I would still like to find a more efficient way of grabbing battery level rather than searching through the entire message log. Though for now, it works exactly like it should.

Here's the Method for getting battery status:

Mojo.Service.Request('palm://com.palm.power/com/palm/power/', {method: 'batteryStatusQuery',});

-pEEf

Email a URL to open Google Maps showing location of phone.

Below is a code snippet that will send an email with working URL to open Google Map and show you the location of your phone. The cron job mentioned above is setup to call this script every 20 minutes on my machine...works great. I let GMAIL archive them. If the phone gets stolen, I can find it as long as it has service.

The larger Accuracy is, the further away the coordinates output will be from your actual position.

Added speed & heading to Google URL. Is there any way to have the sent messages not appear in the Text Messaging app, or to use the shell to email the output via mailx? Until I figure out a built-in mail function, you can use an alternative I'm testing that uses a server's mailx command: echo "$msg2" | /opt/bin/ssh -x user@server /bin/mailx $DEST -hopspitfire

modified by wilderf353 on 09-09-01: I modified the original script because the Google URL being sent was getting truncated on my phone and a few other people that posted at forums.precentral.net. I did some testing and it looks like when you use sendMessageFromCompose, you are limited to a message with less than 136 characters. I shortened the message and added :

  • at the beginning of the script, turn on GPS if it is off
  • at the beginning of the script, turn on Location Services if it is off
  • at the end of the script, turn GPS back off, if it was off when the script started
  • at the end of the script, turn Location Services back off, if it was off when the script started
  • added altitude and altitude accuracy information to message
  • added the ability to only send the message if GPS coordinates have changed since the last run
  • added the ability to send a message on the hour even if GPS coordinates have not changed

(NOTE: You will need to add your email address to the script)

#!/bin/sh

####### Stuff to set

## email address to mail info to
DEST=johns@gmail.com
# example: DEST=wsmith@aol.com   (make sure you don't have any spaces)

## send url with embedded heading/speed info
# we only have ~136 characters to work with. If you embed heading & speed info, you can't 
# include altitude and altitude accuracy information 
# msg_with_heading=0  (don't embed heading/speed info, but include altitude information)
# msg_with_heading=1  (embed heading/speed info)
msg_with_heading=0

# run_only_if_diff=0, send a message every time 
# run_only_if_diff=1, send a message only if GPS coords have changed since last run 
run_only_if_diff=1

# file where gps coords should  be stored until next run
last_gps_coord_file=/tmp/track_coords

# use with run_only_if_diff
# send_every_hour=1, send a message on the hour, even if the phone hasn't moved
# send_every_hour=0, don't send a message on the hour
send_every_hour=1

######

# get current minute and current time
cur_min=$(date +"%M")
now=$(date +"%D %R")

# The GPS should be turned on to get an accurate fix...otherwise you get the tower location
# Is the GPS turned on? 
$(luna-send -n 1 palm://com.palm.location/getUseGps '{}' 2>&1 | grep 'true' > /dev/null)
grep_ret=$?
if [ $grep_ret -eq 0 ]        # Test exit status of "grep" command.
then
   # gps is on
   gps_on=1
else  
   #gps is off...let's turn it on and remember to turn it back off later
   gps_on=0
   $(luna-send -n 1 palm://com.palm.location/setUseGps '{"useGps":true}' > /dev/null 2>&1)
   # wait for 60 seconds so gps gets a good lock
   sleep 60
fi

# Location services must be turned on, or startTracking will not work (you get a {"errorCode":7})
# Are locations service turned on? 
$(luna-send -n 1 palm://com.palm.location/getAutoLocate '{}' 2>&1 | grep 'true' > /dev/null)
grep_ret=$?
if [ $grep_ret -eq 0 ]        # Test exit status of "grep" command.
then
   # location service is on
   location_service=1
else  
   #location service is off...let's turn it on and remember to turn it back off later
   location_service=0
   $(luna-send -n 1 palm://com.palm.location/setAutoLocate '{"autoLocate":true}' > /dev/null 2>&1)
fi

# Get current coords
pos=$(luna-send -n 2 palm://com.palm.location/startTracking '{"appId": "ILovePalm", "subscribe": true}' 2>&1 | tail -1 | cut -d, -f4,5,6,7,8,9,10 | sed -r 's/[^-\.0-9,]//g')

lat=$(echo $pos | cut -d, -f1)
lon=$(echo $pos | cut -d, -f2)
acc=$(echo $pos | cut -d, -f3 | cut -d. -f1)
dir=$(echo $pos | cut -d, -f4)
spd=$(echo $pos | cut -d, -f5)
alt=$(echo $pos | cut -d, -f6)
altacc=$(echo $pos | cut -d, -f7 | cut -d. -f1)
bat=$(grep BATTERY: /var/log/messages | tail -1 | awk '{print $8}' | sed 's/%,//')

# turn off GPS?
if [ $gps_on -eq 0 ]
then
   # the GPS was off when we started the script...turn it back off
   $(luna-send -n 1 palm://com.palm.location/setUseGps '{"useGps":false}' > /dev/null 2>&1)
fi

# turn off location service?
if [ $location_service -eq 0 ]
then
   # location service was off when we started the script...turn it back off
   $(luna-send -n 1 palm://com.palm.location/setAutoLocate '{"autoLocate":false}' > /dev/null 2>&1)
fi

# check if we should send a message
if [ $run_only_if_diff -eq 1 ] 
then
    # create short coords. 
    # use "printf("%3.4f\n",$0)" for 4 decimal places (about 30 feet accuracy)
    # use "printf("%3.3f\n",$0)" for 3 decimal places (about 280 feet accuracy)                                                            
    # use "printf("%3.2f\n",$0)" for 2 decimal places (about 0.5 miles accuracy)                                                            
    sh_lat=$(echo $lat |  awk '{printf("%3.4f\n",$0)}')
    sh_lon=$(echo $lon |  awk '{printf("%3.4f\n",$0)}')

   # does the file with the last coords exist?
    if [ -f $last_gps_coord_file ]
    then
        $(grep "$sh_lat $sh_lon" $last_gps_coord_file > /dev/null)
        grep_ret=$?
        if [ $grep_ret -eq 0 ]
        then
            # coords match...don't send a message
            send_message=0
        else
            # coords don't match...send a message and update coord file
            send_message=1 
            echo $sh_lat $sh_lon > $last_gps_coord_file                                                                                                   
        fi
    else
        # there is not a last coords file...create one for next time
        send_message=1
        echo $sh_lat $sh_lon > $last_gps_coord_file  
    fi
else
    # $run_only_if_diff is false, so send a message
    send_message=1        
fi

# if configured to send on the hour...is it time?
if [ $send_every_hour -eq 1 -a $cur_min = "00" ]
then
  send_message=1 
fi

# Enable this below if you want to keep logs - not sure where to write them /var/home/root not the best place.
# echo $now,$lat,$lon,$acc,$dir,$spd,$alt,$altacc,$bat >>mygpsdata.log

# send the message
if [ $send_message -eq 1 ]
then
    #Build message content to be sent
    if [ $msg_with_heading -eq 1 ]
    then
       msg=$(echo $now "\n" Bat:$bat Acc:$acc "http://maps.google.com/maps?q=$lat%2C$lon+(Heading:%20$dir%0DSpeed:%20$spd)")
    else
       msg=$(echo $now "\n" "http://maps.google.com/maps?q=$lat%2C$lon" "\n" Bat=$bat,Acc=$acc,Dir=$dir,Spd=$spd,Alt=$alt,AltAcc=$altacc)
    fi

    $(luna-send -n 1 palm://com.palm.messaging/sendMessageFromCompose '{"recipientJSONArray": [{"value": "'${DEST}'", "contactDisplay": "'${DEST}'", "prefix": "to$A", "identifier": "palm_anon_element_8"}], "messageText": "'"$msg"'"}' > /dev/null 2>&1)
fi

This has been running every 20 minutes on my phone for the last 4 days, no problem. -dld121


Reply with Maps Link and Delete Messages

This script is based off of the original code above as well as code I presume was from "isyougeekedup.com".

When put in your crontab the script looks for messages containing your secret key anywhere in them. It then turns on the GPS, replies to the sender of that message (works with messages sent from email too). We then leave the GPS on so you don't lose your fix, then the next time the script runs, if it receives no requests, will turn the GPS back off. Then the scripts deletes all traces of the received and sent messages, beware though, they are on the phone between the time they are received and the time the script runs. You may be able to install per-sender alerts to disable tones sent from specific numbers.

Added Altitude, Heading, Accuracy. I would like to know battery status, but I don't know where to get and it cannot be found in /var/log/messages on my phone.

#!/bin/sh
SECRET=make something up here

# Check if GPS is on or not and set variable accordingly.
GPS=`luna-send -n 1 palm://com.palm.location/getUseGps '{}' 2>&1 | awk 'BEGIN {FS="[ }]"} ; {print $7}'`

sendloc ()
{
    # Enable the GPS, if not already, for a more-accurate location fix. We will turn it off the nex time the script runs if no messages are sent out.
    if [ "$GPS" = "false" ]; then
        luna-send -n 1 palm://com.palm.location/setUseGps {\"useGps\":\"true\"}
        echo yes > /tmp/tracksetgps
    fi
    pos=$(luna-send -n 3 palm://com.palm.location/startTracking '{"appId": "ILovePalm", "subscribe": true}' 2>&1 | tail -1 | cut -d, -f4,5,6,7,8,9,10 | sed -r 's/[^-\.0-9,]//g')
    lat=$(echo $pos | cut -d, -f1)
    lon=$(echo $pos | cut -d, -f2)
    acc=$(echo $pos | cut -d, -f3)
    hed=$(echo $pos | cut -d, -f4)
    spd=$(echo $pos | cut -d, -f5)
    alt=$(echo $pos | cut -d, -f6)
    vac=$(echo $pos | cut -d, -f7)
    # Silencing logs removed battery messages.
    #bat=$(grep BATTERY: /var/log/messages | tail -1 | awk '{print $8}' | sed 's/%,//')
    now=$(date)
    # Enable this below if you want to keep logs - not sure where to write them /var/home/root not the best place.
    # echo $now,$lat,$lon,$spd,$bat >>mygpsdata.log
    #Build a message variable for all the data to be logged.
    msg=$(echo $now,$lat,$lon,$spd,$bat )
    #Build message content to be sent
    msg2=$(echo RE:$SECRET $now Speed:$spd  Heading:$hed  Altitude:$alt+-$vac  Accuracy:$acc  URL http://maps.google.com/maps?q=$lat%2C$lon)
    ret1=$(luna-send -n 1 palm://com.palm.messaging/sendMessageFromCompose '{"recipientJSONArray": [{"value": "'${DEST}'", "contactDisplay": "'${DEST}'", "prefix": "to$A", "identifier": "palm_anon_element_8"}], "messageText": "'"$msg2"'"}' 2>&1)
    echo SENT $msg2 >> /tmp/track.log
    delcmd='delete from com_palm_pim_FolderEntry where messageText like "%'$SECRET'%";'
    echo $delcmd|sqlite3 -init /tmp/trackersql /var/luna/data/dbdata/PalmDatabase.db3
    exit
}

checkmsg ()
{
    echo ".timeout 30000" > /tmp/trackersql
    destcmd='select fromAddress from com_palm_pim_FolderEntry where timeStamp > (strftime("%s000", "now")-600000) and messageText like "%'$SECRET'%" order by timestamp desc limit 1;'
    DEST=$(echo $destcmd|sqlite3 -init /tmp/trackersql /var/luna/data/dbdata/PalmDatabase.db3)
    NL=$'\n'
    DEST=${DEST%NL}
    if [ -n "$DEST" ]; then
        sendloc
    else
        # If we turned on the GPS, turn it off now.
        if [ "`cat /tmp/tracksetgps`" = "yes" ]; then
            luna-send -n 1 palm://com.palm.location/setUseGps {\"useGps\":\"false\"}
            echo no > /tmp/tracksetgps
        fi
        exit
    fi
}

echo `date` Checking messages to send location. > /tmp/track.log
checkmsg