如果找到了对您有用的资料,烦请点击右手边的Google广告支持我继续共享知识,谢谢! http://dengpeng.spaces.live.com/

2009年9月22日星期二

Pachube Java Tutorial

Pachube is a webapp aggragate sensor data around the world. The tutorials given on this site is not well written I think. So, I decide to try it out and blog this simple example. Hope it will be helpfull to you.

Pachube + Java depend Libraries:
1. EEML: http://www.eeml.org/library/eeml.zip
2. Processing: http://processing.org/download/

This is a manual (casual) update example source code. remember to call the setup() before draw():

import eeml.*;
import processing.core.PApplet;

/**
*
* @author pdeng
*/

public class HelloPachube {

DataOut dOut;

void setup() {

PApplet p = new PApplet();
dOut = new DataOut(p, "YOUR_FEED_URL", "YOUR_API_KEY");

// and add and tag a datastream
dOut.addData(0, "temperature");
}

void draw() {
System.out.println("ready to POST: ");
dOut.update(0, 22.5f); // update the datastream
int response = dOut.updatePachube(); // updatePachube() updates by an authenticated PUT HTTP request
System.out.println(response);
}
}

2009年9月15日星期二

Smack API Tutorial

Version: Smack 3.1.0 Beta
Smack is a Java XMPP library. You can create your own GTalk with this.
Digested from: http://www.javaprogrammingforums.com/java-tips-tutorials/551-how-write-simple-xmpp-jabber-client-using-smack-api.html

package jabberhelloworld;

import java.util.*;
import java.io.*;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class Main implements MessageListener {

XMPPConnection connection;

public void login(String userName, String password) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org", 5222, "jabber.org");
connection = new XMPPConnection(config);

connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login(userName, password);
}

public void sendMessage(String message, String to) throws XMPPException {
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
}

public void displayBuddyList() {
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();

System.out.println("\n\n" + entries.size() + " buddy(ies):");
for (RosterEntry r : entries) {
System.out.println(r.getUser());
}
}

public void disconnect() {
connection.disconnect();
}

public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat) {
System.out.println(chat.getParticipant() + " says: " + message.getBody());
try {
chat.sendMessage(message.getBody() + " echo");
} catch (XMPPException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

public static void main(String args[]) throws XMPPException, IOException {
// declare variables
Main c = new Main();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg;


// turn on the enhanced debugger
XMPPConnection.DEBUG_ENABLED = true;


// Enter your login information here
c.login("yourusername", "yourpassword");

c.displayBuddyList();

System.out.println("-----");

System.out.println("Who do you want to talk to? - Type contacts full email address:");
String talkTo = br.readLine();

System.out.println("-----");
System.out.println("All messages will be sent to " + talkTo);
System.out.println("Enter your message in the console:");
System.out.println("-----\n");

while (!(msg = br.readLine()).equals("bye")) {
c.sendMessage(msg, talkTo);
}

c.disconnect();
System.exit(0);
}
}

Sun SPOT offline sensing client

To monitor an activity, sometimes base station is not in communication range. SPOT should be able to store data in its internal memory. When the base station is avaliable, it could send data back to PC.
this is how it works:
1. start SPOT
2. before your activity, click left button on SPOT,and it is recording
3. click left button again to pause recording
4. take it back, click right button on SPOT to send recoreded back to base station

SPOT Side:

/*
* StartApplication.java
*
* Created on Sep 15, 2009 4:32:39 PM;
*/

package org.sunspotworld;

import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.peripheral.ISwitch;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.io.j2me.radiostream.*;
import com.sun.spot.peripheral.NoRouteException;
import com.sun.spot.sensorboard.peripheral.IAccelerometer3D;
import com.sun.spot.sensorboard.peripheral.ILightSensor;
import com.sun.spot.sensorboard.peripheral.ISwitchListener;
import com.sun.spot.sensorboard.peripheral.ITemperatureInput;
import com.sun.spot.util.*;

import java.io.*;
import java.util.Date;
import javax.microedition.io.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
* The startApp method of this class is called by the VM to start the
* application.
*
* The manifest specifies this class as MIDlet-1, which means it will
* be selected for execution.
*/

public class StartApplication extends MIDlet implements ISwitchListener {

private ITriColorLED[] leds = EDemoBoard.getInstance().getLEDs();
ISwitch switch0 = EDemoBoard.getInstance().getSwitches()[0];
ISwitch switch1 = EDemoBoard.getInstance().getSwitches()[1];
boolean switch0Status = false;
boolean switch1Status = false;
RecordStore rms;
int recordStoreIndex = 0;
private IAccelerometer3D accel = EDemoBoard.getInstance().getAccelerometer();
private ITemperatureInput tempSensor = EDemoBoard.getInstance().getADCTemperature();
private ILightSensor lightSensor = EDemoBoard.getInstance().getLightSensor();

protected void startApp() throws MIDletStateChangeException {
new BootloaderListener().start(); // monitor the USB (if connected) and recognize commands from host

long ourAddr = RadioFactory.getRadioPolicyManager().getIEEEAddress();
System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));

//add listeners to two switchs
switch0.addISwitchListener(this);
switch1.addISwitchListener(this);

//set the default LED indicator
leds[0].setRGB(100, 100, 0);
leds[0].setOn();

//uncomment this line below would delete all RecordStore
//deleteRecordStore();

while (true) {
//click the left button to start/stop recording
if (switch0Status) {
try {
//create or open RecordStore
rms = RecordStore.openRecordStore("Record", true);
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
//get values from sensors and store
while (switch0Status) {
try {
String msg = String.valueOf(accel.getAccelX()) + "," +
String.valueOf(accel.getAccelY()) + "," +
String.valueOf(accel.getAccelZ()) + "," +
String.valueOf(accel.getTiltX()) + "," +
String.valueOf(accel.getTiltY()) + "," +
String.valueOf(accel.getTiltZ()) + "," +
String.valueOf(tempSensor.getCelsius()) + "," +
String.valueOf(lightSensor.getValue() + "," +
new Date().getTime());
System.out.println(msg);
Utils.sleep(10);
//add value to RecordStore
rms.addRecord(msg.getBytes(), 0, msg.getBytes().length);
} catch (Exception ex) {
ex.printStackTrace();
}
}
try {
//add a spliter for each of activities
rms.addRecord("finish".getBytes(), 0, "finish".getBytes().length);
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}

//click the right button to send data to server
if (switch1Status) {
leds[0].setOff();
//send data
try {
sendout();
} catch (Exception ex) {
ex.printStackTrace();
}
switch1Status = false;
leds[7].setOff();
leds[0].setRGB(100, 100, 0);
leds[0].setOn();
}
}
}

protected void pauseApp() {
// This is not currently called by the Squawk VM
}

/**
* Called if the MIDlet is terminated by the system.
* I.e. if startApp throws any exception other than MIDletStateChangeException,
* if the isolate running the MIDlet is killed with Isolate.exit(), or
* if VM.stopVM() is called.
*
* It is not called if MIDlet.notifyDestroyed() was called.
*
* @param unconditional If true when this method is called, the MIDlet must
* cleanup and release all resources. If false the MIDlet may throw
* MIDletStateChangeException to indicate it does not want to be destroyed
* at this time.
*/

protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
for (int i = 0; i < 8; i++) {
leds[i].setOff();
}
}

public void switchPressed(ISwitch sw) {
}

public void switchReleased(ISwitch sw) {
if (sw == switch0) {
System.out.println("switch 0 released");
if (switch0Status == false) {
switch0Status = true;
leds[0].setRGB(100, 0, 0);
leds[0].setOn();
} else {
switch0Status = false;
leds[0].setRGB(100, 100, 0);
leds[0].setOn();
}
} else if (sw == switch1) {
System.out.println("switch 1 released");
if (switch1Status == false) {
switch1Status = true;
leds[7].setRGB(100, 0, 0);
leds[7].setOn();
} else {
switch1Status = false;
leds[7].setRGB(100, 100, 0);
leds[7].setOn();
}
}
}

private void sendout() throws Exception {
RadiostreamConnection conn =
(RadiostreamConnection) Connector.open("radiostream://0014.4F01.0000.4bfd:100");
DataInputStream dis = conn.openDataInputStream();
DataOutputStream dos = conn.openDataOutputStream();
try {

for (int j = 1; j < rms.getNumRecords(); j++) {
dos.writeUTF(new String(rms.getRecord(j)));
}
dos.flush();
} catch (NoRouteException e) {
System.out.println("No route to 0014.4F01.0000.0006");
} finally {
dis.close();
dos.close();
conn.close();
}
}

private void deleteRecordStore() {
if (RecordStore.listRecordStores().length > 0) {
for (int k = 0; k < RecordStore.listRecordStores().length; k++) {
try {
RecordStore.deleteRecordStore(RecordStore.listRecordStores()[k]);
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
}


Host Side:



/*
* SunSpotHostApplication.java
*
* Created on Sep 15, 2009 4:03:06 PM;
*/

package org.sunspotworld;

import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.io.j2me.radiostream.*;
import com.sun.spot.peripheral.NoRouteException;
import com.sun.spot.util.IEEEAddress;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.microedition.io.*;

/**
* Sample Sun SPOT host application
*/

public class SunSpotHostApplication {

FileWriter fc = null;
PrintWriter pc = null;

/**
* Print out our radio address.
*/

public void run() {
try {
fc = new java.io.FileWriter("C:\\value.dat", true);
} catch (IOException ex) {
ex.printStackTrace();
}
pc = new java.io.PrintWriter(fc);
long ourAddr = RadioFactory.getRadioPolicyManager().getIEEEAddress();
System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));
try {
receive();
} catch (IOException ex) {
Logger.getLogger(SunSpotHostApplication.class.getName()).log(Level.SEVERE, null, ex);
}
}

/**
* Start up the host application.
*
* @param args any command line arguments
*/

public static void main(String[] args) {
SunSpotHostApplication app = new SunSpotHostApplication();
app.run();
}

private void receive() throws IOException {
RadiostreamConnection conn =
(RadiostreamConnection) Connector.open("radiostream://0014.4F01.0000.46e0:100");
DataInputStream dis = conn.openDataInputStream();
DataOutputStream dos = conn.openDataOutputStream();
try {
while (true) {
String question = dis.readUTF();
write2File(question);
}
} catch (NoRouteException e) {
System.out.println("No route to 0014.4F01.0000.0007");
} finally {
dis.close();
dos.close();
conn.close();
pc.close();
try {
fc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

private void write2File(String question) {
pc.println(question);
}
}