如果找到了对您有用的资料,烦请点击右手边的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);
}
}

2009年8月17日星期一

Use NetBeans IDE 6.7 to Combine JAR Files Into a Single JAR File

This article is digested from http://java.sun.com/developer/technicalArticles/java_warehouse/single_jar/

1. Create Mars Rover Viewer project in Samples folder in NetBeans

2. Switch to Files tab, and open build.xml which is ANT script

3. Edit the file, add following text at the bottom of build.xml and before </project> tag

<target name="package-for-store" depends="jar">

<!-- Change the value of this property to be the name of your JAR,
minus the .jar extension. It should not have spaces.
<property name="store.jar.name" value="MyJarName"/>
-->

<property name="store.jar.name" value="MarsRoverViewer"/>

<!-- don't edit below this line -->

<property name="store.dir" value="store"/>
<property name="store.jar" value="${store.dir}/${store.jar.name}.jar"/>

<echo message="Packaging ${application.title} into a single JAR at ${store.jar}"/>

<delete dir="${store.dir}"/>
<mkdir dir="${store.dir}"/>

<jar destfile="${store.dir}/temp_final.jar" filesetmanifest="skip">
<zipgroupfileset dir="dist" includes="*.jar"/>
<zipgroupfileset dir="dist/lib" includes="*.jar"/>

<manifest>
<attribute name="Main-Class" value="${main.class}"/>
</manifest>
</jar>

<zip destfile="${store.jar}">
<zipfileset src="${store.dir}/temp_final.jar"
excludes="META-INF/*.SF, META-INF/*.DSA, META-INF/*.RSA"/>
</zip>

<delete file="${store.dir}/temp_final.jar"/>

</target>



4. Note, this line above



<property name="store.jar.name" value="MarsRoverViewer"/>



The "MarsRoverViewer" is the name of the compiled single jar file you finally get, change it if you want



5. When you done your coding, right click on the build.xml—>Run Target—>Other Targets—>package-for-store



6. a folder called Store should appear in your project folder and the MarsRoverViewer.jar should sit in there



7. double click it and run!



For more detail, please go to http://java.sun.com/developer/technicalArticles/java_warehouse/single_jar/

2009年6月30日星期二

China: 2009 Declaration of the Anonymous Netizens

2009 Declaration of the Anonymous Netizens

To the Internet censors of China,

We are the Anonymous Netizens. We have seen your moves on the Internet. You have deprived your netizens of the freedom of speech. You have come to see technology as your mortal enemy. You have clouded and distorted the truth in collaboration with Party mouthpieces. You have hired commentators to create the “public opinion” you wanted to see. All these are etched into our collective memory. More recently, you forced the installation of Green Dam on the entire population and smothered Google with vicious slander. It is now clear as day: what you want is the complete control and censorship of the Internet. We hereby declare that we, the Anonymous Netizens, are going to launch our attack worldwide on your censorship system starting on July 1st, 2009.

For the freedom of the Internet, for the advancement of Internetization, and for our rights, we are going to acquaint your censorship machine with systematic sabotage and show you just how weak the claws of your censorship really are. We are going to mark you as the First Enemy of the Internet. This is not a single battle; it is but the beginning of a war. Play with your artificial public opinion to your heart's content, for you will soon be submerged in the sea of warring netizens. Your archaic means of propaganda, your epithets borrowed straight from the Cultural Revolution era, your utter ignorance of the Internet itself - these are the tolls of your death bell. You cannot evade us, for we are everywhere. Violence of the state cannot save you - for every one of us that falls, another ten rises. We are familiar with your intrigues. You label some of us as the “vicious few” and dismiss the rest of us as unknowing accomplices; that way you can divide and rule. Go ahead and do that. In fact, we encourage you to do that; the more accustomed you are to viewing your netizens this way, the deeper your self-deception.

You are trying in vain to halt the wheels of history. Even with your technocratic reinforcements, you will not understand the Internet in the foreseeable future. We congratulate you on your adherence to your Cultural-Revolution style conspiracy theories in your dealings with dissent; for we too get nostalgic at times. We toast to your attempts to erect a Great Wall among your netizens, for such epic folly adds spice to any historical narrative. Still, there's something we feel obliged to tell you.

NOBODY wants to topple your regime. We take no interest whatsoever in your archaic view of state power and your stale ideological teachings. You do not understand how your grand narrative dissipated in the face of Internetization. You do not understand why appealing to statism and nationalism no longer works. You cannot break free from your own ignorance of the Internet. Your regime is not our enemy. We are not affiliated in any way with any country or organization, and we are not waging this war on any country or organization, not even on you. YOU are waging this war on yourself. YOU are digging your own grave through corruption and antagonization. We are not interested in you, destined for the sewage of history. You cannot stop the Internetization of the human race. In fact, we won't bat an eyelid even if you decide to sever the transpacific information cables in order to obtain the total control you wanted. The harder you try to roll back history, the more you strain the already taut strings, and the more destructive their final release. You are accelerating your own fall. The sun of tomorrow does not shine on those who are fearing tomorrow itself.

We are the Anonymous Netizens. We are the sum of the world's entire online population. We are coordinated. We are dominant. We are innumerable. For every one of us that falls, another ten joins. We are omnipresent. We are omnipotent. We are unstoppable. We have no weaknesses. We utilize every weakness. We are the humanity under every mask. We are the mirrors of conscience. We are created equal. We are born free. We are an army. We do not forgive. We do not forget.

LIBERTY LEADS THE INTERNET.

WE'RE COMING.

2009年6月2日星期二

I am BACK…

I have not update my tech blog for ages. Sorry, subscribersSmile

I was working on SensorWeb project directed by Dr. Rajkumar Buyya in University of Melbourne. My part of the project is finish. It is an honor to work in this innovative lab.

Here is a introduction of the project:

The SensorWeb project aims at developing Open SensorWeb Architecture (OSWA) and implementing standards compliant platform and middleware for integration of sensor networks with emerging distributed computing platforms such as Grids. It confirms to Web Services standard defined by the W3C (World-Wide Web) and SensorML (Sensor Model Language) standard defined by the OpenGeospatial Consortium. This integration of sensor networks with Grid computing brings out dual benefits:
(i) sensor networks can off-load heavy processing activities to the Grid and
(ii) Grid-based sensor applications can provide advance services for smart-sensing by deploying scenario-specific operators at runtime.

Our Open SensorWeb Architecture consists of four layers: sensor fabric layer, core services, user-level services, and applications. Core services are provided by lower-level layer components whereas components at the user-level layer provide tools for creation of applications and management of life-cycle of data captured through sensor networks. The project primarily aims to develop (a) an interactive development environment, (b) an open and standards-compliant SensorWeb application services middleware, and (c) a coordination language to support the development of sensor applications in various domains including water observation networks, safe road transportation management systems, and Tsunami detection network for the early warning systems. The OSWA-based platform provides a number of sensor and actuation services, such as:
* sensor notification, collection and observation,
* data collection, aggregation and archiving,
* sensor coordination and data processing,
* faulty sensor data correction & management, and
* sensor configuration and directory services.

Now, I am re-focusing on Sun SPOT. This blog focuses on explore and study the fundemental knowledge, skill, experience and idea of not only Sun SPOT but all WSN.

2009年2月24日星期二

SunSPOT BroadcastSample Code

/*
* Copyright (c) 2007 Sun Microsystems, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**/


package org.sunspotworld.demo;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.microedition.midlet.MIDletStateChangeException;

import com.sun.spot.io.j2me.radiogram.RadiogramConnection;

import com.sun.spot.util.Utils;

/**
* @author: David Mercier <david.mercier@sun.com>
*
* This simple demo shows you how to use the radio to broadcast
* some data to any listening SPOT(s).
*
* There is one thread (startSenderThread) that sends data on a particular
* channel.
* There is a second thread (startReceiverThread) that receives
* data on that same channel.
*
*/

public class BroadcastSample extends javax.microedition.midlet.MIDlet {

protected void startApp() throws MIDletStateChangeException {

System.out.println("I'm about to rock that SPOT !");

startSenderThread();
startReceiverThread();
}

/**
* The receiver thread blocks on the receive function
* so you don't have to sleep between each receive.
*/

public void startReceiverThread() {
new Thread() {
public void run() {
String tmp = null;
RadiogramConnection dgConnection = null;
Datagram dg = null;

try {
dgConnection = (RadiogramConnection) Connector.open("radiogram://:37");
// Then, we ask for a datagram with the maximum size allowed
dg = dgConnection.newDatagram(dgConnection.getMaximumLength());
} catch (IOException e) {
System.out.println("Could not open radiogram receiver connection");
e.printStackTrace();
return;
}

while(true){
try {
dg.reset();
dgConnection.receive(dg);
tmp = dg.readUTF();
System.out.println("Received: " + tmp + " from " + dg.getAddress());
} catch (IOException e) {
System.out.println("Nothing received");
}
}
}
}.start();
}

/**
* The sender thread sends a string each 500 ms
*/

synchronized public void startSenderThread() {
new Thread() {
public void run() {
// We create a DatagramConnection
DatagramConnection dgConnection = null;
Datagram dg = null;
try {
// The Connection is a broadcast so we specify it in the creation string
dgConnection = (DatagramConnection) Connector.open("radiogram://broadcast:37");
// Then, we ask for a datagram with the maximum size allowed
dg = dgConnection.newDatagram(dgConnection.getMaximumLength());
} catch (IOException ex) {
System.out.println("Could not open radiogram broadcast connection");
ex.printStackTrace();
return;
}

while(true){
try {
// We send the message (UTF encoded)
dg.reset();
dg.writeUTF("I rock");
dgConnection.send(dg);
System.out.println("Broadcast is going through");
} catch (IOException ex) {
ex.printStackTrace();
}
Utils.sleep(500);
}
}
}.start();
}

protected void pauseApp() {
}

/**
* 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 {
}

}