I have never programmed using J2ME before the wonderfully obtuse piece of code you see below.

There are hooks to read and write from config files located locally on the phone. Using some configuration variables, you can easily set up your own i296 to send and receive data from the internet.

I will update this with comments later. If you need further explanation, or I've forgotten to do this, feel free to kick me. — Brad Luyster 2010/10/07 17:38

NewTest.java
package com.mot.j2me.midlets.newtest;
 
import java.io.*;
 
import javax.bluetooth.*;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javax.microedition.lcdui.*;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.QualifiedCoordinates;
import javax.microedition.midlet.*;
import javax.wireless.messaging.Message;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.MessagePart;
import javax.wireless.messaging.MultipartMessage;
import javax.wireless.messaging.TextMessage;
import java.lang.Object;
import java.util.Vector;
 
public class NewTest extends MIDlet implements CommandListener {
    // Display manager for the application
    Display display = null;
 
    // Main menu for the application
    List menu = null;
 
    // TextBox used for input
    TextBox input = null;
 
    //Google
    String gvoice = "+15025096852";
 
    //Twitter
    String tweet = "+40404";
 
    //File Access
    String config = "file://config.txt";
 
 
    //UDP
    //TODO: Replace with Config keys
    //UDP Addresses for Sending Telemetry
    static final String hostname = "zuph.com";
    static final int serverport 	= 1111;
 
    //Added for Bluetooth
    private static Connection instance=null;
    private StreamConnection stream=null;
 
    //TODO: Replace with Config Key
    //What bluetooth device to connect to?
    private final String url="btspp://00a09617a9b1:1";
    private String DatafrmServer="";
    OutputStream oustream=null;
    InputStream istream=null;
    //End of Bluetooth
 
 
 
    // Commands used in the application
    static final Command backCommand = new Command("Back", Command.BACK, 0);
    static final Command mainMenuCommand = new Command("Main", Command.SCREEN, 1);
    static final Command exitCommand = new Command("Exit", Command.STOP, 2);
    String currentMenu = null;
 
    // CommandTest constructor
    public NewTest() {
 
    }
 
    class sendTweet extends Thread
    {
    	//TODO: Use a config key for this.
    	private long tweetSleep = 9000000;
 
    	public void run()
    	{
 
    		while(true)
    		{
	    		String gps = null;
	    		try {
					gps = getHumanGPS();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
 
				gps = gps.substring(0, gps.indexOf("*"));
 
				try {
					sendMsg(tweet, gps);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
 
				try {
					this.sleep(tweetSleep);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
 
    	}
    }
 
    class sampleGatherAndSend extends Thread
    {
 
    	private int sampleNo = 0;
 
    	//TODO: Replace these with config keys.
    	private int sampleSleep = 5000;
    	private String sampleFile = "file://data.txt";
 
    	public void run()
    	{
    		//Delete old Data Samples
    		StreamConnection sc = null;
        	InputStream is = null;
        	OutputStream os = null;
 
        	try {
				CreateNewConnection();
			} catch (IOException e3) {
				// TODO Auto-generated catch block
				e3.printStackTrace();
			}
 
        	try {
	        	sc = (StreamConnection) Connector.open(sampleFile + ";DELETE");
	        	sc.close();
        	} catch(Exception e)
        	{
 
        	}
 
 
    		while(true)
    		{
    			//Gather Sample Data
    			try {
	    			sc = (StreamConnection) Connector.open(sampleFile);
		        	os = sc.openOutputStream();	
    			} catch(Exception e)
    			{
 
    			}
    			String sampleString = "S"+sampleNo+"~~";
 
    				//GPS
    			try {
					sampleString += getNMEA();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				sampleString += "~~";
 
				String telemetry = "";
				try {
 
					telemetry = WriteBtData("?");
				} catch (IOException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
 
 
				 //Telemetry
				sampleString += telemetry; //Stub for Telemetry Data
				sampleString += "~~~~";
 
    			//Save Sample Data to File
				try {
					os.write(sampleString.getBytes());
					sc.close();
					os.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}			
 
    			//Send Sample Data UDP
				sendUDP("datagram://" + hostname+":"+serverport,sampleString);
 
    			Alert myAlert = new Alert("Sample", Integer.toString(sampleNo), null, AlertType.INFO);
    			myAlert.setTimeout(1000);
    			display.setCurrent(myAlert);
 
    			sampleNo++;
 
    			try {
					this.sleep(sampleSleep);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    	}
 
    }
 
    /**
     * Starts the MIDlet by creating a list of items and assigning
     * the exit command to it.
     */
    public void startApp() throws MIDletStateChangeException {
      display = Display.getDisplay(this);
 
      menu = new List("Menu Items", Choice.IMPLICIT);
      menu.append("Send Text", null);
      menu.append("Snd GPS 2 Brad", null);
      menu.append("BT SPP", null);
      menu.append("Send INET Data", null);
      menu.append("Send Tweets", null);
 
      menu.addCommand(exitCommand);
      menu.setCommandListener(this);
 
      mainMenu();
    }
 
    public void pauseApp() {
      display = null;
      menu = null;
      input = null;
    }
 
    public void destroyApp(boolean unconditional) {
      notifyDestroyed();
    }
 
    // Main menu
    void mainMenu() {
      display.setCurrent(menu);
      currentMenu = "Main"; 
    }
 
    /**
     * A generic method which is called when one of the 
     * items on the list is selected.
     */
    public void prepare() {
       input = new TextBox("Enter some text: ", "", 5, TextField.ANY);
       input.addCommand(backCommand);
       input.setCommandListener(this);
       input.setString("");
       display.setCurrent(input);
    }
 
    public void sendMsg(String phone, String myMessage) throws IOException
    {
 
    	String appID = getAppProperty("MMS-ApplicationID");
    	String address = "mms://"+phone+":" + appID;
 
    	MessageConnection mmsconn = null;
 
    	mmsconn = (MessageConnection) Connector.open(address);
 
    	MultipartMessage mmmessage =(MultipartMessage) mmsconn.newMessage(MessageConnection.MULTIPART_MESSAGE);
    	mmmessage.setAddress(address);
 
    	String mimeType = "text/plain";
    	String encoding = "UTF-8";
 
    	byte[] contents = myMessage.getBytes(encoding);
    	MessagePart mpart = new MessagePart(contents, 0, contents.length, mimeType, "id" + 0, "contentLocation", encoding);
 
    	mmmessage.addMessagePart(mpart);
 
    	//mmmessage.setSubject("Hello World!");
    	mmsconn.send(mmmessage);
 
    	mmsconn.close();
 
    }
 
 
    private String [] split(String original, String delimiter)
    {
 
    	Vector nodes = new Vector();
		int index = original.indexOf(delimiter);
		while(index >=0) 
		{
			nodes.addElement(original.substring(0, index));
			original = original.substring(index+delimiter.length());
			index = original.indexOf(delimiter);
		}
		nodes.addElement(original);
 
		String[] result = new String[nodes.size()];
		if(nodes.size() > 0)
		{
			for(int loop=0; loop<nodes.size(); loop++)
			{
				result[loop] = (String)nodes.elementAt(loop);
			}
		}
 
    	return result; 	
    }
 
    public void configWrite(String key, String value) throws IOException
    {
 
    	StreamConnection sc = null;
    	InputStream is = null;
    	OutputStream os = null;
 
    	sc = (StreamConnection) Connector.open(config);
 
    	is = sc.openInputStream();
    	byte [] read = new byte[is.available()];
    	is.read(read);
 
    	String fileData = new String(read);
    	String [] fileLines = split(fileData, "\n");
    	String newFileData = new String();
 
    	boolean foundFlag = false;
 
    	for(int loop=0; loop < fileLines.length; loop++)
    	{
    		String[] key_value = split(fileLines[loop], " ");
    		if(key_value[0].equals(key))
    		{
    			key_value[1] = value;
    			fileLines[loop] = key_value[0] + " " + key_value[1];
    			foundFlag = true;
    		}
    		newFileData += fileLines[loop] + "\n";
    	}
    	if(!foundFlag)
    	{
    		newFileData += key + " " + value +"\n";
    	}
    	newFileData = newFileData.substring(0, newFileData.length()-1);
 
    	sc.close();
    	is.close();
 
    	sc= (StreamConnection) Connector.open(config+";DELETE");
 
    	sc.close();
 
    	sc = (StreamConnection) Connector.open(config);
 
 
    	os = sc.openOutputStream();
    	os.write(newFileData.getBytes());
 
    	sc.close();
    	os.close();
 
    }
 
    /**
     * Test item1.
     */
    public void testItem1() {
 
		try {
			sendMsg("+15025096852", "Hello");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Alert myAlert = new Alert("Test", "Text", null, AlertType.INFO);
		myAlert.setTimeout(5000);
 
		display.setCurrent(myAlert);
 
 
      currentMenu = "item1";
    }
 
    public String getNMEA() throws LocationException, SecurityException, IllegalArgumentException, InterruptedException
    {
 
    	LocationProvider lp = null;
    	Criteria cr = new Criteria();
 
    	lp = LocationProvider.getInstance(cr);
    	Location loc = lp.getLocation(-1);
 
    	return loc.getExtraInfo("application/X-jsr179-location-nmea");
 
    }
 
    public String getHumanGPS() throws SecurityException, IllegalArgumentException, LocationException, InterruptedException
    {
 
    	LocationProvider lp = null;
    	Criteria cr = new Criteria();
 
    	lp = LocationProvider.getInstance(cr);
    	Location loc = lp.getLocation(-1);
 
    	QualifiedCoordinates qc = loc.getQualifiedCoordinates();
 
    	double lat = qc.getLatitude();
    	double lon = qc.getLongitude();
    	double alt = qc.getAltitude();
    	double hed = loc.getCourse();
    	double spd = loc.getSpeed();
    	double time = loc.getTimestamp();
 
    	String xtra;
    	String twitX;
    	if(loc.isValid())
    	{
    		xtra = "";
    		twitX = "Valid Location";
    	} else {
    		xtra = loc.getExtraInfo("text/plain");
    		twitX = "Invalid Location";
    	}
		return "Lat:"+lat+" Lon:"+lon+" Alt:"+alt+" "+ twitX +"* Hed:"+hed+" Spd:"+spd+" Time:"+time+" X:"+xtra+"$";
 
    }
 
    /**
     * Test item2.
     */
    public void testItem2() {
 
 
    	try {
    		sendMsg("+15025339013", getHumanGPS());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
 
       currentMenu = "item2"; 
    }
 
    /**
     * Test item3.
     */
    public void testItem3() {
 
 
    	try {
    		CreateNewConnection();
    		WriteBtData("?");
    		CloseOpenConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
 
 
       currentMenu = "item3"; 
    }
 
    /**
     * Test item4.
     */
    public void testItem4() {
 
 
    	Thread mySampler = new sampleGatherAndSend();
    	mySampler.start();
       currentMenu = "item4"; 
    }
 
    public void testItem5() {
    	Thread myTweet = new sendTweet();
    	myTweet.start();
 
    	currentMenu = "item5"; 
 
    }
 
 
   /**
    * Event handler.
    */  
   public void commandAction(Command c, Displayable d) {
      String label = c.getLabel();
      if (label.equals("Exit")) {
         destroyApp(true);
      } else if (label.equals("Back")) {
          if(currentMenu.equals("item1") || currentMenu.equals("item2") ||
             currentMenu.equals("item3") || currentMenu.equals("item4") ||
             currentMenu.equals("item5"))  {
            // Returns to menu
            mainMenu();
          } 
 
      } else {
         List down = (List)display.getCurrent();
         switch(down.getSelectedIndex()) {
           case 0: testItem1();break;
           case 1: testItem2();break;
           case 2: testItem3();break;
           case 3: testItem4();break;
           case 4: testItem5();break;
         }
 
      }
  }
 
   public void sendUDP(String destAddr, String msg)
   {
 
	   int length = msg.length();
	   byte[] message = msg.getBytes();
 
	   DatagramConnection dc = null;
 
	   String localhost = "datagram://localhost:" + serverport;
 
	   try {
		   dc = (DatagramConnection)Connector.open(localhost);
	       Datagram dobject = dc.newDatagram(message, length, destAddr);         
	       dc.send(dobject);
	   } catch (Exception e){
 
	   } finally {
		   try {
			dc.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   }
 
   }
 
   //Bluetooth Code
   public void CreateNewConnection() throws IOException 
   {
	   try {
		   stream = (StreamConnection) Connector.open(url);
		   oustream = stream.openOutputStream();
		   istream = stream.openInputStream();
	   } catch (Exception e) {
		   Alert alert = new Alert("Sorry", "Sorry : Unable To Create Bluetooth Connectivity", null, AlertType.ERROR);
		   alert.setTimeout(Alert.FOREVER);
		   display.setCurrent(alert);
	   }
   }
 
   public String WriteBtData(String Data) throws IOException 
   {
	   byte[] ch= new byte[60];
	   if(stream!=null)
	   {	   
		   oustream.write(Data.getBytes());
		   try {
			   Thread.sleep(1000);
		   } catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		   }
		  int counter = 0;
		  int iByte;
		  while((iByte = istream.read()) != 0x2A)
		  {
			  ch[counter] = (byte)iByte;
			  counter++;
		  }
 
	   }
	   return new String(ch);
   }
 
   public void CloseOpenConnection() 
   {
	   try
	   {
		   if(stream!=null)
		   oustream.close();
		   istream.close();
		   stream.close();
		   stream = null;
	   }
	   catch (Exception e) 
	   {
		   e.printStackTrace();
	   }
   }
 
}
launches/highball/i290.txt · Last modified: 2010/10/07 21:40 by bradluyster
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki