code
stringlengths
3
1.18M
language
stringclasses
1 value
/** Automatically generated file. DO NOT MODIFY */ package home.remote.control; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package home.remote.control.util; import android.app.Activity; import android.os.Build; import android.view.View; /** * A utility class that helps with showing and hiding system UI such as the * status bar and navigation/system bar. This class uses backward-compatibility * techniques described in <a href= * "http://developer.android.com/training/backward-compatible-ui/index.html"> * Creating Backward-Compatible UIs</a> to ensure that devices running any * version of ndroid OS are supported. More specifically, there are separate * implementations of this abstract class: for newer devices, * {@link #getInstance} will return a {@link SystemUiHiderHoneycomb} instance, * while on older devices {@link #getInstance} will return a * {@link SystemUiHiderBase} instance. * <p> * For more on system bars, see <a href= * "http://developer.android.com/design/get-started/ui-overview.html#system-bars" * > System Bars</a>. * * @see android.view.View#setSystemUiVisibility(int) * @see android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN */ public abstract class SystemUiHider { /** * When this flag is set, the * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN} * flag will be set on older devices, making the status bar "float" on top * of the activity layout. This is most useful when there are no controls at * the top of the activity layout. * <p> * This flag isn't used on newer devices because the <a * href="http://developer.android.com/design/patterns/actionbar.html">action * bar</a>, the most important structural element of an Android app, should * be visible and not obscured by the system UI. */ public static final int FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES = 0x1; /** * When this flag is set, {@link #show()} and {@link #hide()} will toggle * the visibility of the status bar. If there is a navigation bar, show and * hide will toggle low profile mode. */ public static final int FLAG_FULLSCREEN = 0x2; /** * When this flag is set, {@link #show()} and {@link #hide()} will toggle * the visibility of the navigation bar, if it's present on the device and * the device allows hiding it. In cases where the navigation bar is present * but cannot be hidden, show and hide will toggle low profile mode. */ public static final int FLAG_HIDE_NAVIGATION = FLAG_FULLSCREEN | 0x4; /** * The activity associated with this UI hider object. */ protected Activity mActivity; /** * The view on which {@link View#setSystemUiVisibility(int)} will be called. */ protected View mAnchorView; /** * The current UI hider flags. * * @see #FLAG_FULLSCREEN * @see #FLAG_HIDE_NAVIGATION * @see #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES */ protected int mFlags; /** * The current visibility callback. */ protected OnVisibilityChangeListener mOnVisibilityChangeListener = sDummyListener; /** * Creates and returns an instance of {@link SystemUiHider} that is * appropriate for this device. The object will be either a * {@link SystemUiHiderBase} or {@link SystemUiHiderHoneycomb} depending on * the device. * * @param activity * The activity whose window's system UI should be controlled by * this class. * @param anchorView * The view on which {@link View#setSystemUiVisibility(int)} will * be called. * @param flags * Either 0 or any combination of {@link #FLAG_FULLSCREEN}, * {@link #FLAG_HIDE_NAVIGATION}, and * {@link #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES}. */ public static SystemUiHider getInstance(Activity activity, View anchorView, int flags) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return new SystemUiHiderHoneycomb(activity, anchorView, flags); } else { return new SystemUiHiderBase(activity, anchorView, flags); } } protected SystemUiHider(Activity activity, View anchorView, int flags) { mActivity = activity; mAnchorView = anchorView; mFlags = flags; } /** * Sets up the system UI hider. Should be called from * {@link Activity#onCreate}. */ public abstract void setup(); /** * Returns whether or not the system UI is visible. */ public abstract boolean isVisible(); /** * Hide the system UI. */ public abstract void hide(); /** * Show the system UI. */ public abstract void show(); /** * Toggle the visibility of the system UI. */ public void toggle() { if (isVisible()) { hide(); } else { show(); } } /** * Registers a callback, to be triggered when the system UI visibility * changes. */ public void setOnVisibilityChangeListener( OnVisibilityChangeListener listener) { if (listener == null) { listener = sDummyListener; } mOnVisibilityChangeListener = listener; } /** * A dummy no-op callback for use when there is no other listener set. */ private static OnVisibilityChangeListener sDummyListener = new OnVisibilityChangeListener() { @Override public void onVisibilityChange(boolean visible) { } }; /** * A callback interface used to listen for system UI visibility changes. */ public interface OnVisibilityChangeListener { /** * Called when the system UI visibility has changed. * * @param visible * True if the system UI is visible. */ public void onVisibilityChange(boolean visible); } }
Java
package home.remote.control.util; import android.app.Activity; import android.view.View; import android.view.WindowManager; /** * A base implementation of {@link SystemUiHider}. Uses APIs available in all * API levels to show and hide the status bar. */ public class SystemUiHiderBase extends SystemUiHider { /** * Whether or not the system UI is currently visible. This is a cached value * from calls to {@link #hide()} and {@link #show()}. */ private boolean mVisible = true; /** * Constructor not intended to be called by clients. Use * {@link SystemUiHider#getInstance} to obtain an instance. */ protected SystemUiHiderBase(Activity activity, View anchorView, int flags) { super(activity, anchorView, flags); } @Override public void setup() { if ((mFlags & FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES) == 0) { mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } } @Override public boolean isVisible() { return mVisible; } @Override public void hide() { if ((mFlags & FLAG_FULLSCREEN) != 0) { mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } mOnVisibilityChangeListener.onVisibilityChange(false); mVisible = false; } @Override public void show() { if ((mFlags & FLAG_FULLSCREEN) != 0) { mActivity.getWindow().setFlags(0, WindowManager.LayoutParams.FLAG_FULLSCREEN); } mOnVisibilityChangeListener.onVisibilityChange(true); mVisible = true; } }
Java
package home.remote.control.util; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.view.View; import android.view.WindowManager; /** * An API 11+ implementation of {@link SystemUiHider}. Uses APIs available in * Honeycomb and later (specifically {@link View#setSystemUiVisibility(int)}) to * show and hide the system UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SystemUiHiderHoneycomb extends SystemUiHiderBase { /** * Flags for {@link View#setSystemUiVisibility(int)} to use when showing the * system UI. */ private int mShowFlags; /** * Flags for {@link View#setSystemUiVisibility(int)} to use when hiding the * system UI. */ private int mHideFlags; /** * Flags to test against the first parameter in * {@link android.view.View.OnSystemUiVisibilityChangeListener#onSystemUiVisibilityChange(int)} * to determine the system UI visibility state. */ private int mTestFlags; /** * Whether or not the system UI is currently visible. This is cached from * {@link android.view.View.OnSystemUiVisibilityChangeListener}. */ private boolean mVisible = true; /** * Constructor not intended to be called by clients. Use * {@link SystemUiHider#getInstance} to obtain an instance. */ protected SystemUiHiderHoneycomb(Activity activity, View anchorView, int flags) { super(activity, anchorView, flags); mShowFlags = View.SYSTEM_UI_FLAG_VISIBLE; mHideFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE; mTestFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE; if ((mFlags & FLAG_FULLSCREEN) != 0) { // If the client requested fullscreen, add flags relevant to hiding // the status bar. Note that some of these constants are new as of // API 16 (Jelly Bean). It is safe to use them, as they are inlined // at compile-time and do nothing on pre-Jelly Bean devices. mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN; } if ((mFlags & FLAG_HIDE_NAVIGATION) != 0) { // If the client requested hiding navigation, add relevant flags. mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; mTestFlags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; } } /** {@inheritDoc} */ @Override public void setup() { mAnchorView .setOnSystemUiVisibilityChangeListener(mSystemUiVisibilityChangeListener); } /** {@inheritDoc} */ @Override public void hide() { mAnchorView.setSystemUiVisibility(mHideFlags); } /** {@inheritDoc} */ @Override public void show() { mAnchorView.setSystemUiVisibility(mShowFlags); } /** {@inheritDoc} */ @Override public boolean isVisible() { return mVisible; } private View.OnSystemUiVisibilityChangeListener mSystemUiVisibilityChangeListener = new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int vis) { // Test against mTestFlags to see if the system UI is visible. if ((vis & mTestFlags) != 0) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { // Pre-Jelly Bean, we must manually hide the action bar // and use the old window flags API. mActivity.getActionBar().hide(); mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } // Trigger the registered listener and cache the visibility // state. mOnVisibilityChangeListener.onVisibilityChange(false); mVisible = false; } else { mAnchorView.setSystemUiVisibility(mShowFlags); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { // Pre-Jelly Bean, we must manually show the action bar // and use the old window flags API. mActivity.getActionBar().show(); mActivity.getWindow().setFlags(0, WindowManager.LayoutParams.FLAG_FULLSCREEN); } // Trigger the registered listener and cache the visibility // state. mOnVisibilityChangeListener.onVisibilityChange(true); mVisible = true; } } }; }
Java
package home.remote.control; import home.remote.control.util.SystemUiHider; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class RemoteControlActivity extends Activity { private RemoteControlActivity instance = this; /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * If set, will toggle the system UI visibility upon interaction. Otherwise, * will show the system UI visibility upon interaction. */ private static final boolean TOGGLE_ON_CLICK = true; /** * The flags to pass to {@link SystemUiHider#getInstance}. */ private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION; /** * The instance of the {@link SystemUiHider} for this activity. */ private SystemUiHider mSystemUiHider; private Button buttonOn = null; private Button buttonOff = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_remote_control); final View controlsView = findViewById(R.id.fullscreen_content_controls); final View contentView = findViewById(R.id.fullscreen_content); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() { // Cached values. int mControlsHeight; int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { // If the ViewPropertyAnimator API is available // (Honeycomb MR2 and later), use it to animate the // in-layout UI controls at the bottom of the // screen. if (mControlsHeight == 0) { mControlsHeight = controlsView.getHeight(); } if (mShortAnimTime == 0) { mShortAnimTime = getResources().getInteger( android.R.integer.config_shortAnimTime); } controlsView .animate() .translationY(visible ? 0 : mControlsHeight) .setDuration(mShortAnimTime); } else { // If the ViewPropertyAnimator APIs aren't // available, simply show or hide the in-layout UI // controls. controlsView.setVisibility(visible ? View.VISIBLE : View.GONE); } if (visible && AUTO_HIDE) { // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); } } }); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (TOGGLE_ON_CLICK) { mSystemUiHider.toggle(); } else { mSystemUiHider.show(); } } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. findViewById(R.id.button_on).setOnTouchListener(mDelayHideTouchListener); buttonOn = (Button)findViewById(R.id.button_on); buttonOff = (Button)findViewById(R.id.button_off); buttonOn.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { sendEmailMessage("{ 'operation':'turn-relay-on' }"); } catch (Exception ex) { Toast.makeText(instance.getApplicationContext(), "Error:\n" + ex.toString(), Toast.LENGTH_LONG).show(); } } }); buttonOff.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { sendEmailMessage("{ 'operation':'turn-relay-off' }"); } catch (Exception ex) { Toast.makeText(instance.getApplicationContext(), "Error:\n" + ex.toString(), Toast.LENGTH_LONG).show(); } } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; } }; Handler mHideHandler = new Handler(); Runnable mHideRunnable = new Runnable() { @Override public void run() { mSystemUiHider.hide(); } }; /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } private void sendEmailMessage(String message) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("message/rfc822"); i.putExtra(Intent.EXTRA_EMAIL , new String[]{"olivier.lediouris@gmail.com"}); i.putExtra(Intent.EXTRA_SUBJECT, "PI Request"); i.putExtra(Intent.EXTRA_TEXT , message); try { startActivity(Intent.createChooser(i, "Send mail...")); // Toast.makeText(RemoteControlActivity.this, "Message has been sent.", Toast.LENGTH_SHORT).show(); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(RemoteControlActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show(); } } }
Java
package rangesensor; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import java.text.DecimalFormat; import java.text.Format; /** * @see https://www.modmypi.com/blog/hc-sr04-ultrasonic-range-sensor-on-the-raspberry-pi * * This version is multi-threaded. * This allows the management of a signal that does not come back. */ public class HC_SR04andLeds { private final static Format DF22 = new DecimalFormat("#0.00"); private final static double SOUND_SPEED = 34300; // in cm, 343 m/s private final static double DIST_FACT = SOUND_SPEED / 2; // round trip private final static int MIN_DIST = 5; private final static long BETWEEN_LOOPS = 500L; private final static long MAX_WAIT = 500L; private final static boolean DEBUG = false; public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - Range Sensor HC-SR04."); System.out.println("Will stop is distance is smaller than " + MIN_DIST + " cm"); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalOutput trigPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "Trig", PinState.LOW); final GpioPinDigitalInput echoPin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_05, "Echo"); final GpioPinDigitalOutput ledOne = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "One", PinState.LOW); final GpioPinDigitalOutput ledTwo = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "Two", PinState.LOW); final GpioPinDigitalOutput ledThree = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "Three", PinState.LOW); final GpioPinDigitalOutput ledFour = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03, "Four", PinState.LOW); final GpioPinDigitalOutput ledFive = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_06, "Five", PinState.LOW); final GpioPinDigitalOutput[] ledArray = new GpioPinDigitalOutput[] { ledOne, ledTwo, ledThree, ledFour, ledFive }; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Oops!"); for (int i=0; i<ledArray.length; i++) ledArray[i].low(); gpio.shutdown(); System.out.println("Exiting nicely."); } }); System.out.println("Waiting for the sensor to be ready (2s)..."); Thread.sleep(2000L); Thread mainThread = Thread.currentThread(); boolean go = true; System.out.println("Looping until the distance is less than " + MIN_DIST + " cm"); while (go) { boolean ok = true; double start = 0d, end = 0d; if (DEBUG) System.out.println("Triggering module."); TriggerThread trigger = new TriggerThread(mainThread, trigPin, echoPin); trigger.start(); try { synchronized (mainThread) { long before = System.currentTimeMillis(); mainThread.wait(MAX_WAIT); long after = System.currentTimeMillis(); long diff = after - before; if (DEBUG) System.out.println("MainThread done waiting (" + Long.toString(diff) + " ms)"); if (diff >= MAX_WAIT) { ok = false; if (true || DEBUG) System.out.println("...Reseting."); if (trigger.isAlive()) trigger.interrupt(); } } } catch (Exception ex) { ex.printStackTrace(); ok = false; } if (ok) { start = trigger.getStart(); end = trigger.getEnd(); if (DEBUG) System.out.println("Measuring..."); if (end > 0 && start > 0) { double pulseDuration = (end - start) / 1000000000d; // in seconds double distance = pulseDuration * DIST_FACT; if (distance < 1000) // Less than 10 meters System.out.println("Distance: " + DF22.format(distance) + " cm."); // + " (" + pulseDuration + " = " + end + " - " + start + ")"); if (distance > 0 && distance < MIN_DIST) go = false; else { if (distance < 0) System.out.println("Dist:" + distance + ", start:" + start + ", end:" + end); for (int i=0; i<ledArray.length; i++) { if (distance < ((i+1) * 10)) { ledArray[i].high(); } else ledArray[i].low(); } try { Thread.sleep(BETWEEN_LOOPS); } catch (Exception ex) {} } } else { System.out.println("Hiccup!"); // try { Thread.sleep(2000L); } catch (Exception ex) {} } } } System.out.println("Done."); for (int i=0; i<ledArray.length; i++) ledArray[i].low(); trigPin.low(); // Off gpio.shutdown(); System.exit(0); } private static class TriggerThread extends Thread { private GpioPinDigitalOutput trigPin = null; private GpioPinDigitalInput echoPin = null; private Thread caller = null; private double start = 0D, end = 0D; public TriggerThread(Thread parent, GpioPinDigitalOutput trigger, GpioPinDigitalInput echo) { this.trigPin = trigger; this.echoPin = echo; this.caller = parent; } public void run() { trigPin.high(); // 10 microsec (10000 ns) to trigger the module (8 ultrasound bursts at 40 kHz) // https://www.dropbox.com/s/615w1321sg9epjj/hc-sr04-ultrasound-timing-diagram.png try { Thread.sleep(0, 10000); } catch (Exception ex) { ex.printStackTrace(); } trigPin.low(); // Wait for the signal to return while (echoPin.isLow()) start = System.nanoTime(); // There it is while (echoPin.isHigh()) end = System.nanoTime(); synchronized (caller) { caller.notify(); } } public double getStart() { return start; } public double getEnd() { return end; } } }
Java
package rangesensor; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import java.text.DecimalFormat; import java.text.Format; /** * @see https://www.modmypi.com/blog/hc-sr04-ultrasonic-range-sensor-on-the-raspberry-pi * */ public class HC_SR04 { private final static Format DF22 = new DecimalFormat("#0.00"); private final static double SOUND_SPEED = 34300; // in cm, 343 m/s private final static double DIST_FACT = SOUND_SPEED / 2; // round trip private final static int MIN_DIST = 5; public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - Range Sensor HC-SR04."); System.out.println("Will stop is distance is smaller than " + MIN_DIST + " cm"); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalOutput trigPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "Trig", PinState.LOW); final GpioPinDigitalInput echoPin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_05, "Echo"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Oops!"); gpio.shutdown(); System.out.println("Exiting nicely."); } }); System.out.println("Waiting for the sensor to be ready (2s)..."); Thread.sleep(2000); boolean go = true; System.out.println("Looping until the distance is less than " + MIN_DIST + " cm"); while (go) { double start = 0d, end = 0d; trigPin.high(); // 10 microsec to trigger the module (8 ultrasound bursts at 40 kHz) // https://www.dropbox.com/s/615w1321sg9epjj/hc-sr04-ultrasound-timing-diagram.png try { Thread.sleep(0, 10000); } catch (Exception ex) { ex.printStackTrace(); } trigPin.low(); // Wait for the signal to return while (echoPin.isLow()) start = System.nanoTime(); // There it is while (echoPin.isHigh()) end = System.nanoTime(); if (end > 0 && start > 0) { double pulseDuration = (end - start) / 1000000000d; // in seconds double distance = pulseDuration * DIST_FACT; if (distance < 1000) // Less than 10 meters System.out.println("Distance: " + DF22.format(distance) + " cm."); // + " (" + pulseDuration + " = " + end + " - " + start + ")"); if (distance > 0 && distance < MIN_DIST) go = false; else { if (distance < 0) System.out.println("Dist:" + distance + ", start:" + start + ", end:" + end); try { Thread.sleep(1000L); } catch (Exception ex) {} } } else { System.out.println("Hiccup!"); try { Thread.sleep(2000L); } catch (Exception ex) {} } } System.out.println("Done."); System. trigPin.low(); // Off gpio.shutdown(); } }
Java
package readserialport; import com.pi4j.io.serial.Serial; import com.pi4j.io.serial.SerialDataEvent; import com.pi4j.io.serial.SerialDataListener; import com.pi4j.io.serial.SerialFactory; /** * Just reads the GPS data. * No parsing, just raw data. */ public class GPSDataReader { public static void main(String args[]) throws InterruptedException, NumberFormatException { int br = Integer.parseInt(System.getProperty("baud.rate", "9600")); String port = System.getProperty("port.name", Serial.DEFAULT_COM_PORT); if (args.length > 0) { try { br = Integer.parseInt(args[0]); } catch (Exception ex) { System.err.println(ex.getMessage()); } } System.out.println("Serial Communication."); System.out.println(" ... connect using settings: " + Integer.toString(br) + ", N, 8, 1."); System.out.println(" ... data received on serial port should be displayed below."); // create an instance of the serial communications class final Serial serial = SerialFactory.createInstance(); // create and register the serial data listener serial.addListener(new SerialDataListener() { @Override public void dataReceived(SerialDataEvent event) { // print out the data received to the console String data = event.getData(); System.out.println("Got Data (" + data.length() + " byte(s))"); if (data.startsWith("$")) System.out.println(data); else { String hexString = ""; char[] ca = data.toCharArray(); for (int i=0; i<ca.length; i++) hexString += (lpad(Integer.toHexString(ca[i]), "0", 2) + " "); System.out.println(hexString); } } }); final Thread t = Thread.currentThread(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("\nShutting down..."); try { if (serial.isOpen()) { serial.close(); System.out.println("Serial port closed"); } synchronized (t) { t.notify(); System.out.println("Thread notified"); } } catch (Exception ex) { ex.printStackTrace(); } } }); try { System.out.println("Opening port [" + port + "]"); boolean open = false; while (!open) { serial.open(port, br); open = serial.isOpen(); System.out.println("Port is " + (open ? "" : "NOT ") + "opened."); if (!open) try { Thread.sleep(500L); } catch (Exception ex) {} } synchronized (t) { t.wait(); } System.out.println("Bye..."); } catch (InterruptedException ie) { ie.printStackTrace(); } } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
Java
package nmea; import calculation.AstroComputer; import calculation.SightReductionUtil; import java.text.DecimalFormat; import java.util.Calendar; import java.util.TimeZone; import ocss.nmea.api.NMEAClient; import ocss.nmea.api.NMEAEvent; import ocss.nmea.api.NMEAListener; import ocss.nmea.parser.GeoPos; import ocss.nmea.parser.RMC; import ocss.nmea.parser.StringParsers; /** * Reads the GPS Data, parse the RMC String * Display astronomical data */ public class CustomNMEAReader extends NMEAClient { private final static DecimalFormat DFH = new DecimalFormat("#0.00'\272'"); private final static DecimalFormat DFZ = new DecimalFormat("##0.00'\272'"); private static GeoPos prevPosition = null; private static long prevDateTime = -1L; public CustomNMEAReader() { super(); } @Override public void dataDetectedEvent(NMEAEvent e) { // System.out.println("Received:" + e.getContent()); manageData(e.getContent().trim()); } private static CustomNMEAReader customClient = null; private static void manageData(String sentence) { boolean valid = StringParsers.validCheckSum(sentence); if (valid) { String id = sentence.substring(3, 6); if ("RMC".equals(id)) { System.out.println(sentence); RMC rmc = StringParsers.parseRMC(sentence); // System.out.println(rmc.toString()); if (rmc != null && rmc.getRmcDate() != null && rmc.getGp() != null) { if ((prevDateTime == -1L || prevPosition == null) || (prevDateTime != (rmc.getRmcDate().getTime() / 1000) || !rmc.getGp().equals(prevPosition))) { Calendar current = Calendar.getInstance(TimeZone.getTimeZone("etc/UTC")); current.setTime(rmc.getRmcDate()); AstroComputer.setDateTime(current.get(Calendar.YEAR), current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH), current.get(Calendar.HOUR_OF_DAY), current.get(Calendar.MINUTE), current.get(Calendar.SECOND)); AstroComputer.calculate(); SightReductionUtil sru = new SightReductionUtil(AstroComputer.getSunGHA(), AstroComputer.getSunDecl(), rmc.getGp().lat, rmc.getGp().lng); sru.calculate(); Double he = sru.getHe(); Double z = sru.getZ(); System.out.println(current.getTime().toString() + ", He:" + DFH.format(he)+ ", Z:" + DFZ.format(z) + " (" + rmc.getGp().toString() + ")"); } prevPosition = rmc.getGp(); prevDateTime = (rmc.getRmcDate().getTime() / 1000); } else { if (rmc == null) System.out.println("... no RMC data in [" + sentence + "]"); else { String errMess = ""; if (rmc.getRmcDate() == null) errMess += ("no Date "); if (rmc.getGp() == null) errMess += ("no Pos "); System.out.println(errMess + "in [" + sentence + "]"); } } } else System.out.println("Read [" + sentence + "]"); } else System.out.println("Invalid data [" + sentence + "]"); } public static void main(String[] args) { System.setProperty("deltaT", System.getProperty("deltaT", "67.2810")); // 2014-Jan-01 int br = 9600; System.out.println("CustomNMEAReader invoked with " + args.length + " Parameter(s)."); for (String s : args) { System.out.println("CustomNMEAReader prm:" + s); try { br = Integer.parseInt(s); } catch (NumberFormatException nfe) {} } customClient = new CustomNMEAReader(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println ("\nShutting down nicely."); customClient.stopDataRead(); } }); customClient.initClient(); customClient.setReader(new CustomNMEASerialReader(customClient.getListeners(), br)); customClient.startWorking(); // Feignasse! } private void stopDataRead() { if (customClient != null) { for (NMEAListener l : customClient.getListeners()) l.stopReading(new NMEAEvent(this)); } } }
Java
package nmea; import com.pi4j.io.serial.Serial; import com.pi4j.io.serial.SerialDataEvent; import com.pi4j.io.serial.SerialDataListener; import com.pi4j.io.serial.SerialFactory; import java.util.List; import ocss.nmea.api.NMEAEvent; import ocss.nmea.api.NMEAListener; import ocss.nmea.api.NMEAReader; public class CustomNMEASerialReader extends NMEAReader { private int baudRate = 4800; private CustomNMEASerialReader instance = this; public CustomNMEASerialReader(List<NMEAListener> al, int br) { super(al); baudRate = br; } @Override public void read() { if (System.getProperty("verbose", "false").equals("true")) System.out.println("From " + this.getClass().getName() + " Reading Serial Port."); super.enableReading(); // Opening Serial port try { final Serial serial = SerialFactory.createInstance(); // create and register the serial data listener serial.addListener(new SerialDataListener() { @Override public void dataReceived(SerialDataEvent event) { // System.out.print(/*"Read:\n" + */ event.getData()); instance.fireDataRead(new NMEAEvent(this, event.getData())); } }); String port = System.getProperty("port.name", Serial.DEFAULT_COM_PORT); if (System.getProperty("verbose", "false").equals("true")) System.out.println("Opening port [" + port + "]"); serial.open(port, baudRate); // Reading on Serial Port if (System.getProperty("verbose", "false").equals("true")) System.out.println("Port is " + (serial.isOpen() ? "" : "NOT ") + "open."); } catch (Exception ex) { ex.printStackTrace(); } } }
Java
package nmea; import calculation.AstroComputer; import calculation.SightReductionUtil; import java.text.DecimalFormat; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import ocss.nmea.api.NMEAClient; import ocss.nmea.api.NMEAEvent; import ocss.nmea.api.NMEAListener; import ocss.nmea.parser.GeoPos; import ocss.nmea.parser.RMC; import ocss.nmea.parser.StringParsers; import ocss.nmea.parser.UTC; /** * Reads the GPS Data, parse the GGA String */ public class CustomGGAReader extends NMEAClient { public CustomGGAReader() { super(); } @Override public void dataDetectedEvent(NMEAEvent e) { // System.out.println("Received:" + e.getContent()); manageData(e.getContent().trim()); } private static CustomGGAReader customClient = null; private static void manageData(String sentence) { boolean valid = StringParsers.validCheckSum(sentence); if (valid) { String id = sentence.substring(3, 6); if ("GGA".equals(id)) { System.out.println(sentence); List<Object> al = StringParsers.parseGGA(sentence); UTC utc = (UTC)al.get(0); GeoPos pos = (GeoPos)al.get(1); Integer nbs = (Integer)al.get(2); Double alt = (Double)al.get(3); System.out.println("\tUTC:" + utc.toString() + "\tPos:" + pos.toString()); System.out.println("\t" + nbs.intValue() + " Satellite(s) in use"); System.out.println("\tAltitude:" + alt); System.out.println("------------------"); } // else // System.out.println("Read [" + sentence + "]"); } else System.out.println("Invalid data [" + sentence + "]"); } public static void main(String[] args) { int br = 9600; System.out.println("CustomNMEAReader invoked with " + args.length + " Parameter(s)."); for (String s : args) { System.out.println("CustomGGAReader prm:" + s); try { br = Integer.parseInt(s); } catch (NumberFormatException nfe) {} } customClient = new CustomGGAReader(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println ("\nShutting down nicely."); customClient.stopDataRead(); } }); customClient.initClient(); customClient.setReader(new CustomNMEASerialReader(customClient.getListeners(), br)); customClient.startWorking(); // Feignasse! } private void stopDataRead() { if (customClient != null) { for (NMEAListener l : customClient.getListeners()) l.stopReading(new NMEAEvent(this)); } } }
Java
package nmea; import calculation.AstroComputer; import calculation.SightReductionUtil; import java.io.BufferedReader; import java.io.FileReader; import java.text.DecimalFormat; import java.util.Calendar; import java.util.TimeZone; import ocss.nmea.parser.GeoPos; import ocss.nmea.parser.RMC; import ocss.nmea.parser.StringParsers; /** * Parse the RMC string from a log file. * No serial port involved */ public class WithFakedData { private final static DecimalFormat DFH = new DecimalFormat("#0.00'\272'"); private final static DecimalFormat DFZ = new DecimalFormat("#0.00'\272'"); private static GeoPos prevPosition = null; private static long prevDateTime = -1L; /* * deltaT, system variable. * See http://maia.usno.navy.mil/ser7/deltat.data */ public static void main(String[] args) throws Exception { System.setProperty("deltaT", "67.2810"); // 2014-Jan-01 BufferedReader br = new BufferedReader(new FileReader("raspPiLog.nmea")); String line = ""; boolean go = true; long nbRec = 0L, nbDisplay = 0L; while (go) { line = br.readLine(); if (line == null) go = false; else { nbRec++; boolean valid = StringParsers.validCheckSum(line); if (valid) { String id = line.substring(3, 6); if ("RMC".equals(id)) { // System.out.println(line); RMC rmc = StringParsers.parseRMC(line); // System.out.println(rmc.toString()); if (rmc.getRmcDate() != null && rmc.getGp() != null) { if ((prevDateTime == -1L || prevPosition == null) || (prevDateTime != (rmc.getRmcDate().getTime() / 1000) || !rmc.getGp().equals(prevPosition))) { nbDisplay++; Calendar current = Calendar.getInstance(TimeZone.getTimeZone("etc/UTC")); current.setTime(rmc.getRmcDate()); AstroComputer.setDateTime(current.get(Calendar.YEAR), current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH), current.get(Calendar.HOUR_OF_DAY), // 12 - (int)Math.round(AstroComputer.getTimeZoneOffsetInHours(TimeZone.getTimeZone(ts.getTimeZone()))), current.get(Calendar.MINUTE), current.get(Calendar.SECOND)); AstroComputer.calculate(); SightReductionUtil sru = new SightReductionUtil(AstroComputer.getSunGHA(), AstroComputer.getSunDecl(), rmc.getGp().lat, rmc.getGp().lng); sru.calculate(); Double he = sru.getHe(); Double z = sru.getZ(); System.out.println(current.getTime().toString() + ", He:" + DFH.format(he)+ ", Z:" + DFZ.format(z)); } prevPosition = rmc.getGp(); prevDateTime = (rmc.getRmcDate().getTime() / 1000); } } } } } br.close(); System.out.println(nbRec + " record(s)."); System.out.println(nbDisplay + " displayed."); } }
Java
package readserialport; import com.pi4j.io.serial.Serial; import com.pi4j.io.serial.SerialDataEvent; import com.pi4j.io.serial.SerialDataListener; import com.pi4j.io.serial.SerialFactory; import com.pi4j.io.serial.SerialPortException; import java.util.Date; public class SerialReader { public static void main(String args[]) throws InterruptedException, NumberFormatException { int br = Integer.parseInt(System.getProperty("baud.rate", "9600")); if (args.length > 0) { try { br = Integer.parseInt(args[0]); } catch (Exception ex) { System.err.println(ex.getMessage()); } } System.out.println("Serial Communication."); System.out.println(" ... connect using settings: " + Integer.toString(br) + ", N, 8, 1."); System.out.println(" ... data received on serial port should be displayed below."); // create an instance of the serial communications class final Serial serial = SerialFactory.createInstance(); // create and register the serial data listener serial.addListener(new SerialDataListener() { @Override public void dataReceived(SerialDataEvent event) { // print out the data received to the console System.out.print(/*"Read:\n" + */ event.getData()); } }); try { // open the default serial port provided on the GPIO header System.out.println("Opening port [" + Serial.DEFAULT_COM_PORT + ":" + Integer.toString(br) + "]"); serial.open(Serial.DEFAULT_COM_PORT, br); System.out.println("Port is opened."); // continuous loop to keep the program running until the user terminates the program while (true) { if (serial.isOpen()) { System.out.println("Writing to the serial port..."); try { // write a formatted string to the serial transmit buffer serial.write("CURRENT TIME: %s", new Date().toString()); // write a individual bytes to the serial transmit buffer serial.write((byte) 13); serial.write((byte) 10); // write a simple string to the serial transmit buffer serial.write("Second Line"); // write a individual characters to the serial transmit buffer serial.write('\r'); serial.write('\n'); // write a string terminating with CR+LF to the serial transmit buffer serial.writeln("Third Line"); } catch (IllegalStateException ex) { ex.printStackTrace(); } } else { System.out.println("Not open yet..."); } // wait 1 second before continuing Thread.sleep(1000); } } catch (SerialPortException ex) { System.out.println(" ==>> SERIAL SETUP FAILED : " + ex.getMessage()); return; } } }
Java
package relay; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * 5v are required to drive the relay * The GPIO pins deliver 3.3v * To drive a relay, a relay board is required. * (it may contain what's needed to drive the relay with 3.3v) */ public class Relay01 { public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - pin 00/#17 and 01/#18 ... started."); System.out.println("(Labelled #17 an #18 on the cobbler.)"); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // For a relay it seems that HIGH means NC (Normally Closed)... final GpioPinDigitalOutput pin17 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "Relay1", PinState.HIGH); final GpioPinDigitalOutput pin18 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "Relay2", PinState.HIGH); System.out.println("--> GPIO state should be: OFF, and it is "); Thread.sleep(1000); pin17.low(); System.out.println("--> pin 17 should be: ON, and it is " + (pin17.isHigh()?"OFF":"ON")); Thread.sleep(1000); pin17.high(); System.out.println("--> pin 17 should be: OFF"); Thread.sleep(1000); pin18.low(); System.out.println("--> pin 18 should be: ON"); Thread.sleep(1000); pin18.high(); System.out.println("--> pin 18 should be: OFF"); gpio.shutdown(); } }
Java
package adc.gui; import adc.ADCObserver; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class AnalogDisplayApp { private ADCObserver.MCP3008_input_channels channel = null; private final ADCObserver obs; public AnalogDisplayApp(int ch) { channel = findChannel(ch); obs = new ADCObserver(channel); // Note: We could instantiate more than one observer (on several channels). JFrame frame = new AnalogDisplayFrame(channel, this); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } frame.setLocation( ( screenSize.width - frameSize.width ) / 2, ( screenSize.height - frameSize.height ) / 2 ); // frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { close(); System.exit(0); } }); frame.setVisible(true); if (true) // For Dev... { try { obs.start(); } catch (Exception ioe) { System.err.println("Oops"); ioe.printStackTrace(); } } } public static void main(String[] args) { try { if (System.getProperty("swing.defaultlaf") == null) UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } int channel = 0; if (args.length > 0) channel = Integer.parseInt(args[0]); new AnalogDisplayApp(channel); // swingWait(1L); } public void close() { System.out.println("Exiting."); if (obs != null) obs.stop(); } private static ADCObserver.MCP3008_input_channels findChannel(int ch) throws IllegalArgumentException { ADCObserver.MCP3008_input_channels channel = null; switch (ch) { case 0: channel = ADCObserver.MCP3008_input_channels.CH0; break; case 1: channel = ADCObserver.MCP3008_input_channels.CH1; break; case 2: channel = ADCObserver.MCP3008_input_channels.CH2; break; case 3: channel = ADCObserver.MCP3008_input_channels.CH3; break; case 4: channel = ADCObserver.MCP3008_input_channels.CH4; break; case 5: channel = ADCObserver.MCP3008_input_channels.CH5; break; case 6: channel = ADCObserver.MCP3008_input_channels.CH6; break; case 7: channel = ADCObserver.MCP3008_input_channels.CH7; break; default: throw new IllegalArgumentException("No channel " + Integer.toString(ch)); } return channel; } private static void swingWait(final long w) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { try { Thread.sleep(w); } catch (Exception ex) {} } }); } catch (Exception ex) { ex.printStackTrace(); } } }
Java
package adc.gui; import adc.ADCObserver; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class AnalogDisplayFrame extends JFrame { private JMenuBar menuBar = new JMenuBar(); private JMenu menuFile = new JMenu(); private JMenuItem menuFileExit = new JMenuItem(); private AnalogDisplayPanel displayPanel = null; private transient AnalogDisplayApp caller; public AnalogDisplayFrame(ADCObserver.MCP3008_input_channels channel, AnalogDisplayApp parent) { this.caller = parent; displayPanel = new AnalogDisplayPanel(channel, 100); try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setJMenuBar(menuBar); this.getContentPane().setLayout(new BorderLayout()); this.setSize(new Dimension(400, 275)); this.setTitle("Volume"); menuFile.setText("File"); menuFileExit.setText("Exit"); menuFileExit.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { fileExit_ActionPerformed( ae ); } } ); menuFile.add( menuFileExit ); menuBar.add( menuFile ); this.getContentPane().add(displayPanel, BorderLayout.CENTER); } void fileExit_ActionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); this.caller.close(); System.exit(0); } }
Java
package adc; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * Read an Analog to Digital Converter */ public class ADCObserver { private final static boolean DISPLAY_DIGIT = false; // Note: "Mismatch" 23-24. The wiring says DOUT->#23, DIN->#24 // 23: DOUT on the ADC is IN on the GPIO. ADC:Slave, GPIO:Master // 24: DIN on the ADC, OUT on the GPIO. Same reason as above. // SPI: Serial Peripheral Interface private static Pin spiClk = RaspiPin.GPIO_01; // Pin #18, clock private static Pin spiMiso = RaspiPin.GPIO_04; // Pin #23, data in. MISO: Master In Slave Out private static Pin spiMosi = RaspiPin.GPIO_05; // Pin #24, data out. MOSI: Master Out Slave In private static Pin spiCs = RaspiPin.GPIO_06; // Pin #25, Chip Select public static enum MCP3008_input_channels { CH0(0), CH1(1), CH2(2), CH3(3), CH4(4), CH5(5), CH6(6), CH7(7); private int ch; MCP3008_input_channels(int chNum) { this.ch = chNum; } public int ch() { return this.ch; } } private MCP3008_input_channels[] adcChannel; // Between 0 and 7, 8 channels on the MCP3008 private static GpioPinDigitalInput misoInput = null; private static GpioPinDigitalOutput mosiOutput = null; private static GpioPinDigitalOutput clockOutput = null; private static GpioPinDigitalOutput chipSelectOutput = null; private boolean go = true; public ADCObserver(MCP3008_input_channels channel) { this(new MCP3008_input_channels[] { channel }) ; } public ADCObserver(MCP3008_input_channels[] channel) { adcChannel = channel; } public void start() { GpioController gpio = GpioFactory.getInstance(); mosiOutput = gpio.provisionDigitalOutputPin(spiMosi, "MOSI", PinState.LOW); clockOutput = gpio.provisionDigitalOutputPin(spiClk, "CLK", PinState.LOW); chipSelectOutput = gpio.provisionDigitalOutputPin(spiCs, "CS", PinState.LOW); misoInput = gpio.provisionDigitalInputPin(spiMiso, "MISO"); int lastRead[] = new int[adcChannel.length]; for (int i=0; i<lastRead.length; i++) lastRead[i] = 0; int tolerance = 5; while (go) { for (int i=0; i<adcChannel.length; i++) { int adc = readAdc(adcChannel[i]); // System.out.println("ADC:" + adc); int postAdjust = Math.abs(adc - lastRead[i]); if (postAdjust > tolerance) { ADCContext.getInstance().fireValueChanged(adcChannel[i], adc); lastRead[i] = adc; } } try { Thread.sleep(100L); } catch (InterruptedException ie) { ie.printStackTrace(); } } System.out.println("Shutting down..."); gpio.shutdown(); } public void stop() { go = false; } private int readAdc(MCP3008_input_channels channel) { chipSelectOutput.high(); clockOutput.low(); chipSelectOutput.low(); int adccommand = channel.ch(); adccommand |= 0x18; // 0x18: 00011000 adccommand <<= 3; // Send 5 bits: 8 - 3. 8 input channels on the MCP3008. for (int i=0; i<5; i++) // { if ((adccommand & 0x80) != 0x0) // 0x80 = 0&10000000 mosiOutput.high(); else mosiOutput.low(); adccommand <<= 1; clockOutput.high(); clockOutput.low(); } int adcOut = 0; for (int i=0; i<12; i++) // Read in one empty bit, one null bit and 10 ADC bits { clockOutput.high(); clockOutput.low(); adcOut <<= 1; if (misoInput.isHigh()) { // System.out.println(" " + misoInput.getName() + " is high (i:" + i + ")"); // Shift one bit on the adcOut adcOut |= 0x1; } if (DISPLAY_DIGIT) System.out.println("ADCOUT: 0x" + Integer.toString(adcOut, 16).toUpperCase() + ", 0&" + Integer.toString(adcOut, 2).toUpperCase()); } chipSelectOutput.high(); adcOut >>= 1; // Drop first bit return adcOut; } }
Java
package adc; import java.util.ArrayList; import java.util.List; public class ADCContext { private static ADCContext instance = null; private List<ADCListener> listeners = null; private ADCContext() { listeners = new ArrayList<ADCListener>(); } public synchronized static ADCContext getInstance() { if (instance == null) instance = new ADCContext(); return instance; } public void addListener(ADCListener listener) { if (!listeners.contains(listener)) listeners.add(listener); } public void removeListener(ADCListener listener) { if (listeners.contains(listener)) listeners.remove(listener); } public List<ADCListener> getListeners() { return this.listeners; } public void fireValueChanged(ADCObserver.MCP3008_input_channels channel, int newValue) { for (ADCListener listener : listeners) listener.valueUpdated(channel, newValue); } }
Java
package adc; public class ADCListener { public void valueUpdated(ADCObserver.MCP3008_input_channels channel, int newValue) {}; }
Java
package adc.sample; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; import adc.utils.EscapeSeq; import org.fusesource.jansi.AnsiConsole; public class SampleMain { private final static boolean DEBUG = false; private final static String STR100 = " "; private final static int DIGITAL_OPTION = 0; private final static int ANALOG_OPTION = 1; private static int displayOption = ANALOG_OPTION; final String[] channelColors = new String[] { EscapeSeq.ANSI_RED, EscapeSeq.ANSI_BLUE, EscapeSeq.ANSI_YELLOW, EscapeSeq.ANSI_GREEN, EscapeSeq.ANSI_WHITE }; private ADCObserver.MCP3008_input_channels channel = null; public SampleMain(int ch) throws Exception { channel = findChannel(ch); final ADCObserver obs = new ADCObserver(channel); // Note: We could instantiate more than one observer (on several channels). ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { if (inputChannel.equals(channel)) { int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (DEBUG) System.out.println("readAdc:" + Integer.toString(newValue) + " (0x" + lpad(Integer.toString(newValue, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(newValue, 2), "0", 8) + ")"); if (displayOption == DIGITAL_OPTION) System.out.println("Volume:" + volume + "% (" + newValue + ")"); else if (displayOption == ANALOG_OPTION) { String str = ""; for (int i=0; i<volume; i++) str += "."; try { str = EscapeSeq.superpose(str, "Ch " + Integer.toString(inputChannel.ch()) + ": " + Integer.toString(volume) + "%"); AnsiConsole.out.println(EscapeSeq.ansiLocate(1, 1) + EscapeSeq.ANSI_NORMAL + EscapeSeq.ANSI_DEFAULT_BACKGROUND + EscapeSeq.ANSI_DEFAULT_TEXT + STR100); AnsiConsole.out.println(EscapeSeq.ansiLocate(1, 1) + EscapeSeq.ansiSetTextAndBackgroundColor(EscapeSeq.ANSI_WHITE, channelColors[inputChannel.ch()]) + EscapeSeq.ANSI_BOLD + str + EscapeSeq.ANSI_NORMAL + EscapeSeq.ANSI_DEFAULT_BACKGROUND + EscapeSeq.ANSI_DEFAULT_TEXT); } catch (Exception ex) { System.out.println(str); } } } } }); obs.start(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (obs != null) obs.stop(); } }); } public static void main(String[] args) throws Exception { if (displayOption == ANALOG_OPTION) { AnsiConsole.systemInstall(); AnsiConsole.out.println(EscapeSeq.ANSI_CLS); } int channel = 0; if (args.length > 0) channel = Integer.parseInt(args[0]); new SampleMain(channel); } private static ADCObserver.MCP3008_input_channels findChannel(int ch) throws IllegalArgumentException { ADCObserver.MCP3008_input_channels channel = null; switch (ch) { case 0: channel = ADCObserver.MCP3008_input_channels.CH0; break; case 1: channel = ADCObserver.MCP3008_input_channels.CH1; break; case 2: channel = ADCObserver.MCP3008_input_channels.CH2; break; case 3: channel = ADCObserver.MCP3008_input_channels.CH3; break; case 4: channel = ADCObserver.MCP3008_input_channels.CH4; break; case 5: channel = ADCObserver.MCP3008_input_channels.CH5; break; case 6: channel = ADCObserver.MCP3008_input_channels.CH6; break; case 7: channel = ADCObserver.MCP3008_input_channels.CH7; break; default: throw new IllegalArgumentException("No channel " + Integer.toString(ch)); } return channel; } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
Java
package adc.sample; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; import java.io.FileOutputStream; import oracle.generic.ws.client.ClientFacade; import oracle.generic.ws.client.ServerListenerAdapter; import oracle.generic.ws.client.ServerListenerInterface; public class WebSocketFeeder { private final static boolean DEBUG = false; private ADCObserver.MCP3008_input_channels channel = null; private boolean keepWorking = true; private ClientFacade webSocketClient = null; public WebSocketFeeder(int ch) throws Exception { channel = findChannel(ch); String wsUri = System.getProperty("ws.uri", "ws://localhost:9876/"); initWebSocketConnection(wsUri); final ADCObserver obs = new ADCObserver(channel); // Note: We could instantiate more than one observer (on several channels). ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { if (inputChannel.equals(channel)) { int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (DEBUG) System.out.println("readAdc:" + Integer.toString(newValue) + " (0x" + lpad(Integer.toString(newValue, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(newValue, 2), "0", 8) + ")"); System.out.println("Volume:" + volume + "% (" + newValue + ")"); webSocketClient.send(Integer.toString(volume)); } } }); obs.start(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (obs != null) obs.stop(); keepWorking = false; webSocketClient.bye(); } }); } private void initWebSocketConnection(String serverURI) { String[] targetedTransports = new String[] {"WebSocket", "XMLHttpRequest"}; ServerListenerInterface serverListener = new ServerListenerAdapter() { @Override public void onMessage(String mess) { // System.out.println(" . Text message :[" + mess + "]"); // JSONObject json = new JSONObject(mess); // System.out.println(" . Mess content:[" + ((JSONObject)json.get("data")).get("text") + "]"); } @Override public void onMessage(byte[] bb) { System.out.println(" . Message for you (ByteBuffer) ..."); System.out.println("Length:" + bb.length); try { FileOutputStream fos = new FileOutputStream("binary.xxx"); for (int i=0; i<bb.length; i++) fos.write(bb[i]); fos.close(); System.out.println("... was written in binary.xxx"); } catch (Exception ex) { ex.printStackTrace(); } } @Override public void onConnect() { System.out.println(" .You're in!"); keepWorking = true; } @Override public void onClose() { System.out.println(" .Connection has been closed..."); keepWorking = false; } @Override public void onError(String error) { System.out.println(" .Oops! error [" + error + "]"); keepWorking = false; // Careful with that one..., in case of a fallback, use the value returned by the init method. } @Override public void setStatus(String status) { System.out.println(" .Your status is now [" + status + "]"); } @Override public void onPong(String s) { if (DEBUG) System.out.println("WS Pong"); } @Override public void onPing(String s) { if (DEBUG) System.out.println("WS Ping"); } @Override public void onHandShakeSentAsClient() { System.out.println("WS-HS sent as client"); } @Override public void onHandShakeReceivedAsServer() { if (DEBUG) System.out.println("WS-HS received as server"); } @Override public void onHandShakeReceivedAsClient() { if (DEBUG) System.out.println("WS-HS received as client"); } }; try { webSocketClient = new ClientFacade(serverURI, targetedTransports, serverListener); keepWorking = webSocketClient.init(); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) throws Exception { int channel = 0; if (args.length > 0) channel = Integer.parseInt(args[0]); new WebSocketFeeder(channel); } private static ADCObserver.MCP3008_input_channels findChannel(int ch) throws IllegalArgumentException { ADCObserver.MCP3008_input_channels channel = null; switch (ch) { case 0: channel = ADCObserver.MCP3008_input_channels.CH0; break; case 1: channel = ADCObserver.MCP3008_input_channels.CH1; break; case 2: channel = ADCObserver.MCP3008_input_channels.CH2; break; case 3: channel = ADCObserver.MCP3008_input_channels.CH3; break; case 4: channel = ADCObserver.MCP3008_input_channels.CH4; break; case 5: channel = ADCObserver.MCP3008_input_channels.CH5; break; case 6: channel = ADCObserver.MCP3008_input_channels.CH6; break; case 7: channel = ADCObserver.MCP3008_input_channels.CH7; break; default: throw new IllegalArgumentException("No channel " + Integer.toString(ch)); } return channel; } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
Java
package adc.sample; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; import java.io.BufferedWriter; import java.io.FileWriter; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.TimeZone; public class BatteryMonitor { private static boolean debug = false; private static boolean calib = false; private ADCObserver.MCP3008_input_channels channel = null; private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private final static TimeZone HERE = TimeZone.getTimeZone("America/Los_Angeles"); static { SDF.setTimeZone(HERE); } private final static NumberFormat VF = new DecimalFormat("00.00"); private static BufferedWriter bw = null; private static ADCObserver obs; private long lastLogTimeStamp = 0; private int lastVolumeLogged = 0; private static String logFileName = "battery.log"; public BatteryMonitor(int ch) throws Exception { channel = findChannel(ch); if (tuning) { minADC = 0; minVolt = 0f; maxADC = tuningADC; maxVolt = tuningVolt; } final int deltaADC = maxADC - minADC; final float deltaVolt = maxVolt - minVolt; final float b = ((maxVolt * minADC) - (minVolt * maxADC)) / deltaADC; final float a = (maxVolt - b) / maxADC; if (debug) { System.out.println("Volt [" + minVolt + ", " + maxVolt + "]"); System.out.println("ADC [" + minADC + ", " + maxADC + "]"); System.out.println("a=" + a+ ", b=" + b); } System.out.println("Value range: ADC=0 => V=" + b + ", ADC=1023 => V=" + ((a * 1023) + b)); obs = new ADCObserver(channel); // Note: We could instantiate more than one observer (on several channels). bw = new BufferedWriter(new FileWriter(logFileName)); ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { if (inputChannel.equals(channel)) { long now = System.currentTimeMillis(); if (calib || Math.abs(now - lastLogTimeStamp) > 1000) { int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (Math.abs(volume - lastVolumeLogged) > 1) // 1 % { float voltage = 0; if (false) { if (newValue < minADC) { voltage = /* 0 + */ minVolt * ((float)newValue / (float)minADC); } else if (newValue >= minADC && newValue <= maxADC) { voltage = minVolt + (deltaVolt * (float)(newValue - minADC) / (float)deltaADC); } else // value > maxADC { voltage = maxVolt + ((15 - maxVolt) * (float)(newValue - maxADC) / (float)(1023 - maxADC)); } } else { voltage = (a * newValue) + b; } if (debug) { System.out.print("readAdc:" + Integer.toString(newValue) + " (0x" + lpad(Integer.toString(newValue, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(newValue, 2), "0", 8) + ") "); System.out.println("Volume:" + volume + "% (" + newValue + ") Volt:" + VF.format(voltage)); } // Log the voltage, along with the date and ADC val. String line = SDF.format(GregorianCalendar.getInstance(HERE).getTime()) + ";" + newValue + ";" + volume + ";" + VF.format(voltage); // System.out.println(line); try { bw.write(line + "\n"); bw.flush(); } catch (Exception ex) { ex.printStackTrace(); } lastLogTimeStamp = now; lastVolumeLogged = volume; } } } } }); obs.start(); } private final static String DEBUG_PRM = "-debug="; private final static String CALIBRATION_PRM = "-calibration"; private final static String CAL_PRM = "-cal"; private final static String CHANNEL_PRM = "-ch="; private final static String MIN_VALUE = "-min="; private final static String MAX_VALUE = "-max="; private final static String TUNE_VALUE = "-tune="; private final static String SCALE_PRM = "-scale="; private final static String LOG_PRM = "-log="; private static int minADC = 0; private static int maxADC = 1023; private static float minVolt = 0f; private static float maxVolt = 15f; private static float tuningVolt = 15f; private static int tuningADC = 1023; private static boolean scale = false; private static boolean tuning = false; public static void main(String[] args) throws Exception { System.out.println("Parameters are:"); System.out.println(" -calibration or -cal"); System.out.println(" -debug=y|n|yes|no|true|false - example -debug=y (default is n)"); System.out.println(" -ch=[0-7] - example -ch=0 (default is 0)"); System.out.println(" -min=minADC:minVolt - example -min=280:3.75 (default is 0:0.0)"); System.out.println(" -max=maxADC:maxVolt - example -min=879:11.25 (default is 1023:15.0)"); System.out.println(" -tune=ADC:volt - example -tune=973:12.6 (default is 1023:15.0)"); System.out.println(" -scale=y|n - example -scale=y (default is n)"); System.out.println(" -log=[log-file-name] - example -log=[batt.csv] (default is battery.log)"); System.out.println(""); System.out.println(" -min & -max are required if -tune is not here, and vice versa."); int channel = 0; for (String prm : args) { if (prm.startsWith(CHANNEL_PRM)) channel = Integer.parseInt(prm.substring(CHANNEL_PRM.length())); else if (prm.startsWith(CALIBRATION_PRM) || prm.startsWith(CAL_PRM)) { debug = true; calib = true; } else if (!debug && prm.startsWith(DEBUG_PRM)) debug = ("y".equals(prm.substring(DEBUG_PRM.length())) || "yes".equals(prm.substring(DEBUG_PRM.length())) || "true".equals(prm.substring(DEBUG_PRM.length()))); else if (prm.startsWith(SCALE_PRM)) scale = ("y".equals(prm.substring(SCALE_PRM.length()))); else if (prm.startsWith(LOG_PRM)) logFileName = prm.substring(LOG_PRM.length()); else if (prm.startsWith(TUNE_VALUE)) { tuning = true; String val = prm.substring(TUNE_VALUE.length()); tuningADC = Integer.parseInt(val.substring(0, val.indexOf(":"))); tuningVolt = Float.parseFloat(val.substring(val.indexOf(":") + 1)); } else if (prm.startsWith(MIN_VALUE)) { String val = prm.substring(MIN_VALUE.length()); minADC = Integer.parseInt(val.substring(0, val.indexOf(":"))); minVolt = Float.parseFloat(val.substring(val.indexOf(":") + 1)); } else if (prm.startsWith(MAX_VALUE)) { String val = prm.substring(MAX_VALUE.length()); maxADC = Integer.parseInt(val.substring(0, val.indexOf(":"))); maxVolt = Float.parseFloat(val.substring(val.indexOf(":") + 1)); } } String prms = "Prms: ADC Channel:" + channel; if (tuning) prms += ", tuningADC:" + tuningADC + ", tuningVolt:" + tuningVolt; else prms += ", MinADC:" + minADC + ", MinVolt:" + minVolt + ", MaxADC:" + maxADC + ", maxVolt:" + maxVolt; System.out.println(prms); if (scale) { if (tuning) { minADC = 0; minVolt = 0f; maxADC = tuningADC; maxVolt = tuningVolt; } final int deltaADC = maxADC - minADC; final float deltaVolt = maxVolt - minVolt; float b = ((maxVolt * minADC) - (minVolt * maxADC)) / deltaADC; float a = (maxVolt - b) / maxADC; // System.out.println("a=" + a + "(" + ((maxVolt - b) / maxADC) + "), b=" + b); System.out.println("=== Scale ==="); System.out.println("Value range: ADC:0 => V:" + b + ", ADC:1023 => V:" + ((a * 1023) + b)); System.out.println("Coeff A:" + a + ", coeff B:" + b); for (int i=0; i<1024; i++) System.out.println(i + ";" + ((a * i) + b)); System.out.println("============="); System.exit(0); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("\nShutting down"); if (bw != null) { System.out.println("Closing log file"); try { bw.flush(); bw.close(); } catch (Exception ex) { ex.printStackTrace(); } } if (obs != null) obs.stop(); } }); new BatteryMonitor(channel); } private static ADCObserver.MCP3008_input_channels findChannel(int ch) throws IllegalArgumentException { ADCObserver.MCP3008_input_channels channel = null; switch (ch) { case 0: channel = ADCObserver.MCP3008_input_channels.CH0; break; case 1: channel = ADCObserver.MCP3008_input_channels.CH1; break; case 2: channel = ADCObserver.MCP3008_input_channels.CH2; break; case 3: channel = ADCObserver.MCP3008_input_channels.CH3; break; case 4: channel = ADCObserver.MCP3008_input_channels.CH4; break; case 5: channel = ADCObserver.MCP3008_input_channels.CH5; break; case 6: channel = ADCObserver.MCP3008_input_channels.CH6; break; case 7: channel = ADCObserver.MCP3008_input_channels.CH7; break; default: throw new IllegalArgumentException("No channel " + Integer.toString(ch)); } return channel; } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
Java
package adc.sample.log; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.swing.JOptionPane; import javax.swing.UIManager; public class LogAnalysis { private static float voltageCoeff = 1.0f; // MULTIPLYING VOLTAGE by this one ! private static int hourOffset = 0; private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private final Map<Date, LogData> logdata = new HashMap<Date, LogData>(); public LogAnalysis(String fName) throws IOException, ParseException { LogAnalysisFrame frame = new LogAnalysisFrame(this); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } frame.setLocation( ( screenSize.width - frameSize.width ) / 2, ( screenSize.height - frameSize.height ) / 2 ); // frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setVisible(true); BufferedReader br = new BufferedReader(new FileReader(fName)); String line = ""; boolean keepReading = true; Date minDate = null, maxDate = null; long smallestTimeInterval = Long.MAX_VALUE; long previousDate = -1L; int prevAdc = 0; int prevVolume = 0; float prevVoltage = 0; float minVolt = Float.MAX_VALUE, maxVolt = Float.MIN_VALUE; int nbl = 0; boolean withSmoothing = "true".equals(System.getProperty("with.smoothing", "true")); while (keepReading) { line = br.readLine(); if (line == null) keepReading = false; else { nbl++; if (nbl % 100 == 0) System.out.println("Read " + nbl + " lines"); String[] data = line.split(";"); try { Date logDate = SDF.parse(data[0]); logDate = new Date(logDate.getTime() + (hourOffset * 3600 * 1000)); // TODO Make sure the gap is not too big (like > 1 day) int adc = Integer.parseInt(data[1]); int volume = Integer.parseInt(data[2]); float voltage = Float.parseFloat(data[3]) * voltageCoeff; if (withSmoothing && previousDate != -1) { // Smooth... long deltaT = (logDate.getTime() - previousDate) / 1000; // in seconds int deltaADC = (adc - prevAdc); int deltaVolume = (volume - prevVolume); float deltaVolt = (voltage - prevVoltage); for (int i=0; i<deltaT; i++) { Date smoothDate = new Date(previousDate + (i * 1000)); int smoothADC = prevAdc + (int)((double)deltaADC * ((double)i / (double)deltaT)); int smoothVolume = prevVolume + (int)((double)deltaVolume * ((double)i / (double)deltaT)); float smoothVolt = prevVoltage + (float)((double)deltaVolt * ((double)i / (double)deltaT)); logdata.put(smoothDate, new LogData(smoothDate, smoothADC, smoothVolume, smoothVolt)); } } else { logdata.put(logDate, new LogData(logDate, adc, volume, voltage)); } if (minDate == null) minDate = logDate; else { long interval = logDate.getTime() - previousDate; smallestTimeInterval = Math.min(smallestTimeInterval, interval); if (logDate.before(minDate)) minDate = logDate; } prevAdc = adc; prevVolume = volume; prevVoltage = voltage; previousDate = logDate.getTime(); if (maxDate == null) maxDate = logDate; else { if (logDate.after(maxDate)) maxDate = logDate; } minVolt = Math.min(minVolt, voltage); maxVolt = Math.max(maxVolt, voltage); } catch (NumberFormatException nfe) { System.err.println("For line [" + line + "], (" + nbl + ") " + nfe.toString()); } catch (ParseException pe) { System.err.println("For line [" + line + "], (" + nbl + ") " + pe.toString()); } catch (Exception ex) { System.err.println("For line [" + line + "], (" + nbl + ")"); ex.printStackTrace(); } } } br.close(); System.out.println("Read " + nbl + " lines."); // Sort // SortedSet<Date> keys = new TreeSet<Date>(logdata.keySet()); // for (Date key : keys) // { // LogData value = logdata.get(key); // // do something // System.out.println(value.getDate() + ": " + value.getVoltage() + " V"); // } if (nbl == 0) { JOptionPane.showMessageDialog(null, "LogFile [" + fName + "] is empty, aborting.", "Battery Log", JOptionPane.WARNING_MESSAGE); System.exit(1); } else { System.out.println("From [" + minDate + "] to [" + maxDate + "] (" + Long.toString((maxDate.getTime() - minDate.getTime()) / 1000) + " s)"); System.out.println("Volts [" + minVolt + ", " + maxVolt + "]"); System.out.println("Smallest interval:" + (smallestTimeInterval / 1000) + " s."); System.out.println("LogData has " + logdata.size() + " element(s)"); frame.setLogData(logdata); } } public static void main(String[] args) throws Exception { try { if (System.getProperty("swing.defaultlaf") == null) UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } try { voltageCoeff = Float.parseFloat(System.getProperty("voltage.coeff", Float.toString(voltageCoeff))); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } try { hourOffset = Integer.parseInt(System.getProperty("hour.offset", Integer.toString(hourOffset))); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } System.setProperty("hour.offset", Integer.toString(hourOffset)); String dataFName = "battery.log"; if (args.length > 0) dataFName = args[0]; new LogAnalysis(dataFName); } public static class LogData { private Date date; private int adc; private int volume; public Date getDate() { return date; } public int getAdc() { return adc; } public int getVolume() { return volume; } public float getVoltage() { return voltage; } private float voltage; public LogData(Date d, int a, int v, float volt) { this.date = d; this.adc = a; this.volume = v; this.voltage = volt; } } }
Java
package adc.sample.log; import adc.sample.log.LogAnalysis.LogData; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.JPanel; public class LogAnalysisPanel extends JPanel implements MouseListener, MouseMotionListener { @SuppressWarnings("compatibility:5644286187611665244") public final static long serialVersionUID = 1L; private transient Map<Date, LogData> logdata = null; private Date minDate = null, maxDate = null; private float minVolt = Float.MAX_VALUE, maxVolt = Float.MIN_VALUE; private final static NumberFormat VOLT_FMT = new DecimalFormat("#0.00"); private final static DateFormat DATE_FMT = new SimpleDateFormat("dd-MMM-yy HH:mm"); protected transient Stroke thick = new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); private boolean withSmoothing = "true".equals(System.getProperty("with.smoothing", "true")); public LogAnalysisPanel() { try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setLayout(null); this.setOpaque(false); this.setBackground(new Color(0, 0, 0, 0)); this.addMouseListener(this); this.addMouseMotionListener(this); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (logdata != null) { // Smooth Voltage Map<Date, Float> smoothVoltage = new HashMap<Date, Float>(); final int SMOOTH_WIDTH = 1000; SortedSet<Date> keys = new TreeSet<Date>(logdata.keySet()); if (withSmoothing) { List<LogData> ld = new ArrayList<LogData>(); for (Date d : keys) ld.add(logdata.get(d)); for (int i=0; i<ld.size(); i++) { float yAccu = 0f; for (int acc=i-(SMOOTH_WIDTH / 2); acc<i+(SMOOTH_WIDTH/2); acc++) { double y; if (acc < 0) y = ld.get(0).getVoltage(); else if (acc > (ld.size() - 1)) y = ld.get(ld.size() - 1).getVoltage(); else y = ld.get(acc).getVoltage(); yAccu += y; } yAccu = yAccu / SMOOTH_WIDTH; // System.out.println("Smooth Voltage:" + yAccu); smoothVoltage.put(ld.get(i).getDate(), yAccu); } } // Sort, mini maxi. boolean narrow = "y".equals(System.getProperty("narrow", "n")); /* SortedSet<Date> */ keys = new TreeSet<Date>(logdata.keySet()); for (Date key : keys) { LogData value = logdata.get(key); // System.out.println(value.getDate() + ": " + value.getVoltage() + " V"); if (minDate == null) minDate = value.getDate(); else { if (value.getDate().before(minDate)) minDate = value.getDate(); } if (maxDate == null) maxDate = value.getDate(); else { if (value.getDate().after(maxDate)) maxDate = value.getDate(); } if (narrow) { minVolt = Math.min(minVolt, value.getVoltage()); maxVolt = Math.max(maxVolt, value.getVoltage()); } } if (!narrow) { minVolt = 0; // Math.min(minVolt, value.getVoltage()); maxVolt = 15; // Math.max(maxVolt, value.getVoltage()); } long timespan = maxDate.getTime() - minDate.getTime(); float voltspan = maxVolt - minVolt; g2d.setColor(Color.white); g2d.fillRect(0, 0, this.getWidth(), this.getHeight()); // Volt grid int minVoltGrid = (int)Math.floor(minVolt); int maxVoltGrid = (int)Math.ceil(maxVolt); g2d.setColor(Color.lightGray); for (int v=minVoltGrid; v<maxVoltGrid; v++) { float voltoffset = v - minVolt; int y = this.getHeight() - (int)(this.getHeight() * ((float)voltoffset / (float)voltspan)); g2d.drawLine(0, y, this.getWidth(), y); } g2d.setColor(Color.red); Point previous = null; // Raw Data for (Date key : keys) { LogData value = logdata.get(key); Date date = key; float volt = value.getVoltage(); long timeoffset = date.getTime() - minDate.getTime(); float voltoffset = volt - minVolt; int x = (int)(this.getWidth() * ((float)timeoffset / (float)timespan)); int y = this.getHeight() - (int)(this.getHeight() * ((float)voltoffset / (float)voltspan)); Point current = new Point(x, y); // System.out.println("x:" + x + ", y:" + y); if (previous != null) g2d.drawLine(previous.x, previous.y, current.x, current.y); previous = current; } if (withSmoothing) { // Smooth Data g2d.setColor(Color.blue); Stroke orig = g2d.getStroke(); g2d.setStroke(thick); previous = null; for (Date key : keys) { float volt = smoothVoltage.get(key).floatValue(); long timeoffset = key.getTime() - minDate.getTime(); float voltoffset = volt - minVolt; int x = (int)(this.getWidth() * ((float)timeoffset / (float)timespan)); int y = this.getHeight() - (int)(this.getHeight() * ((float)voltoffset / (float)voltspan)); Point current = new Point(x, y); //System.out.println("x:" + x + ", y:" + y); if (previous != null) g2d.drawLine(previous.x, previous.y, current.x, current.y); previous = current; } g2d.setStroke(orig); } } } public void setLogData(Map<Date, LogData> logdata) { this.logdata = logdata; this.repaint(); } @Override public void mouseClicked(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mousePressed(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mouseReleased(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mouseEntered(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mouseExited(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mouseDragged(MouseEvent mouseEvent) { // TODO Implement this method } @Override public void mouseMoved(MouseEvent mouseEvent) { int x = mouseEvent.getPoint().x; int y = mouseEvent.getPoint().y; // Voltage try { float voltspan = maxVolt - minVolt; long timespan = maxDate.getTime() - minDate.getTime(); float voltage = minVolt + (voltspan * (float)(this.getHeight() - y) / (float)this.getHeight()); long minTime = minDate.getTime(); long time = minTime + (long)(timespan * ((float)x / (float)this.getWidth())); Date date = new Date(time); String mess = "<html><center><b>" + VOLT_FMT.format(voltage) + " V</b><br>" + DATE_FMT.format(date) + "</center></html>"; // System.out.println(mess); this.setToolTipText(mess); } catch (NullPointerException npe) { } } }
Java
package adc.sample.log; import adc.ADCObserver; import adc.gui.AnalogDisplayApp; import adc.gui.AnalogDisplayPanel; import adc.sample.log.LogAnalysis.LogData; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import java.util.Map; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; public class LogAnalysisFrame extends JFrame { private JMenuBar menuBar = new JMenuBar(); private JMenu menuFile = new JMenu(); private JMenuItem menuFileExit = new JMenuItem(); private LogAnalysisPanel displayPanel = null; private transient LogAnalysis caller; private JScrollPane jScrollPane = null; public LogAnalysisFrame(LogAnalysis parent) { this.caller = parent; displayPanel = new LogAnalysisPanel(); try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setJMenuBar(menuBar); this.getContentPane().setLayout(new BorderLayout()); this.setSize(new Dimension(1000, 275)); this.setTitle("Battery Data"); menuFile.setText("File"); menuFileExit.setText("Exit"); menuFileExit.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { fileExit_ActionPerformed( ae ); } } ); menuFile.add( menuFileExit ); menuBar.add( menuFile ); displayPanel.setPreferredSize(new Dimension(1400, 275)); jScrollPane = new JScrollPane(displayPanel); // this.getContentPane().add(displayPanel, BorderLayout.CENTER); this.getContentPane().add(jScrollPane, BorderLayout.CENTER); } void fileExit_ActionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); // this.caller.close(); System.exit(0); } public void setLogData(Map<Date, LogData> logdata) { displayPanel.setLogData(logdata); } }
Java
package adc.sample; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; import adc.utils.EscapeSeq; import org.fusesource.jansi.AnsiConsole; public class FiveChannelListener { private final static boolean DEBUG = false; private final static String STR100 = " "; private final static int DIGITAL_OPTION = 0; private final static int ANALOG_OPTION = 1; private static int displayOption = ANALOG_OPTION; private static ADCObserver.MCP3008_input_channels channel[] = null; private final int[] channelValues = new int[] { 0, 0, 0, 0, 0 }; public FiveChannelListener() throws Exception { channel = new ADCObserver.MCP3008_input_channels[] { ADCObserver.MCP3008_input_channels.CH0, ADCObserver.MCP3008_input_channels.CH1, ADCObserver.MCP3008_input_channels.CH2, ADCObserver.MCP3008_input_channels.CH3, ADCObserver.MCP3008_input_channels.CH4 }; final ADCObserver obs = new ADCObserver(channel); final String[] channelColors = new String[] { EscapeSeq.ANSI_RED, EscapeSeq.ANSI_WHITE, EscapeSeq.ANSI_YELLOW, EscapeSeq.ANSI_GREEN, EscapeSeq.ANSI_BLUE }; ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { // if (inputChannel.equals(channel)) { int ch = inputChannel.ch(); int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] channelValues[ch] = volume; if (DEBUG) System.out.println("readAdc:" + Integer.toString(newValue) + " (0x" + lpad(Integer.toString(newValue, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(newValue, 2), "0", 8) + ")"); if (displayOption == DIGITAL_OPTION) { String output = ""; for (int chan=0; chan<channel.length; chan++) output += "Ch " + Integer.toString(chan) + ", Volume:" + channelValues[chan] + "% "; System.out.println(output.trim()); } else if (displayOption == ANALOG_OPTION) { for (int chan=0; chan<channel.length; chan++) { String str = ""; for (int i=0; i<channelValues[chan]; i++) str += "."; try { str = EscapeSeq.superpose(str, "Ch " + Integer.toString(chan) + ": " + Integer.toString(channelValues[chan]) + "%"); AnsiConsole.out.println(EscapeSeq.ansiLocate(2, 2 + chan + 1) + EscapeSeq.ANSI_NORMAL + EscapeSeq.ANSI_DEFAULT_BACKGROUND + EscapeSeq.ANSI_DEFAULT_TEXT + STR100); AnsiConsole.out.println(EscapeSeq.ansiLocate(2, 2 + chan + 1) + EscapeSeq.ansiSetTextAndBackgroundColor(EscapeSeq.ANSI_WHITE, channelColors[chan]) + EscapeSeq.ANSI_BOLD + str + EscapeSeq.ANSI_NORMAL + EscapeSeq.ANSI_DEFAULT_BACKGROUND + EscapeSeq.ANSI_DEFAULT_TEXT); } catch (Exception ex) { System.out.println(str); } } } } } }); obs.start(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (obs != null) obs.stop(); } }); } public static void main(String[] args) throws Exception { if (displayOption == ANALOG_OPTION) { AnsiConsole.systemInstall(); AnsiConsole.out.println(EscapeSeq.ANSI_CLS); AnsiConsole.out.println(EscapeSeq.ansiLocate(1, 1) + EscapeSeq.ANSI_NORMAL + EscapeSeq.ANSI_DEFAULT_BACKGROUND + EscapeSeq.ANSI_DEFAULT_TEXT + EscapeSeq.ANSI_BOLD + "Displaying channels' volume"); } // Channels are hard-coded new FiveChannelListener(); } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
Java
package adc.utils; import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; public class EscapeSeq { public final static char ESC = '\u001b'; // (char) 27; public final static String ANSI_BLACK = "0"; public final static String ANSI_RED = "1"; public final static String ANSI_GREEN = "2"; public final static String ANSI_YELLOW = "3"; public final static String ANSI_BLUE = "4"; public final static String ANSI_MAGENTA = "5"; public final static String ANSI_CYAN = "6"; public final static String ANSI_WHITE = "7"; public static final String ANSI_CLS = ESC + "[2J"; public static final String ANSI_HOME = ESC + "[H"; // 0,0 public static final String ANSI_HEAD = ESC + "[1G"; // Start of current line, position 1 public static final String ANSI_NORMAL = ESC + "[0m"; public static final String ANSI_BOLD = ESC + "[1m"; public static final String ANSI_FAINT = ESC + "[2m"; public static final String ANSI_ITALIC = ESC + "[3m"; public static final String ANSI_UNDERLINE = ESC + "[4m"; public static final String ANSI_BLINK = ESC + "[5m"; public static final String ANSI_BLINK_FAST = ESC + "[6m"; public static final String ANSI_REVERSE = ESC + "[7m"; public static final String ANSI_CONCEAL = ESC + "[8m"; public static final String ANSI_CROSSED_OUT = ESC + "[9m"; public static final String ANSI_DEFAULT_TEXT = ESC + "[39m"; public static final String ANSI_DEFAULT_BACKGROUND = ESC + "[49m"; private final static String[] SOME_TEXT = { "What happens when the boat sends an email:", "On the boat, you compose your email, and you put it in your outbox.", "Then you turn your SSB on, and you use the SailMail client program to contact a land SailMail station.", "When the contact is established, the messages sitting in the outbox go through the modem and the SSB to ", "be streamed to the land station. On receive, the land station then turns the messages back into digital files,", "and uses its Internet connection to post them on the web. From there, it's the usual email story." }; public static final String ANSI_AT55 = ESC + "[10;10H"; // Actually 10, 10 public static final String ANSI_WHITEONBLUE = ESC + "[37;44m"; public static String ansiSetBackGroundColor(String color) { // ESC[40-47 return ESC + "[4" + color + "m"; } public static String ansiSetTextColor(String color) { // ESC[30-37 return ESC + "[3" + color + "m"; } public static String ansiSetTextAndBackgroundColor(String text, String bg) { // ESC[30-37;40-47 return ESC + "[3" + text + ";4" + bg + "m"; } public static String ansiLocate(int x, int y) { return ESC + "[" + Integer.toString(y) + ";" + Integer.toString(x) + "H"; // Actually Y, X } // An example public static void main(String[] args) { String str80 = " "; AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); // Display 5 rows, like an horizontal bar chart for (int i=0; i<20; i++) { int value1 = (int)Math.round(Math.random() * 80); int value2 = (int)Math.round(Math.random() * 80); int value3 = (int)Math.round(Math.random() * 80); int value4 = (int)Math.round(Math.random() * 80); int value5 = (int)Math.round(Math.random() * 80); String str1 = ""; for (int j=0; j<value1; j++) str1 += "."; String str2 = ""; for (int j=0; j<value2; j++) str2 += "."; String str3 = ""; for (int j=0; j<value3; j++) str3 += "."; String str4 = ""; for (int j=0; j<value4; j++) str4 += "."; String str5 = ""; for (int j=0; j<value5; j++) str5 += "."; str1 = superpose(str1, "Cell 1:" + Integer.toString(value1)); str2 = superpose(str2, "Cell 2:" + Integer.toString(value2)); str3 = superpose(str3, "Cell 3:" + Integer.toString(value3)); str4 = superpose(str4, "Cell 4:" + Integer.toString(value4)); str5 = superpose(str5, "Cell 5:" + Integer.toString(value5)); // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ansiLocate(0, 1) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 1) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_RED) + ANSI_BOLD + str1 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 2) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 2) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_WHITE) + ANSI_BOLD + str2 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 3) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 3) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_YELLOW) + ANSI_BOLD + str3 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 4) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 4) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_GREEN) + ANSI_BOLD + str4 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 5) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 5) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLUE) + ANSI_BOLD + str5 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); try { Thread.sleep(1000L); } catch (Exception ex) {} } System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } public static String superpose(String orig, String override) { byte[] ret = orig.getBytes(); for (int i=0; i<Math.min(orig.length(), override.length()); i++) ret[i] = (byte)override.charAt(i); return new String(ret); } public static void main_(String[] args) { AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_AT55 + ANSI_REVERSE + "10,10 reverse : Hello world" + ANSI_NORMAL); AnsiConsole.out.println(ANSI_HOME + ANSI_WHITEONBLUE + "WhiteOnBlue : Hello world" + ANSI_NORMAL); AnsiConsole.out.print(ANSI_BOLD + "Bold : Press return..." + ANSI_NORMAL); try { System.in.read(); } catch (Exception e) { } // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); AnsiConsole.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); for (String line : SOME_TEXT) { System.out.print(ANSI_HEAD + line); try { Thread.sleep(1000); } catch (Exception ex) {} } System.out.println(); System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } }
Java
package analogdigitalconverter.mcp3008; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * Read an Analog to Digital Converter */ public class MCP3008Reader { private final static boolean DISPLAY_DIGIT = "true".equals(System.getProperty("display.digit", "false")); // Note: "Mismatch" 23-24. The wiring says DOUT->#23, DIN->#24 // 23: DOUT on the ADC is IN on the GPIO. ADC:Slave, GPIO:Master // 24: DIN on the ADC, OUT on the GPIO. Same reason as above. // SPI: Serial Peripheral Interface private static Pin spiClk = RaspiPin.GPIO_01; // Pin #18, clock private static Pin spiMiso = RaspiPin.GPIO_04; // Pin #23, data in. MISO: Master In Slave Out private static Pin spiMosi = RaspiPin.GPIO_05; // Pin #24, data out. MOSI: Master Out Slave In private static Pin spiCs = RaspiPin.GPIO_06; // Pin #25, Chip Select public enum MCP3008_input_channels { CH0(0), CH1(1), CH2(2), CH3(3), CH4(4), CH5(5), CH6(6), CH7(7); private int ch; MCP3008_input_channels(int chNum) { this.ch = chNum; } public int ch() { return this.ch; } } private static GpioController gpio; private static GpioPinDigitalInput misoInput = null; private static GpioPinDigitalOutput mosiOutput = null; private static GpioPinDigitalOutput clockOutput = null; private static GpioPinDigitalOutput chipSelectOutput = null; public static void initMCP3008() { gpio = GpioFactory.getInstance(); mosiOutput = gpio.provisionDigitalOutputPin(spiMosi, "MOSI", PinState.LOW); clockOutput = gpio.provisionDigitalOutputPin(spiClk, "CLK", PinState.LOW); chipSelectOutput = gpio.provisionDigitalOutputPin(spiCs, "CS", PinState.LOW); misoInput = gpio.provisionDigitalInputPin(spiMiso, "MISO"); } public static void shutdownMCP3008() { gpio.shutdown(); } public static int readMCP3008(int channel) { chipSelectOutput.high(); clockOutput.low(); chipSelectOutput.low(); int adccommand = channel; if (DISPLAY_DIGIT) System.out.println("1 - ADCCOMMAND: 0x" + lpad(Integer.toString(adccommand, 16).toUpperCase(), "0", 4) + ", 0&" + lpad(Integer.toString(adccommand, 2).toUpperCase(), "0", 16)); adccommand |= 0x18; // 0x18: 00011000 if (DISPLAY_DIGIT) System.out.println("2 - ADCCOMMAND: 0x" + lpad(Integer.toString(adccommand, 16).toUpperCase(), "0", 4) + ", 0&" + lpad(Integer.toString(adccommand, 2).toUpperCase(), "0", 16)); adccommand <<= 3; if (DISPLAY_DIGIT) System.out.println("3 - ADCCOMMAND: 0x" + lpad(Integer.toString(adccommand, 16).toUpperCase(), "0", 4) + ", 0&" + lpad(Integer.toString(adccommand, 2).toUpperCase(), "0", 16)); // Send 5 bits: 8 - 3. 8 input channels on the MCP3008. for (int i=0; i<5; i++) // { if (DISPLAY_DIGIT) System.out.println("4 - (i=" + i + ") ADCCOMMAND: 0x" + lpad(Integer.toString(adccommand, 16).toUpperCase(), "0", 4) + ", 0&" + lpad(Integer.toString(adccommand, 2).toUpperCase(), "0", 16)); if ((adccommand & 0x80) != 0x0) // 0x80 = 0&10000000 mosiOutput.high(); else mosiOutput.low(); adccommand <<= 1; // Clock high and low tickOnPin(clockOutput); } int adcOut = 0; for (int i=0; i<12; i++) // Read in one empty bit, one null bit and 10 ADC bits { tickOnPin(clockOutput); adcOut <<= 1; if (misoInput.isHigh()) { // System.out.println(" " + misoInput.getName() + " is high (i:" + i + ")"); // Shift one bit on the adcOut adcOut |= 0x1; } if (DISPLAY_DIGIT) System.out.println("ADCOUT: 0x" + lpad(Integer.toString(adcOut, 16).toUpperCase(), "0", 4) + ", 0&" + lpad(Integer.toString(adcOut, 2).toUpperCase(), "0", 16)); } chipSelectOutput.high(); adcOut >>= 1; // Drop first bit return adcOut; } private static void tickOnPin(GpioPinDigitalOutput pin) { pin.high(); pin.low(); } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
Java
package analogdigitalconverter.mcp3008.sample; import analogdigitalconverter.mcp3008.MCP3008Reader; import analogdigitalconverter.mcp3008.MCP3008Reader.MCP3008_input_channels; public class MainMCP3008Sample { private final static boolean DEBUG = false; private static boolean go = true; private static int ADC_CHANNEL = MCP3008Reader.MCP3008_input_channels.CH0.ch(); // Between 0 and 7, 8 channels on the MCP3008 public static void main(String[] args) { MCP3008Reader.initMCP3008(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Shutting down."); go = false; synchronized (Thread.currentThread()) { Thread.currentThread().notify(); } } }); int lastRead = 0; int tolerance = 5; while (go) { boolean trimPotChanged = false; int adc = MCP3008Reader.readMCP3008(ADC_CHANNEL); int postAdjust = Math.abs(adc - lastRead); if (postAdjust > tolerance) { trimPotChanged = true; int volume = (int)(adc / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (DEBUG) System.out.println("readAdc:" + Integer.toString(adc) + " (0x" + lpad(Integer.toString(adc, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(adc, 2), "0", 8) + ")"); System.out.println("Volume:" + volume + "% (" + adc + ")"); lastRead = adc; } try { synchronized (Thread.currentThread()) { Thread.currentThread().wait(100L); } } catch (InterruptedException ie) { ie.printStackTrace(); } } System.out.println("Bye, freeing resources."); MCP3008Reader.shutdownMCP3008(); } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
Java
package analogdigitalconverter; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * Read an Analog to Digital Converter */ public class ADCReader { private final static boolean DISPLAY_DIGIT = false; private final static boolean DEBUG = false; // Note: "Mismatch" 23-24. The wiring says DOUT->#23, DIN->#24 // 23: DOUT on the ADC is IN on the GPIO. ADC:Slave, GPIO:Master // 24: DIN on the ADC, OUT on the GPIO. Same reason as above. // SPI: Serial Peripheral Interface private static Pin spiClk = RaspiPin.GPIO_01; // Pin #18, clock private static Pin spiMiso = RaspiPin.GPIO_04; // Pin #23, data in. MISO: Master In Slave Out private static Pin spiMosi = RaspiPin.GPIO_05; // Pin #24, data out. MOSI: Master Out Slave In private static Pin spiCs = RaspiPin.GPIO_06; // Pin #25, Chip Select private enum MCP3008_input_channels { CH0(0), CH1(1), CH2(2), CH3(3), CH4(4), CH5(5), CH6(6), CH7(7); private int ch; MCP3008_input_channels(int chNum) { this.ch = chNum; } public int ch() { return this.ch; } } private static int ADC_CHANNEL = MCP3008_input_channels.CH0.ch(); // Between 0 and 7, 8 channels on the MCP3008 private static GpioPinDigitalInput misoInput = null; private static GpioPinDigitalOutput mosiOutput = null; private static GpioPinDigitalOutput clockOutput = null; private static GpioPinDigitalOutput chipSelectOutput = null; private static boolean go = true; public static void main(String[] args) { GpioController gpio = GpioFactory.getInstance(); mosiOutput = gpio.provisionDigitalOutputPin(spiMosi, "MOSI", PinState.LOW); clockOutput = gpio.provisionDigitalOutputPin(spiClk, "CLK", PinState.LOW); chipSelectOutput = gpio.provisionDigitalOutputPin(spiCs, "CS", PinState.LOW); misoInput = gpio.provisionDigitalInputPin(spiMiso, "MISO"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Shutting down."); go = false; } }); int lastRead = 0; int tolerance = 5; while (go) { boolean trimPotChanged = false; int adc = readAdc(); int postAdjust = Math.abs(adc - lastRead); if (postAdjust > tolerance) { trimPotChanged = true; int volume = (int)(adc / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (DEBUG) System.out.println("readAdc:" + Integer.toString(adc) + " (0x" + lpad(Integer.toString(adc, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(adc, 2), "0", 8) + ")"); System.out.println("Volume:" + volume + "% (" + adc + ")"); lastRead = adc; } try { Thread.sleep(100L); } catch (InterruptedException ie) { ie.printStackTrace(); } } System.out.println("Bye..."); gpio.shutdown(); } private static int readAdc() { chipSelectOutput.high(); clockOutput.low(); chipSelectOutput.low(); int adccommand = ADC_CHANNEL; adccommand |= 0x18; // 0x18: 00011000 adccommand <<= 3; // Send 5 bits: 8 - 3. 8 input channels on the MCP3008. for (int i=0; i<5; i++) // { if ((adccommand & 0x80) != 0x0) // 0x80 = 0&10000000 mosiOutput.high(); else mosiOutput.low(); adccommand <<= 1; clockOutput.high(); clockOutput.low(); } int adcOut = 0; for (int i=0; i<12; i++) // Read in one empty bit, one null bit and 10 ADC bits { clockOutput.high(); clockOutput.low(); adcOut <<= 1; if (misoInput.isHigh()) { // System.out.println(" " + misoInput.getName() + " is high (i:" + i + ")"); // Shift one bit on the adcOut adcOut |= 0x1; } if (DISPLAY_DIGIT) System.out.println("ADCOUT: 0x" + Integer.toString(adcOut, 16).toUpperCase() + ", 0&" + Integer.toString(adcOut, 2).toUpperCase()); } chipSelectOutput.high(); adcOut >>= 1; // Drop first bit return adcOut; } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
Java
package dac.sample; import dac.mcp4725.AdafruitMCP4725; import java.io.IOException; public class DACSample { private static final int[] DACLookupFullSine9Bit = new int[] { 2048, 2073, 2098, 2123, 2148, 2174, 2199, 2224, 2249, 2274, 2299, 2324, 2349, 2373, 2398, 2423, 2448, 2472, 2497, 2521, 2546, 2570, 2594, 2618, 2643, 2667, 2690, 2714, 2738, 2762, 2785, 2808, 2832, 2855, 2878, 2901, 2924, 2946, 2969, 2991, 3013, 3036, 3057, 3079, 3101, 3122, 3144, 3165, 3186, 3207, 3227, 3248, 3268, 3288, 3308, 3328, 3347, 3367, 3386, 3405, 3423, 3442, 3460, 3478, 3496, 3514, 3531, 3548, 3565, 3582, 3599, 3615, 3631, 3647, 3663, 3678, 3693, 3708, 3722, 3737, 3751, 3765, 3778, 3792, 3805, 3817, 3830, 3842, 3854, 3866, 3877, 3888, 3899, 3910, 3920, 3930, 3940, 3950, 3959, 3968, 3976, 3985, 3993, 4000, 4008, 4015, 4022, 4028, 4035, 4041, 4046, 4052, 4057, 4061, 4066, 4070, 4074, 4077, 4081, 4084, 4086, 4088, 4090, 4092, 4094, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4094, 4092, 4090, 4088, 4086, 4084, 4081, 4077, 4074, 4070, 4066, 4061, 4057, 4052, 4046, 4041, 4035, 4028, 4022, 4015, 4008, 4000, 3993, 3985, 3976, 3968, 3959, 3950, 3940, 3930, 3920, 3910, 3899, 3888, 3877, 3866, 3854, 3842, 3830, 3817, 3805, 3792, 3778, 3765, 3751, 3737, 3722, 3708, 3693, 3678, 3663, 3647, 3631, 3615, 3599, 3582, 3565, 3548, 3531, 3514, 3496, 3478, 3460, 3442, 3423, 3405, 3386, 3367, 3347, 3328, 3308, 3288, 3268, 3248, 3227, 3207, 3186, 3165, 3144, 3122, 3101, 3079, 3057, 3036, 3013, 2991, 2969, 2946, 2924, 2901, 2878, 2855, 2832, 2808, 2785, 2762, 2738, 2714, 2690, 2667, 2643, 2618, 2594, 2570, 2546, 2521, 2497, 2472, 2448, 2423, 2398, 2373, 2349, 2324, 2299, 2274, 2249, 2224, 2199, 2174, 2148, 2123, 2098, 2073, 2048, 2023, 1998, 1973, 1948, 1922, 1897, 1872, 1847, 1822, 1797, 1772, 1747, 1723, 1698, 1673, 1648, 1624, 1599, 1575, 1550, 1526, 1502, 1478, 1453, 1429, 1406, 1382, 1358, 1334, 1311, 1288, 1264, 1241, 1218, 1195, 1172, 1150, 1127, 1105, 1083, 1060, 1039, 1017, 995, 974, 952, 931, 910, 889, 869, 848, 828, 808, 788, 768, 749, 729, 710, 691, 673, 654, 636, 618, 600, 582, 565, 548, 531, 514, 497, 481, 465, 449, 433, 418, 403, 388, 374, 359, 345, 331, 318, 304, 291, 279, 266, 254, 242, 230, 219, 208, 197, 186, 176, 166, 156, 146, 137, 128, 120, 111, 103, 96, 88, 81, 74, 68, 61, 55, 50, 44, 39, 35, 30, 26, 22, 19, 15, 12, 10, 8, 6, 4, 2, 1, 1, 0, 0, 0, 1, 1, 2, 4, 6, 8, 10, 12, 15, 19, 22, 26, 30, 35, 39, 44, 50, 55, 61, 68, 74, 81, 88, 96, 103, 111, 120, 128, 137, 146, 156, 166, 176, 186, 197, 208, 219, 230, 242, 254, 266, 279, 291, 304, 318, 331, 345, 359, 374, 388, 403, 418, 433, 449, 465, 481, 497, 514, 531, 548, 565, 582, 600, 618, 636, 654, 673, 691, 710, 729, 749, 768, 788, 808, 828, 848, 869, 889, 910, 931, 952, 974, 995, 1017, 1039, 1060, 1083, 1105, 1127, 1150, 1172, 1195, 1218, 1241, 1264, 1288, 1311, 1334, 1358, 1382, 1406, 1429, 1453, 1478, 1502, 1526, 1550, 1575, 1599, 1624, 1648, 1673, 1698, 1723, 1747, 1772, 1797, 1822, 1847, 1872, 1897, 1922, 1948, 1973, 1998, 2023 }; public static void main(String[] args)// throws IOException { System.out.println("The output happens on the VOUT terminal of the MCP4725."); AdafruitMCP4725 dac = new AdafruitMCP4725(); for (int i=0; i<5; i++) { for (int volt : DACLookupFullSine9Bit) { dac.setVoltage(volt); try { Thread.sleep(10L); } catch (InterruptedException ie) {} } } } }
Java
package dac.mcp4725; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import java.io.IOException; public class AdafruitMCP4725 { public final static int MCP4725_ADDRESS = 0x62; // Can be changed with pin A0. A0 connected to VDD: 0x63 public final static int MCP4725_REG_WRITEDAC = 0x40; public final static int MCP4725_REG_WRITEDACEEPROM = 0x60; private static boolean verbose = true; private I2CBus bus; private I2CDevice mcp4725; public AdafruitMCP4725() { this(MCP4725_ADDRESS); } public AdafruitMCP4725(int address) { try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends on the RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself mcp4725 = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); } catch (IOException e) { System.err.println(e.getMessage()); } } // Set the voltage, readable on the VOUT terminal public void setVoltage(int voltage) // throws IOException { try { setVoltage(voltage, false); } catch (IOException ioe) { ioe.printStackTrace(); } catch (NullPointerException npe) { npe.printStackTrace(); } } public void setVoltage(int voltage, boolean persist) throws IOException, NullPointerException { voltage = Math.min(voltage, 4095); // 4096 = 2^12 voltage = Math.max(voltage, 0); byte[] bytes = new byte[2]; bytes[0] = (byte)((voltage >> 4) & 0xff); bytes[1] = (byte)((voltage << 4) & 0xff); if (persist) this.mcp4725.write(MCP4725_REG_WRITEDACEEPROM, bytes, 0, 2); else this.mcp4725.write(MCP4725_REG_WRITEDAC, bytes, 0, 2); } }
Java
package sunservo; import org.fusesource.jansi.AnsiConsole; public class EscapeSeq { public final static char ESC = '\u001b'; // (char) 27; public final static String ANSI_BLACK = "0"; public final static String ANSI_RED = "1"; public final static String ANSI_GREEN = "2"; public final static String ANSI_YELLOW = "3"; public final static String ANSI_BLUE = "4"; public final static String ANSI_MAGENTA = "5"; public final static String ANSI_CYAN = "6"; public final static String ANSI_WHITE = "7"; public static final String ANSI_CLS = ESC + "[2J"; public static final String ANSI_HOME = ESC + "[H"; // 0,0 public static final String ANSI_HEAD = ESC + "[1G"; // Start of current line, position 1 public static final String ANSI_NORMAL = ESC + "[0m"; public static final String ANSI_BOLD = ESC + "[1m"; public static final String ANSI_FAINT = ESC + "[2m"; public static final String ANSI_ITALIC = ESC + "[3m"; public static final String ANSI_UNDERLINE = ESC + "[4m"; public static final String ANSI_BLINK = ESC + "[5m"; public static final String ANSI_BLINK_FAST = ESC + "[6m"; public static final String ANSI_REVERSE = ESC + "[7m"; public static final String ANSI_CONCEAL = ESC + "[8m"; public static final String ANSI_CROSSED_OUT = ESC + "[9m"; public static final String ANSI_DEFAULT_TEXT = ESC + "[39m"; public static final String ANSI_DEFAULT_BACKGROUND = ESC + "[49m"; private final static String[] SOME_TEXT = { "What happens when the boat sends an email:", "On the boat, you compose your email, and you put it in your outbox.", "Then you turn your SSB on, and you use the SailMail client program to contact a land SailMail station.", "When the contact is established, the messages sitting in the outbox go through the modem and the SSB to ", "be streamed to the land station. On receive, the land station then turns the messages back into digital files,", "and uses its Internet connection to post them on the web. From there, it's the usual email story." }; public static final String ANSI_AT55 = ESC + "[10;10H"; // Actually 10, 10 public static final String ANSI_WHITEONBLUE = ESC + "[37;44m"; public static String ansiSetBackGroundColor(String color) { // ESC[40-47 return ESC + "[4" + color + "m"; } public static String ansiSetTextColor(String color) { // ESC[30-37 return ESC + "[3" + color + "m"; } public static String ansiSetTextAndBackgroundColor(String text, String bg) { // ESC[30-37;40-47 return ESC + "[3" + text + ";4" + bg + "m"; } public static String ansiLocate(int x, int y) { return ESC + "[" + Integer.toString(y) + ";" + Integer.toString(x) + "H"; // Actually Y, X } // An example public static void main(String[] args) { String str80 = " "; AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); // Display 5 rows, like an horizontal bar chart for (int i=0; i<20; i++) { int value1 = (int)Math.round(Math.random() * 80); int value2 = (int)Math.round(Math.random() * 80); int value3 = (int)Math.round(Math.random() * 80); int value4 = (int)Math.round(Math.random() * 80); int value5 = (int)Math.round(Math.random() * 80); String str1 = ""; for (int j=0; j<value1; j++) str1 += "."; String str2 = ""; for (int j=0; j<value2; j++) str2 += "."; String str3 = ""; for (int j=0; j<value3; j++) str3 += "."; String str4 = ""; for (int j=0; j<value4; j++) str4 += "."; String str5 = ""; for (int j=0; j<value5; j++) str5 += "."; str1 = superpose(str1, "Cell 1:" + Integer.toString(value1)); str2 = superpose(str2, "Cell 2:" + Integer.toString(value2)); str3 = superpose(str3, "Cell 3:" + Integer.toString(value3)); str4 = superpose(str4, "Cell 4:" + Integer.toString(value4)); str5 = superpose(str5, "Cell 5:" + Integer.toString(value5)); // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ansiLocate(0, 1) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 1) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_RED) + ANSI_BOLD + str1 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 2) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 2) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_WHITE) + ANSI_BOLD + str2 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 3) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 3) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_YELLOW) + ANSI_BOLD + str3 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 4) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 4) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_GREEN) + ANSI_BOLD + str4 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 5) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 5) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLUE) + ANSI_BOLD + str5 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); try { Thread.sleep(1000L); } catch (Exception ex) {} } System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } public static String superpose(String orig, String override) { byte[] ret = orig.getBytes(); for (int i=0; i<Math.min(orig.length(), override.length()); i++) ret[i] = (byte)override.charAt(i); return new String(ret); } public static void main_(String[] args) { AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_AT55 + ANSI_REVERSE + "10,10 reverse : Hello world" + ANSI_NORMAL); AnsiConsole.out.println(ANSI_HOME + ANSI_WHITEONBLUE + "WhiteOnBlue : Hello world" + ANSI_NORMAL); AnsiConsole.out.print(ANSI_BOLD + "Bold : Press return..." + ANSI_NORMAL); try { System.in.read(); } catch (Exception e) { } // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); AnsiConsole.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); for (String line : SOME_TEXT) { System.out.print(ANSI_HEAD + line); try { Thread.sleep(1000); } catch (Exception ex) {} } System.out.println(); System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } }
Java
package gpio01; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class GPIO01led { public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - pin 01 ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #01 as an output pin and turn on final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "MyLED", PinState.HIGH); System.out.println("--> GPIO state should be: ON"); Thread.sleep(5000); // turn off gpio pin #01 pin.low(); System.out.println("--> GPIO state should be: OFF"); Thread.sleep(5000); // toggle the current state of gpio pin #01 (should turn on) pin.toggle(); System.out.println("--> GPIO state should be: ON"); Thread.sleep(5000); // toggle the current state of gpio pin #01 (should turn off) pin.toggle(); System.out.println("--> GPIO state should be: OFF"); Thread.sleep(5000); // turn on gpio pin #01 for 1 second and then off System.out.println("--> GPIO state should be: ON for only 1 second"); pin.pulse(1000, true); // set second argument to 'true' use a blocking call // stop all GPIO activity/threads by shutting down the GPIO controller // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks) gpio.shutdown(); } }
Java
package gpio01; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class GPIO08led { public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control ...started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalOutput pin00 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "00", PinState.HIGH); final GpioPinDigitalOutput pin01 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "01", PinState.HIGH); final GpioPinDigitalOutput pin02 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "02", PinState.HIGH); final GpioPinDigitalOutput pin03 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03, "03", PinState.HIGH); final GpioPinDigitalOutput pin04 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "04", PinState.HIGH); final GpioPinDigitalOutput pin05 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_05, "05", PinState.HIGH); final GpioPinDigitalOutput pin06 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_06, "06", PinState.HIGH); final GpioPinDigitalOutput pin07 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_07, "07", PinState.HIGH); final GpioPinDigitalOutput[] ledArray = { pin00, pin01, pin02, pin03, pin04, pin05, pin06, pin07 }; System.out.println("Down an Up"); // Down Thread.sleep(1000); for (int i=0; i<ledArray.length; i++) { ledArray[i].toggle(); Thread.sleep(100); } Thread.sleep(1000); // Up for (int i=0; i<ledArray.length; i++) { ledArray[ledArray.length - 1 - i].toggle(); Thread.sleep(100); } System.out.println("One only"); // Down Thread.sleep(1000); for (int i=0; i<ledArray.length; i++) { oneOnly(ledArray, ledArray[i]); Thread.sleep(100); } Thread.sleep(1000); // Up for (int i=0; i<ledArray.length; i++) { oneOnly(ledArray, ledArray[ledArray.length - 1 - i]); Thread.sleep(100); } System.out.println("Messy..."); Thread.sleep(1000); // Big mess for (int i=0; i<1000; i++) { int idx = (int)(Math.random() * 8); ledArray[idx].toggle(); Thread.sleep(50); } System.out.println("Down and Up, closing."); // Down Thread.sleep(500); for (int i=0; i<ledArray.length; i++) { oneOnly(ledArray, ledArray[i]); Thread.sleep(100); } // Up for (int i=0; i<ledArray.length; i++) { oneOnly(ledArray, ledArray[ledArray.length - 1 - i]); Thread.sleep(100); } System.out.println("Done."); Thread.sleep(1000); // Everything off for (int i=0; i<ledArray.length; i++) ledArray[i].low(); gpio.shutdown(); } private static void oneOnly(GpioPinDigitalOutput[] allLeds, GpioPinDigitalOutput theOneOn) { for (int i=0; i<allLeds.length; i++) { if (allLeds[i].equals(theOneOn)) allLeds[i].high(); else allLeds[i].low(); } } }
Java
package gpio01; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class GPIO02led { public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - pin 00 & 02 ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #00 & #02 as an output pin and turn on final GpioPinDigitalOutput pin00 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "RedLed", PinState.HIGH); final GpioPinDigitalOutput pin02 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "GreenLed", PinState.HIGH); Thread.sleep(1000); System.out.println("Blinking red fast..."); for (int i=0; i<100; i++) { pin00.toggle(); Thread.sleep(50); } System.out.println("Blinking green fast..."); for (int i=0; i<100; i++) { pin02.toggle(); Thread.sleep(50); } pin00.low(); pin02.low(); Thread.sleep(1000); pin00.high(); System.out.println("Blinking red & green fast..."); for (int i=0; i<100; i++) { pin00.toggle(); pin02.toggle(); Thread.sleep(50); } pin00.high(); pin02.low(); Thread.sleep(100); pin02.high(); Thread.sleep(1000); pin00.low(); pin02.low(); Thread.sleep(100); pin00.pulse(500, true); // set second argument to 'true' use a blocking call pin02.pulse(500, true); // set second argument to 'true' use a blocking call Thread.sleep(100); pin00.pulse(500, false); // set second argument to 'true' use a blocking call Thread.sleep(100); pin02.pulse(500, false); // set second argument to 'true' use a blocking call Thread.sleep(1000); // All on pin00.high(); pin02.high(); Thread.sleep(1000); pin00.low(); pin02.low(); // stop all GPIO activity/threads by shutting down the GPIO controller // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks) gpio.shutdown(); } }
Java
package gpio01; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class SpeedTest { public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - Speed test."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #01 as an output pin and turn on final GpioPinDigitalOutput pin01 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "One", PinState.LOW); final GpioPinDigitalOutput pin02 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "Two", PinState.LOW); final GpioPinDigitalOutput pin03 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03, "Three", PinState.LOW); Thread.sleep(1000); long before = System.currentTimeMillis(); pin01.toggle(); long after = System.currentTimeMillis(); System.out.println("Toggle took " + Long.toString(after - before) + " ms."); Thread.sleep(500); System.out.println("Pulse..."); for (int i=0; i<100; i++) { pin01.pulse(75, false); // set second argument to 'true' use a blocking call pin02.pulse(75, false); // set second argument to 'true' use a blocking call pin03.pulse(75, false); // set second argument to 'true' use a blocking call Thread.sleep(100); // 1/10 s } System.out.println("Done"); pin01.low(); // Off gpio.shutdown(); } }
Java
package rgbled; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import java.io.BufferedReader; import java.io.InputStreamReader; public class RGBLed { private static final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); public static String userInput(String prompt) { String retString = ""; System.err.print(prompt); try { retString = stdin.readLine(); } catch(Exception e) { System.out.println(e); String s; try { s = userInput("<Oooch/>"); } catch(Exception exception) { exception.printStackTrace(); } } return retString; } public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - pin 00, 01 & 02 ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalOutput greenPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "green", PinState.LOW); final GpioPinDigitalOutput bluePin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "blue", PinState.LOW); final GpioPinDigitalOutput redPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "red", PinState.LOW); /* * yellow = R+G * cyan = G+B * magenta = R+B * white = R+G+B */ boolean go = true; while (go) { String s = userInput("R, G, B, or QUIT > "); if ("R".equals(s.toUpperCase())) redPin.toggle(); else if ("G".equals(s.toUpperCase())) greenPin.toggle(); else if ("B".equals(s.toUpperCase())) bluePin.toggle(); else if ("QUIT".equals(s.toUpperCase()) || "Q".equals(s.toUpperCase())) go = false; else System.out.println("Unknown command [" + s + "]"); } // Switch them off redPin.low(); greenPin.low(); bluePin.low(); // stop all GPIO activity/threads by shutting down the GPIO controller // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks) gpio.shutdown(); } }
Java
package relay; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class RelayManager { private final GpioController gpio = GpioFactory.getInstance(); private final GpioPinDigitalOutput pin17; private final GpioPinDigitalOutput pin18; public RelayManager() { System.out.println("GPIO Control - pin 00/#17 and 01/#18 ... started."); System.out.println("(Labelled #17 an #18 on the cobbler.)"); // For a relay it seems that HIGH means NC (Normally Closed)... pin17 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "Relay1", PinState.HIGH); pin18 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "Relay2", PinState.HIGH); } public void set(String device, String status) { GpioPinDigitalOutput pin = ("01".equals(device)?pin17:pin18); if ("on".equals(status)) pin.low(); else pin.high(); } public void shutdown() { gpio.shutdown(); } }
Java
package httpserver; import com.sun.speech.freetts.Voice; import com.sun.speech.freetts.VoiceManager; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import relay.RelayManager; /** * Dedicated HTTP Server. * This is NOT J2EE Compliant, not even CGI. * * Runs the communication between an HTTP client and the * features of the Data server to be displayed remotely. * * Comes with a speech option using "freeTTS" (see http://freetts.sourceforge.net/docs/index.php) */ public class StandaloneHTTPServer { private static boolean verbose = false; private static boolean speak = false; private static RelayManager rm; private VoiceManager voiceManager = VoiceManager.getInstance(); private static Voice voice; private final static String VOICENAME = "kevin16"; public StandaloneHTTPServer() {} public StandaloneHTTPServer(String[] prms) { try { rm = new RelayManager(); } catch (Exception ex) { System.err.println("You're not on the PI, hey?"); ex.printStackTrace(); } // Bind the server String machineName = "localhost"; String port = "9999"; machineName = System.getProperty("http.host", machineName); port = System.getProperty("http.port", port); System.out.println("HTTP Host:" + machineName); System.out.println("HTTP Port:" + port); System.out.println("\nOptions are -verbose=y|[n], -speak=y|[n]"); if (prms != null && prms.length > 0) { for (int i=0; i<prms.length; i++) { // System.out.println("Parameter[" + i + "]=" + prms[i]); if (prms[i].startsWith("-verbose=")) { verbose = prms[i].substring("-verbose=".length()).equals("y"); } else if (prms[i].startsWith("-speak=")) { speak = prms[i].substring("-speak=".length()).equals("y"); } // System.out.println("verbose=" + verbose); } } int _port = 0; try { _port = Integer.parseInt(port); } catch (NumberFormatException nfe) { throw nfe; } if (speak) { voice = voiceManager.getVoice(VOICENAME); voice.allocate(); } if (verbose) System.out.println("Server running from [" + System.getProperty("user.dir") + "]"); // Infinite loop try { ServerSocket ss = new ServerSocket(_port); while (true) { Socket client = ss.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(new OutputStreamWriter(client.getOutputStream())); String line; while ((line = in.readLine()) != null) { if (line.length() == 0) break; else if (line.startsWith("POST /exit") || line.startsWith("GET /exit")) { System.out.println("Received an exit signal"); System.exit(0); } else if (line.startsWith("POST /") || line.startsWith("GET /")) { manageRequest(line, out); } if (verbose) System.out.println("Read:[" + line + "]"); } // out.println(generateContent()); out.flush(); out.close(); in.close(); client.close(); } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } private void manageRequest(String request, PrintWriter out) { out.println(generateContent(request)); } private String generateContent(String request) { String str = ""; // "Content-Type: text/xml\r\n\r\n"; // System.out.println("Managing request [" + request + "]"); String[] elements = request.split(" "); if (elements[0].equals("GET")) { String[] parts = elements[1].split("\\?"); if (parts.length != 2) { String fileName = parts[0]; File data = new File("." + fileName); if (data.exists()) { try { BufferedReader br = new BufferedReader(new FileReader(data)); String line = ""; while (line != null) { line = br.readLine(); if (line != null) str += (line + "\n"); } br.close(); } catch (Exception ex) { ex.printStackTrace(); } } else str = "- There is no parameter is this query -"; } else { if (request.startsWith("GET /relay-access")) { System.out.println("--> " + request); String dev = ""; String status = ""; String[] params = parts[1].split("&"); for (String nv : params) { String[] nvPair = nv.split("="); // System.out.println(nvPair[0] + " = " + nvPair[1]); if (nvPair[0].equals("dev")) dev = nvPair[1]; else if (nvPair[0].equals("status")) status = nvPair[1]; } System.out.println("Setting [" + dev + "] to [" + status + "]"); if (("01".equals(dev) || "02".equals(dev)) && ("on".equals(status) || "off".equals(status))) { if (speak) voice.speak("Turning light " + ("01".equals(dev)?"one":"two") + ", " + status + "!"); try { rm.set(dev, status); } catch (Exception ex) { System.err.println(ex.toString()); } str = "200 OK\r\n"; } else { System.out.println("Unknown dev/status [" + dev + "/" + status + "]"); } } } } else str = "- Not managed -"; return str; } public static void shutdown() { rm.shutdown(); rm.set("01", "off"); rm.set("02", "off"); if (speak) voice.deallocate(); } /** * * @param args see usage */ public static void main(String[] args) { System.out.println("Starting tiny dedicated server"); System.out.println("Use [Ctrl] + [C] to stop it, or POST the following request:"); System.out.println("http://localhost:" + System.getProperty("http.port", "9999") + "/exit"); System.out.println("Data are available at:"); System.out.println("http://localhost:" + System.getProperty("http.port", "9999")); System.out.println("----------------------------------"); if (isHelpRequired(args)) { System.out.println("Usage is: java " + new StandaloneHTTPServer().getClass().getName() + " prms"); System.out.println("\twhere prms can be:"); System.out.println("\t-?\tDisplay this message"); System.out.println("\t-verbose=[y|n] - default is n"); System.out.println("The following variables can be defined in the command line (before the class name):"); System.out.println("\t-Dhttp.port=[port number]\tThe HTTP port to listen to, 9999 by default"); System.out.println("\t-Dhttp.host=[hostname] \tThe HTTP host to bind, localhost by default"); System.out.println("Example:"); System.out.println("java -Dhttp.port=6789 -Dhttp.host=localhost " + new StandaloneHTTPServer().getClass().getName()); System.exit(0); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("\nShutting down nicely..."); shutdown(); } }); new StandaloneHTTPServer(args); } private static boolean isHelpRequired(String[] args) { boolean ret = false; if (args != null) { for (int i=0; i<args.length; i++) { if (args[i].toUpperCase().equals("-H") || args[i].toUpperCase().equals("-HELP") || args[i].toUpperCase().equals("HELP") || args[i].equals("?") || args[i].equals("-?")) { ret = true; break; } } } return ret; } }
Java
package httpserver; import java.io.EOFException; import java.net.HttpURLConnection; import java.net.SocketException; import java.net.URL; public class SmallClient { public static void main(String[] args) throws Exception { int responseCode = 0; try { URL url = new URL("http://raspberrypi:9999/relay-access?dev=01&status=off"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); responseCode = conn.getResponseCode(); System.out.println("Done. (" + responseCode + ")"); } catch (EOFException eofe) { System.out.println("EOFException"); // That's ok, nothing is returned } catch (SocketException se) { System.out.println("SocketException"); // OK too. } catch (Exception ex) { ex.printStackTrace(); } System.out.println("Response Code:" + responseCode); } }
Java
package relay.gpio; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; public class GPIOController { private GpioController gpio = null; private OneRelay relay = null; public GPIOController() { this.gpio = GpioFactory.getInstance(); this.relay = new OneRelay(this.gpio, RaspiPin.GPIO_00, "Relay01"); } public void shutdown() { this.gpio.shutdown(); } public void switchRelay(boolean on) { if (on) relay.on(); else relay.off(); } }
Java
package relay.gpio; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; public class OneRelay { private GpioPinDigitalOutput led = null; private String name; public OneRelay(GpioController gpio, Pin pin, String name) { this.name = name; led = gpio.provisionDigitalOutputPin(pin, name, PinState.HIGH); // Begin HIGH for a relay } public void on() { if ("true".equals(System.getProperty("verbose", "false"))) System.out.println(this.name + " is on."); led.low(); } public void off() { if ("true".equals(System.getProperty("verbose", "false"))) System.out.println(this.name + " is off."); led.high(); } }
Java
package relay.gpio; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; public interface RaspberryPIEventListener { public void manageEvent(GpioPinDigitalStateChangeEvent event); }
Java
package relay; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.json.JSONObject; import relay.email.EmailReceiver; import relay.email.EmailSender; public class SampleMain { private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); private static boolean verbose = "true".equals(System.getProperty("verbose", "false")); /** * Invoked like: * java pi4j.email.SampleMain [-verbose] -send:google -receive:yahoo * * This will send emails using google, and receive using yahoo. * Do check the file email.properties for the different values associated with email servers. * * NO GPIO INTERACTION in this one. * * @param args See above */ public static void main(String[] args) { // String provider = "yahoo"; String providerSend = "oracle"; // String provider = "oracle"; // provider = "yahoo"; String providerReceive = "oracle"; // provider = "oracle"; for (int i=0; i<args.length; i++) { if ("-verbose".equals(args[i])) { verbose = true; System.setProperty("verbose", "true"); } else if (args[i].startsWith("-send:")) providerSend = args[i].substring("-send:".length()); else if (args[i].startsWith("-receive:")) providerReceive =args[i].substring("-receive:".length()); else if ("-help".equals(args[i])) { System.out.println("Usage:"); System.out.println(" java pi4j.email.SampleMain -verbose -send:google -receive:yahoo -help"); System.exit(0); } } final EmailSender sender = new EmailSender(providerSend); Thread senderThread = new Thread() { public void run() { try { for (int i=0; i<10; i++) { System.out.println("Sending..."); sender.send(new String[] { "olivier@lediouris.net", "webmaster@lediouris.net", "olivier.lediouris@gmail.com", "olivier_le_diouris@yahoo.com", "olivier.lediouris@oracle.com" }, "PI Request", "{ operation: 'see-attached-" + Integer.toString(i + 1) + "' }", "P8150115.JPG"); System.out.println("Sent."); Thread.sleep(60000L); // 1 minute } System.out.println("Exiting..."); sender.send(new String[] { "olivier@lediouris.net", "webmaster@lediouris.net", "olivier.lediouris@gmail.com", "olivier_le_diouris@yahoo.com", "olivier.lediouris@oracle.com" }, "PI Request", "{ operation: 'exit' }"); System.out.println("Bye."); } catch (Exception ex) { ex.printStackTrace(); } } }; senderThread.start(); // Bombarding if (args.length > 1) providerSend = args[1]; EmailReceiver receiver = new EmailReceiver(providerReceive); // For Google, pop must be explicitely enabled at the account level try { boolean keepLooping = true; while (keepLooping) { List<String> received = receiver.receive(); if (verbose || received.size() > 0) System.out.println(SDF.format(new Date()) + " - Retrieved " + received.size() + " message(s)."); for (String s : received) { // System.out.println(s); String operation = ""; try { JSONObject json = new JSONObject(s); operation = json.getString("operation"); } catch (Exception ex) { System.err.println(ex.getMessage()); System.err.println("Message is [" + s + "]"); } if ("exit".equals(operation)) { keepLooping = false; System.out.println("Will exit next batch."); // break; } else { System.out.println("Operation: [" + operation + "], sent for processing."); try { Thread.sleep(1000L); } catch (InterruptedException ie) { ie.printStackTrace(); } } } } System.out.println("Done."); } catch (Exception ex) { ex.printStackTrace(); } } }
Java
package relay.email; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Set; import javax.mail.Address; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.InternetAddress; import javax.mail.search.AndTerm; import javax.mail.search.FlagTerm; import javax.mail.search.FromStringTerm; import javax.mail.search.OrTerm; import javax.mail.search.SearchTerm; import javax.mail.search.SubjectTerm; public class EmailReceiver { private static String protocol; private static int outgoingPort; private static int incomingPort; private static String username; private static String password; private static String outgoing; private static String incoming; private static String replyto; private static boolean smtpauth; private static String sendEmailsTo; private static String acceptEmailsFrom; private static String acceptSubject; private static String ackSubject; private static boolean verbose = "true".equals(System.getProperty("verbose", "false")); private EmailSender emailSender = null; // For Ack private String provider = null; public EmailReceiver(String provider) throws RuntimeException { this.provider = provider; EmailReceiver.protocol = ""; EmailReceiver.outgoingPort = 0; EmailReceiver.incomingPort = 0; EmailReceiver.username = ""; EmailReceiver.password = ""; EmailReceiver.outgoing = ""; EmailReceiver.incoming = ""; EmailReceiver.replyto = ""; EmailReceiver.smtpauth = false; EmailReceiver.sendEmailsTo = ""; EmailReceiver.acceptEmailsFrom = ""; EmailReceiver.acceptSubject = ""; EmailReceiver.ackSubject = ""; Properties props = new Properties(); String propFile = "email.properties"; try { FileInputStream fis = new FileInputStream(propFile); props.load(fis); } catch (Exception e) { System.out.println("email.properies file problem..."); throw new RuntimeException("File not found:email.properies"); } EmailReceiver.sendEmailsTo = props.getProperty("pi.send.emails.to"); EmailReceiver.acceptEmailsFrom = props.getProperty("pi.accept.emails.from"); EmailReceiver.acceptSubject = props.getProperty("pi.email.subject"); EmailReceiver.ackSubject = props.getProperty("pi.ack.subject"); EmailReceiver.protocol = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.protocol"); EmailReceiver.outgoingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server.port", "0")); EmailReceiver.incomingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server.port", "0")); EmailReceiver.username = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.username", ""); EmailReceiver.password = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.password", ""); EmailReceiver.outgoing = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server", ""); EmailReceiver.incoming = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server", ""); EmailReceiver.replyto = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.replyto", ""); EmailReceiver.smtpauth = "true".equals(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.smtpauth", "false")); if (verbose) { System.out.println("Protocol:" + EmailReceiver.protocol); System.out.println("Usr/pswd:" + EmailReceiver.username + "/" + EmailReceiver.password); } } private static SearchTerm[] buildSearchTerm(String str) { String[] sa = str.split(","); List<SearchTerm> lst = new ArrayList<SearchTerm>(); for (String s : sa) lst.add(new FromStringTerm(s.trim())); SearchTerm[] sta = new SearchTerm[lst.size()]; sta = lst.toArray(sta); return sta; } private Properties setProps() { Properties props = new Properties(); props.put("mail.debug", verbose?"true":"false"); // TASK smtp should be irrelevant for a receiver props.put("mail.smtp.host", EmailReceiver.outgoing); props.put("mail.smtp.port", Integer.toString(EmailReceiver.outgoingPort)); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // See http://www.oracle.com/technetwork/java/faq-135477.html#yahoomail // props.put("mail.smtp.starttls.required", "true"); props.put("mail.smtp.ssl.enable", "true"); if ("pop3".equals(EmailReceiver.protocol)) { props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.pop3.socketFactory.fallback", "false"); props.setProperty("mail.pop3.port", Integer.toString(EmailReceiver.incomingPort)); props.setProperty("mail.pop3.socketFactory.port", Integer.toString(EmailReceiver.incomingPort)); } if ("imap".equals(protocol)) { props.setProperty("mail.imap.starttls.enable", "false"); // Use SSL props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.imap.socketFactory.fallback", "false"); props.setProperty("mail.imap.port", Integer.toString(EmailReceiver.incomingPort)); props.setProperty("mail.imap.socketFactory.port", Integer.toString(EmailReceiver.incomingPort)); props.setProperty("mail.imaps.class", "com.sun.mail.imap.IMAPSSLStore"); } return props; } public boolean isAuthRequired() { return EmailReceiver.smtpauth; } public String getUserName() { return EmailReceiver.username; } public String getPassword() { return EmailReceiver.password; } public String getReplyTo() { return EmailReceiver.replyto; } public String getIncomingServer() { return EmailReceiver.incoming; } public String getOutgoingServer() { return EmailReceiver.outgoing; } public List<String> receive() throws Exception { return receive(null); } public List<String> receive(String dir) throws Exception { if (verbose) System.out.println("Receiving..."); List<String> messList = new ArrayList<String>(); Store store = null; Folder folder = null; try { // Properties props = System.getProperties(); Properties props = setProps(); if (verbose) { Set<Object> keys = props.keySet(); for (Object o : keys) System.out.println(o.toString() + ":" + props.get(o).toString()); } if (verbose) System.out.println("Getting session..."); // Session session = Session.getInstance(props, null); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); session.setDebug(verbose); if (verbose) System.out.println("Session established."); store = session.getStore(EmailReceiver.protocol); if (EmailReceiver.incomingPort == 0) store.connect(EmailReceiver.incoming, EmailReceiver.username, EmailReceiver.password); else store.connect(EmailReceiver.incoming, EmailReceiver.incomingPort, EmailReceiver.username, EmailReceiver.password); if (verbose) System.out.println("Connected to store"); folder = store.getDefaultFolder(); if (folder == null) throw new RuntimeException("No default folder"); folder = store.getFolder("INBOX"); if (folder == null) throw new RuntimeException("No INBOX"); folder.open(Folder.READ_WRITE); if (verbose) System.out.println("Connected... filtering, please wait."); SearchTerm st = new AndTerm(new SearchTerm[] { new OrTerm(buildSearchTerm(sendEmailsTo)), new SubjectTerm(acceptSubject), new FlagTerm(new Flags(Flags.Flag.SEEN), false) }); // st = new SubjectTerm("PI Request"); Message msgs[] = folder.search(st); // Message msgs[] = folder.getMessages(); if (verbose) System.out.println("Search completed, " + msgs.length + " message(s)."); for (int msgNum=0; msgNum<msgs.length; msgNum++) { try { Message mess = msgs[msgNum]; Address from[] = mess.getFrom(); String sender = ""; try { sender = from[0].toString(); } catch(Exception exception) { exception.printStackTrace(); } // System.out.println("Message from [" + sender + "], subject [" + subject + "], content [" + mess.getContent().toString().trim() + "]"); if (true) { if (!mess.isSet(javax.mail.Flags.Flag.SEEN) && !mess.isSet(javax.mail.Flags.Flag.DELETED)) { String txtMess = printMessage(mess, dir); messList.add(txtMess); mess.setFlag(javax.mail.Flags.Flag.SEEN, true); mess.setFlag(javax.mail.Flags.Flag.DELETED, true); // Send an ack - by email. if (this.emailSender == null) this.emailSender = new EmailSender(this.provider); this.emailSender.send(new String[] { sender }, ackSubject, "Your request [" + txtMess.trim() + "] is being taken care of."); if (verbose) System.out.println("Sent an ack to " + sender); } else { if (verbose) System.out.println("Old message in your inbox..., received " + mess.getReceivedDate().toString()); } } } catch(Exception ex) { // System.err.println(ex.getMessage()); ex.printStackTrace(); } } } catch(Exception ex) { throw ex; } finally { try { if (folder != null) folder.close(true); if (store != null) store.close(); } catch(Exception ex2) { System.err.println("Finally ..."); ex2.printStackTrace(); } } return messList; } public static String printMessage(Message message, String dir) { String ret = ""; try { String from = ((InternetAddress)message.getFrom()[0]).getPersonal(); if(from == null) from = ((InternetAddress)message.getFrom()[0]).getAddress(); if (verbose) System.out.println("From: " + from); String subject = message.getSubject(); if (verbose) System.out.println("Subject: " + subject); Part messagePart = message; Object content = messagePart.getContent(); if (content instanceof Multipart) { // messagePart = ((Multipart)content).getBodyPart(0); int nbParts = ((Multipart)content).getCount(); if (verbose) System.out.println("[ Multipart Message ], " + nbParts + " part(s)."); for (int i=0; i<nbParts; i++) { messagePart = ((Multipart)content).getBodyPart(i); if (messagePart.getContentType().toUpperCase().startsWith("APPLICATION/OCTET-STREAM")) { if (verbose) System.out.println(messagePart.getContentType() + ":" + messagePart.getFileName()); InputStream is = messagePart.getInputStream(); String newFileName = ""; if (dir != null) newFileName = dir + File.separator; newFileName += messagePart.getFileName(); FileOutputStream fos = new FileOutputStream(newFileName); ret = messagePart.getFileName(); if (verbose) System.out.println("Downloading " + messagePart.getFileName() + "..."); copy(is, fos); if (verbose) System.out.println("...done."); } else // text/plain, text/html { if (verbose) System.out.println("-- Part #" + i + " --, " + messagePart.getContentType().replace('\n', ' ').replace('\r', ' ').replace("\b", "").trim()); InputStream is = messagePart.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = ""; while (line != null) { line = br.readLine(); if (line != null) { if (verbose) System.out.println("[" + line + "]"); if (messagePart.getContentType().toUpperCase().startsWith("TEXT/PLAIN")) ret += line; } } br.close(); if (verbose) System.out.println("-------------------"); } } } else { // System.out.println(" .Message is a " + content.getClass().getName()); // System.out.println("Content:"); // System.out.println(content.toString()); ret = content.toString(); } if (verbose) System.out.println("-----------------------------"); } catch(Exception ex) { ex.printStackTrace(); } return ret; } private static void copy(InputStream in, OutputStream out) throws IOException { synchronized(in) { synchronized(out) { byte buffer[] = new byte[256]; while (true) { int bytesRead = in.read(buffer); if(bytesRead == -1) break; out.write(buffer, 0, bytesRead); } } } } }
Java
package relay.email; import com.sun.mail.smtp.SMTPTransport; import java.io.FileInputStream; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class EmailSender { private static String protocol; private static int outgoingPort; private static int incomingPort; private static String username; private static String password; private static String outgoing; private static String incoming; private static String replyto; private static boolean smtpauth; private static String sendEmailsTo; private static String eventSubject; private static boolean verbose = "true".equals(System.getProperty("verbose", "false")); public EmailSender(String provider) throws RuntimeException { EmailSender.protocol = ""; EmailSender.outgoingPort = 0; EmailSender.incomingPort = 0; EmailSender.username = ""; EmailSender.password = ""; EmailSender.outgoing = ""; EmailSender.incoming = ""; EmailSender.replyto = ""; EmailSender.smtpauth = false; EmailSender.sendEmailsTo = ""; EmailSender.eventSubject = ""; Properties props = new Properties(); String propFile = "email.properties"; try { FileInputStream fis = new FileInputStream(propFile); props.load(fis); } catch (Exception e) { System.out.println("email.properies file problem..."); throw new RuntimeException("File not found:email.properies"); } EmailSender.sendEmailsTo = props.getProperty("pi.send.emails.to"); EmailSender.eventSubject = props.getProperty("pi.event.subject"); EmailSender.protocol = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.protocol"); EmailSender.outgoingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server.port", "0")); EmailSender.incomingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server.port", "0")); EmailSender.username = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.username", ""); EmailSender.password = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.password", ""); EmailSender.outgoing = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server", ""); EmailSender.incoming = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server", ""); EmailSender.replyto = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.replyto", ""); EmailSender.smtpauth = "true".equals(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.smtpauth", "false")); if (verbose) { System.out.println("-------------------------------------"); System.out.println("Protocol : " + EmailSender.protocol); System.out.println("Usr/pswd : " + EmailSender.username + "/" + EmailSender.password); System.out.println("Incoming server: " + EmailSender.incoming + ":" + EmailSender.incomingPort); System.out.println("Outgoing server: " + EmailSender.outgoing + ":" + EmailSender.outgoingPort); System.out.println("replyto : " + EmailSender.replyto); System.out.println("SMTPAuth : " + EmailSender.smtpauth); System.out.println("-------------------------------------"); } } public boolean isAuthRequired() { return EmailSender.smtpauth; } public String getUserName() { return EmailSender.username; } public String getPassword() { return EmailSender.password; } public String getReplyTo() { return EmailSender.replyto; } public String getIncomingServer() { return EmailSender.incoming; } public String getOutgoingServer() { return EmailSender.outgoing; } public String getEmailDest() { return EmailSender.sendEmailsTo; } public String getEventSubject() { return EmailSender.eventSubject; } public void send(String[] dest, String subject, String content) throws MessagingException, AddressException { send(dest, subject, content, null); } public void send(String[] dest, String subject, String content, String attachment) throws MessagingException, AddressException { Properties props = setProps(); // Session session = Session.getDefaultInstance(props, auth); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); session.setDebug(verbose); Transport tr = session.getTransport("smtp"); if (!(tr instanceof SMTPTransport)) System.out.println("This is NOT an SMTPTransport:[" + tr.getClass().getName() + "]"); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(EmailSender.replyto)); if (dest == null || dest.length == 0) throw new RuntimeException("Need at least one recipient."); msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(dest[0])); for (int i=1; i<dest.length; i++) msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(dest[i])); msg.setSubject(subject); if (attachment != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(content); Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = attachment; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Send the complete message parts msg.setContent(multipart); } else { msg.setText(content != null ? content : ""); msg.setContent(content, "text/plain"); } msg.saveChanges(); if (verbose) System.out.println("sending:[" + content + "], " + Integer.toString(content.length()) + " characters"); Transport.send(msg); } private Properties setProps() { Properties props = new Properties(); props.put("mail.debug", verbose?"true":"false"); props.put("mail.smtp.host", EmailSender.outgoing); props.put("mail.smtp.port", Integer.toString(EmailSender.outgoingPort)); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // See http://www.oracle.com/technetwork/java/faq-135477.html#yahoomail // props.put("mail.smtp.starttls.required", "true"); props.put("mail.smtp.ssl.enable", "true"); return props; } }
Java
package relay; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import java.io.FileReader; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Properties; import org.json.JSONObject; import relay.email.EmailReceiver; import relay.email.EmailSender; import relay.gpio.GPIOController; import relay.gpio.RaspberryPIEventListener; public class PIControllerMain implements RaspberryPIEventListener { private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); private static boolean verbose = "true".equals(System.getProperty("verbose", "false")); private static String providerSend = "google"; private static String providerReceive = "google"; EmailSender sender = null; /** * Invoked like: * java relay.email.PIControllerMain [-verbose] -send:google -receive:yahoo -help * * This will send emails using google, and receive using yahoo. * Default values are: * java pi4j.email.PIControllerMain -send:google -receive:google * * Do check the file email.properties for the different values associated with email servers. * * @param args See above * * To try it: * send email to the right destination (like olivier.lediouris@gmail.com, see in email.properties) with a plain text payload like * { 'operation':'turn-relay-on' } * or * { 'operation':'turn-relay-off' } * * Subject: 'PI Request' */ public static void main(String[] args) { for (int i=0; i<args.length; i++) { if ("-verbose".equals(args[i])) { verbose = true; System.setProperty("verbose", "true"); } else if (args[i].startsWith("-send:")) providerSend = args[i].substring("-send:".length()); else if (args[i].startsWith("-receive:")) providerReceive =args[i].substring("-receive:".length()); else if ("-help".equals(args[i])) { System.out.println("Usage:"); System.out.println(" java relay.email.PIControllerMain -verbose -send:google -receive:yahoo -help"); System.exit(0); } } final GPIOController piController = new GPIOController(); EmailReceiver receiver = new EmailReceiver(providerReceive); // For Google, pop must be explicitely enabled at the account level Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { piController.switchRelay(false); piController.shutdown(); System.out.println("\nExiting nicely."); } }); try { String from = ""; try { Properties props = new Properties(); props.load(new FileReader("email.properties")); String emitters = props.getProperty("pi.accept.emails.from"); from = ", from " + emitters; } catch (Exception ex) { ex.printStackTrace(); } System.out.println("Waiting for instructions" + from + "."); boolean keepLooping = true; while (keepLooping) { List<String> received = receiver.receive(); if (verbose || received.size() > 0) System.out.println(SDF.format(new Date()) + " - Retrieved " + received.size() + " message(s)."); for (String s : received) { // System.out.println(s); String operation = ""; try { JSONObject json = new JSONObject(s); operation = json.getString("operation"); } catch (Exception ex) { System.err.println(ex.getMessage()); System.err.println("Message is [" + s + "]"); } if ("exit".equals(operation)) { keepLooping = false; System.out.println("Will exit next batch."); // break; } else { if ("turn-relay-on".equals(operation)) { System.out.println("Turning relay on"); piController.switchRelay(true); } else if ("turn-relay-off".equals(operation)) { System.out.println("Turning relay off"); piController.switchRelay(false); } try { Thread.sleep(1000L); } catch (InterruptedException ie) { ie.printStackTrace(); } } } } piController.shutdown(); System.out.println("Done."); System.exit(0); } catch (Exception ex) { ex.printStackTrace(); } } public void manageEvent(GpioPinDigitalStateChangeEvent event) { if (sender == null) sender = new EmailSender(providerSend); try { String mess = "{ pin: '" + event.getPin() + "', state:'" + event.getState() + "' }"; System.out.println("Sending:" + mess); sender.send(sender.getEmailDest().split(","), sender.getEventSubject(), mess); } catch (Exception ex) { ex.printStackTrace(); } } }
Java
package relay; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class RelayManager { private final GpioController gpio = GpioFactory.getInstance(); private final GpioPinDigitalOutput pin17; private final GpioPinDigitalOutput pin18; public RelayManager() { System.out.println("GPIO Control - pin 00/#17 and 01/#18 ... started."); System.out.println("(Labelled #17 an #18 on the cobbler.)"); // For a relay it seems that HIGH means NC (Normally Closed)... pin17 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "Relay1", PinState.HIGH); pin18 = null; // gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "Relay2", PinState.HIGH); } public void set(String device, String status) { GpioPinDigitalOutput pin = ("00".equals(device)?pin17:pin18); if ("on".equals(status)) pin.low(); else pin.high(); } public String getStatus(String dev) { String status = "unknown"; GpioPinDigitalOutput pin = ("00".equals(dev)?pin17:pin18); status = pin.isHigh() ? "off" : "on"; return status; } public void shutdown() { gpio.shutdown(); } }
Java
package ws; import adc.ADCContext; import adc.ADCListener; import adc.ADCObserver; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import relay.RelayManager; public class WebSocketFeeder { private final static boolean DEBUG = "true".equals(System.getProperty("debug", "false")); private ADCObserver.MCP3008_input_channels channel = null; private static boolean keepWorking = true; private static WebSocketClient webSocketClient = null; private static RelayManager rm; private static ADCObserver obs = null; public WebSocketFeeder(int ch) throws Exception { channel = findChannel(ch); try { rm = new RelayManager(); rm.set("00", "on"); } catch (Exception ex) { System.err.println("You're not on the PI, hey?"); ex.printStackTrace(); } String wsUri = System.getProperty("ws.uri", "ws://localhost:9876/"); initWebSocketConnection(wsUri); obs = new ADCObserver(channel); // Note: We could instantiate more than one observer (on several channels). ADCContext.getInstance().addListener(new ADCListener() { @Override public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue) { if (inputChannel.equals(channel)) { int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111] if (DEBUG) System.out.println("readAdc:" + Integer.toString(newValue) + " (0x" + lpad(Integer.toString(newValue, 16).toUpperCase(), "0", 2) + ", 0&" + lpad(Integer.toString(newValue, 2), "0", 8) + ")"); System.out.println("Volume:" + volume + "% (" + newValue + ")"); try { webSocketClient.send(Integer.toString(volume)); } catch (Exception ex) { ex.printStackTrace(); } // Turn relay off above 75% if (volume > 75) { String status = rm.getStatus("00"); // System.out.println("Relay is:" + status); if ("on".equals(status)) { System.out.println("Turning relay off!"); try { rm.set("00", "off"); } catch (Exception ex) { System.err.println(ex.toString()); } } } } } }); obs.start(); } private void initWebSocketConnection(String serverURI) { try { webSocketClient = new WebSocketClient(new URI(serverURI)) { @Override public void onOpen(ServerHandshake serverHandshake) { System.out.println("WS On Open"); } @Override public void onMessage(String string) { // System.out.println("WS On Message"); } @Override public void onClose(int i, String string, boolean b) { System.out.println("WS On Close"); } @Override public void onError(Exception exception) { System.out.println("WS On Error"); exception.printStackTrace(); } }; webSocketClient.connect(); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) throws Exception { int channel = 0; if (args.length > 0) channel = Integer.parseInt(args[0]); System.out.println("Listening to MCP3008 channel " + channel); // System.out.println("Adding shutdown hook"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Shutting down nicely."); if (obs != null) { System.out.println("Stopping observer..."); obs.stop(); } keepWorking = false; System.out.println("Closing WebSocket client..."); webSocketClient.close(); try { System.out.println("Turning power off..."); rm.set("00", "off"); rm.shutdown(); } catch (Exception ex) { System.err.println(ex.toString()); } System.out.println("Done."); } }); new WebSocketFeeder(channel); } private static ADCObserver.MCP3008_input_channels findChannel(int ch) throws IllegalArgumentException { ADCObserver.MCP3008_input_channels channel = null; switch (ch) { case 0: channel = ADCObserver.MCP3008_input_channels.CH0; break; case 1: channel = ADCObserver.MCP3008_input_channels.CH1; break; case 2: channel = ADCObserver.MCP3008_input_channels.CH2; break; case 3: channel = ADCObserver.MCP3008_input_channels.CH3; break; case 4: channel = ADCObserver.MCP3008_input_channels.CH4; break; case 5: channel = ADCObserver.MCP3008_input_channels.CH5; break; case 6: channel = ADCObserver.MCP3008_input_channels.CH6; break; case 7: channel = ADCObserver.MCP3008_input_channels.CH7; break; default: throw new IllegalArgumentException("No channel " + Integer.toString(ch)); } return channel; } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
Java
package adc; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * Read an Analog to Digital Converter */ public class ADCObserver { private final static boolean DISPLAY_DIGIT = false; // Note: "Mismatch" 23-24. The wiring says DOUT->#23, DIN->#24 // 23: DOUT on the ADC is IN on the GPIO. ADC:Slave, GPIO:Master // 24: DIN on the ADC, OUT on the GPIO. Same reason as above. // SPI: Serial Peripheral Interface private static Pin spiClk = RaspiPin.GPIO_01; // Pin #18, clock private static Pin spiMiso = RaspiPin.GPIO_04; // Pin #23, data in. MISO: Master In Slave Out private static Pin spiMosi = RaspiPin.GPIO_05; // Pin #24, data out. MOSI: Master Out Slave In private static Pin spiCs = RaspiPin.GPIO_06; // Pin #25, Chip Select public static enum MCP3008_input_channels { CH0(0), CH1(1), CH2(2), CH3(3), CH4(4), CH5(5), CH6(6), CH7(7); private int ch; MCP3008_input_channels(int chNum) { this.ch = chNum; } public int ch() { return this.ch; } } private MCP3008_input_channels[] adcChannel; // Between 0 and 7, 8 channels on the MCP3008 private static GpioPinDigitalInput misoInput = null; private static GpioPinDigitalOutput mosiOutput = null; private static GpioPinDigitalOutput clockOutput = null; private static GpioPinDigitalOutput chipSelectOutput = null; private boolean go = true; public ADCObserver(MCP3008_input_channels channel) { this(new MCP3008_input_channels[] { channel }) ; } public ADCObserver(MCP3008_input_channels[] channel) { adcChannel = channel; } public void start() { GpioController gpio = GpioFactory.getInstance(); mosiOutput = gpio.provisionDigitalOutputPin(spiMosi, "MOSI", PinState.LOW); clockOutput = gpio.provisionDigitalOutputPin(spiClk, "CLK", PinState.LOW); chipSelectOutput = gpio.provisionDigitalOutputPin(spiCs, "CS", PinState.LOW); misoInput = gpio.provisionDigitalInputPin(spiMiso, "MISO"); int lastRead[] = new int[adcChannel.length]; for (int i=0; i<lastRead.length; i++) lastRead[i] = 0; int tolerance = 5; while (go) { for (int i=0; i<adcChannel.length; i++) { int adc = readAdc(adcChannel[i]); // System.out.println("ADC:" + adc); int postAdjust = Math.abs(adc - lastRead[i]); if (postAdjust > tolerance) { ADCContext.getInstance().fireValueChanged(adcChannel[i], adc); lastRead[i] = adc; } } try { Thread.sleep(100L); } catch (InterruptedException ie) { ie.printStackTrace(); } } System.out.println("Shutting down..."); gpio.shutdown(); } public void stop() { go = false; } private int readAdc(MCP3008_input_channels channel) { chipSelectOutput.high(); clockOutput.low(); chipSelectOutput.low(); int adccommand = channel.ch(); adccommand |= 0x18; // 0x18: 00011000 adccommand <<= 3; // Send 5 bits: 8 - 3. 8 input channels on the MCP3008. for (int i=0; i<5; i++) // { if ((adccommand & 0x80) != 0x0) // 0x80 = 0&10000000 mosiOutput.high(); else mosiOutput.low(); adccommand <<= 1; clockOutput.high(); clockOutput.low(); } int adcOut = 0; for (int i=0; i<12; i++) // Read in one empty bit, one null bit and 10 ADC bits { clockOutput.high(); clockOutput.low(); adcOut <<= 1; if (misoInput.isHigh()) { // System.out.println(" " + misoInput.getName() + " is high (i:" + i + ")"); // Shift one bit on the adcOut adcOut |= 0x1; } if (DISPLAY_DIGIT) System.out.println("ADCOUT: 0x" + Integer.toString(adcOut, 16).toUpperCase() + ", 0&" + Integer.toString(adcOut, 2).toUpperCase()); } chipSelectOutput.high(); adcOut >>= 1; // Drop first bit return adcOut; } }
Java
package adc; import java.util.ArrayList; import java.util.List; public class ADCContext { private static ADCContext instance = null; private List<ADCListener> listeners = null; private ADCContext() { listeners = new ArrayList<ADCListener>(); } public synchronized static ADCContext getInstance() { if (instance == null) instance = new ADCContext(); return instance; } public void addListener(ADCListener listener) { if (!listeners.contains(listener)) listeners.add(listener); } public void removeListener(ADCListener listener) { if (listeners.contains(listener)) listeners.remove(listener); } public List<ADCListener> getListeners() { return this.listeners; } public void fireValueChanged(ADCObserver.MCP3008_input_channels channel, int newValue) { for (ADCListener listener : listeners) listener.valueUpdated(channel, newValue); } }
Java
package adc; public class ADCListener { public void valueUpdated(ADCObserver.MCP3008_input_channels channel, int newValue) {}; }
Java
package adc.utils; import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; public class EscapeSeq { public final static char ESC = '\u001b'; // (char) 27; public final static String ANSI_BLACK = "0"; public final static String ANSI_RED = "1"; public final static String ANSI_GREEN = "2"; public final static String ANSI_YELLOW = "3"; public final static String ANSI_BLUE = "4"; public final static String ANSI_MAGENTA = "5"; public final static String ANSI_CYAN = "6"; public final static String ANSI_WHITE = "7"; public static final String ANSI_CLS = ESC + "[2J"; public static final String ANSI_HOME = ESC + "[H"; // 0,0 public static final String ANSI_HEAD = ESC + "[1G"; // Start of current line, position 1 public static final String ANSI_NORMAL = ESC + "[0m"; public static final String ANSI_BOLD = ESC + "[1m"; public static final String ANSI_FAINT = ESC + "[2m"; public static final String ANSI_ITALIC = ESC + "[3m"; public static final String ANSI_UNDERLINE = ESC + "[4m"; public static final String ANSI_BLINK = ESC + "[5m"; public static final String ANSI_BLINK_FAST = ESC + "[6m"; public static final String ANSI_REVERSE = ESC + "[7m"; public static final String ANSI_CONCEAL = ESC + "[8m"; public static final String ANSI_CROSSED_OUT = ESC + "[9m"; public static final String ANSI_DEFAULT_TEXT = ESC + "[39m"; public static final String ANSI_DEFAULT_BACKGROUND = ESC + "[49m"; private final static String[] SOME_TEXT = { "What happens when the boat sends an email:", "On the boat, you compose your email, and you put it in your outbox.", "Then you turn your SSB on, and you use the SailMail client program to contact a land SailMail station.", "When the contact is established, the messages sitting in the outbox go through the modem and the SSB to ", "be streamed to the land station. On receive, the land station then turns the messages back into digital files,", "and uses its Internet connection to post them on the web. From there, it's the usual email story." }; public static final String ANSI_AT55 = ESC + "[10;10H"; // Actually 10, 10 public static final String ANSI_WHITEONBLUE = ESC + "[37;44m"; public static String ansiSetBackGroundColor(String color) { // ESC[40-47 return ESC + "[4" + color + "m"; } public static String ansiSetTextColor(String color) { // ESC[30-37 return ESC + "[3" + color + "m"; } public static String ansiSetTextAndBackgroundColor(String text, String bg) { // ESC[30-37;40-47 return ESC + "[3" + text + ";4" + bg + "m"; } public static String ansiLocate(int x, int y) { return ESC + "[" + Integer.toString(y) + ";" + Integer.toString(x) + "H"; // Actually Y, X } // An example public static void main(String[] args) { String str80 = " "; AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); // Display 5 rows, like an horizontal bar chart for (int i=0; i<20; i++) { int value1 = (int)Math.round(Math.random() * 80); int value2 = (int)Math.round(Math.random() * 80); int value3 = (int)Math.round(Math.random() * 80); int value4 = (int)Math.round(Math.random() * 80); int value5 = (int)Math.round(Math.random() * 80); String str1 = ""; for (int j=0; j<value1; j++) str1 += "."; String str2 = ""; for (int j=0; j<value2; j++) str2 += "."; String str3 = ""; for (int j=0; j<value3; j++) str3 += "."; String str4 = ""; for (int j=0; j<value4; j++) str4 += "."; String str5 = ""; for (int j=0; j<value5; j++) str5 += "."; str1 = superpose(str1, "Cell 1:" + Integer.toString(value1)); str2 = superpose(str2, "Cell 2:" + Integer.toString(value2)); str3 = superpose(str3, "Cell 3:" + Integer.toString(value3)); str4 = superpose(str4, "Cell 4:" + Integer.toString(value4)); str5 = superpose(str5, "Cell 5:" + Integer.toString(value5)); // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ansiLocate(0, 1) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 1) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_RED) + ANSI_BOLD + str1 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 2) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 2) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_WHITE) + ANSI_BOLD + str2 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 3) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 3) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_YELLOW) + ANSI_BOLD + str3 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 4) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 4) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_GREEN) + ANSI_BOLD + str4 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); AnsiConsole.out.println(ansiLocate(0, 5) + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT + str80); AnsiConsole.out.println(ansiLocate(0, 5) + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLUE) + ANSI_BOLD + str5 + ANSI_NORMAL + ANSI_DEFAULT_BACKGROUND + ANSI_DEFAULT_TEXT); try { Thread.sleep(1000L); } catch (Exception ex) {} } System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } public static String superpose(String orig, String override) { byte[] ret = orig.getBytes(); for (int i=0; i<Math.min(orig.length(), override.length()); i++) ret[i] = (byte)override.charAt(i); return new String(ret); } public static void main_(String[] args) { AnsiConsole.systemInstall(); AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_AT55 + ANSI_REVERSE + "10,10 reverse : Hello world" + ANSI_NORMAL); AnsiConsole.out.println(ANSI_HOME + ANSI_WHITEONBLUE + "WhiteOnBlue : Hello world" + ANSI_NORMAL); AnsiConsole.out.print(ANSI_BOLD + "Bold : Press return..." + ANSI_NORMAL); try { System.in.read(); } catch (Exception e) { } // AnsiConsole.out.println(ANSI_CLS); AnsiConsole.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); AnsiConsole.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal text and " + ANSI_WHITEONBLUE + "bold" + ANSI_NORMAL + " text."); System.out.println(ANSI_NORMAL + "Normal " + ansiSetTextColor(ANSI_YELLOW) + "yellow" + ANSI_NORMAL + " text and " + ansiSetTextAndBackgroundColor(ANSI_WHITE, ANSI_BLACK) + "bold" + ANSI_NORMAL + " text."); for (String line : SOME_TEXT) { System.out.print(ANSI_HEAD + line); try { Thread.sleep(1000); } catch (Exception ex) {} } System.out.println(); System.out.println(ansiSetTextAndBackgroundColor(ANSI_GREEN, ANSI_RED) + "this concludes the " + ansiSetTextColor(ANSI_WHITE) + "Jansi" + ansiSetTextColor(ANSI_GREEN) + " demo" + ANSI_NORMAL); } }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.test; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; public class PlugtestSeparateResponseCoapServer implements CoapServer { private static final int PORT = 5683; static int counter = 0; CoapResponse response = null; CoapServerChannel channel = null; int separateResponseTimeMs = 4000; public void start(int separateResponseTimeMs){ CoapChannelManager channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(this, PORT); this.separateResponseTimeMs = separateResponseTimeMs; } @Override public CoapServer onAccept(CoapRequest request) { System.out.println("Accept connection..."); return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { System.out.println("Received message: " + request.toString()); this.channel = channel; response = channel.createSeparateResponse(request, CoapResponseCode.Content_205); (new Thread( new SendDelayedResponse())).start(); } public class SendDelayedResponse implements Runnable { public void run() { response.setContentType(CoapMediaType.text_plain); response.setPayload("payload...".getBytes()); try { Thread.sleep(separateResponseTimeMs); } catch (InterruptedException e) { e.printStackTrace(); } channel.sendSeparateResponse(response); System.out.println("Send separate Response: " + response.toString()); } } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { System.out.println("Separate Response failed"); } }
Java
/** * Server Application for Plugtest 2012, Paris, France * * Execute with argument Identifier (e.g., TD_COAP_CORE_01) */ package org.ws4d.coap.test; import java.util.logging.Level; import java.util.logging.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.rest.CoapResourceServer; import org.ws4d.coap.test.resources.LongPathResource; import org.ws4d.coap.test.resources.QueryResource; import org.ws4d.coap.test.resources.TestResource; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class PlugtestServer { private static PlugtestServer plugtestServer; private CoapResourceServer resourceServer; private static Logger logger = Logger .getLogger(BasicCoapSocketHandler.class.getName()); /** * @param args */ public static void main(String[] args) { if (args.length > 1 || args.length < 1) { System.err.println("illegal number of arguments"); System.exit(1); } logger.setLevel(Level.WARNING); plugtestServer = new PlugtestServer(); plugtestServer.start(args[0]); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("PlugtestServer is now stopping."); System.out.println("===END==="); } }); } public void start(String testId) { System.out.println("===Run Test Server: " + testId + "==="); init(); if (testId.equals("TD_COAP_CORE_01")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_02")) { /* Nothing to setup, POST creates new resource */ run(); } else if (testId.equals("TD_COAP_CORE_03")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_04")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_05")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_06")) { /* Nothing to setup, POST creates new resource */ run(); } else if (testId.equals("TD_COAP_CORE_07")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_08")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_09")) { /* * === SPECIAL CASE: Separate Response: for these tests we cannot * use the resource server */ PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer(); server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS); } else if (testId.equals("TD_COAP_CORE_10")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_11")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_12")) { resourceServer.createResource(new LongPathResource()); run(); } else if (testId.equals("TD_COAP_CORE_13")) { resourceServer.createResource(new QueryResource()); run(); } else if (testId.equals("TD_COAP_CORE_14")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_15")) { /* * === SPECIAL CASE: Separate Response: for these tests we cannot * use the resource server */ PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer(); server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS); } else if (testId.equals("TD_COAP_CORE_16")) { /* * === SPECIAL CASE: Separate Response: for these tests we cannot * use the resource server */ PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer(); server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS); } else if (testId.equals("TD_COAP_LINK_01")) { resourceServer.createResource(new LongPathResource()); resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_LINK_02")) { resourceServer.createResource(new LongPathResource()); resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_BLOCK_01")) { } else if (testId.equals("TD_COAP_BLOCK_02")) { } else if (testId.equals("TD_COAP_BLOCK_03")) { } else if (testId.equals("TD_COAP_BLOCK_04")) { } else if (testId.equals("TD_COAP_OBS_01")) { } else if (testId.equals("TD_COAP_OBS_02")) { } else if (testId.equals("TD_COAP_OBS_03")) { } else if (testId.equals("TD_COAP_OBS_04")) { } else if (testId.equals("TD_COAP_OBS_05")) { } else { System.out.println("unknown test case"); System.exit(-1); } } private void init() { BasicCoapChannelManager.getInstance().setMessageId(2000); if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); } private void run() { try { resourceServer.start(); } catch (Exception e) { e.printStackTrace(); } } }
Java
/** * Server Application for Plugtest 2012, Paris, France * * Execute with argument Identifier (e.g., TD_COAP_CORE_01) */ package org.ws4d.coap.test; import java.util.logging.Level; import java.util.logging.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.rest.CoapResourceServer; import org.ws4d.coap.test.resources.LongPathResource; import org.ws4d.coap.test.resources.QueryResource; import org.ws4d.coap.test.resources.TestResource; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class CompletePlugtestServer { private static CompletePlugtestServer plugtestServer; private CoapResourceServer resourceServer; private static Logger logger = Logger .getLogger(BasicCoapSocketHandler.class.getName()); /** * @param args */ public static void main(String[] args) { logger.setLevel(Level.WARNING); plugtestServer = new CompletePlugtestServer(); plugtestServer.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("PlugtestServer is now stopping."); System.out.println("===END==="); } }); } public void start() { System.out.println("===Run Test Server ==="); init(); resourceServer.createResource(new TestResource()); resourceServer.createResource(new LongPathResource()); resourceServer.createResource(new QueryResource()); run(); } private void init() { BasicCoapChannelManager.getInstance().setMessageId(2000); if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); } private void run() { try { resourceServer.start(); } catch (Exception e) { e.printStackTrace(); } } }
Java
/** * Client Application for Plugtest 2012, Paris, France * * Execute with argument Identifier (e.g., TD_COAP_CORE_01) */ package org.ws4d.coap.test; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class PlugtestClient implements CoapClient{ CoapChannelManager channelManager = null; CoapClientChannel clientChannel = null; CoapRequest request = null; private static Logger logger = Logger.getLogger(BasicCoapSocketHandler.class.getName()); boolean exitAfterResponse = true; String serverAddress = null; int serverPort = 0; String filter = null; public static void main(String[] args) { if (args.length > 4 || args.length < 4) { System.err.println("illegal number of arguments"); System.exit(1); } logger.setLevel(Level.WARNING); PlugtestClient client = new PlugtestClient(); client.start(args[0], Integer.parseInt(args[1]), args[2], args[3]); } public void start(String serverAddress, int serverPort, String testcase, String filter){ System.out.println("===START=== (Run Test Client: " + testcase + ")"); String testId = testcase; this.serverAddress = serverAddress; this.serverPort = serverPort; this.filter = filter; if (testId.equals("TD_COAP_CORE_01")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_02")) { init(true, CoapRequestCode.POST); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_03")) { init(true, CoapRequestCode.PUT); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_04")) { init(true, CoapRequestCode.DELETE); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_05")) { init(false, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_06")) { init(false, CoapRequestCode.POST); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_07")) { init(false, CoapRequestCode.PUT); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_08")) { init(false, CoapRequestCode.DELETE); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_09")) { init(true, CoapRequestCode.GET); request.setUriPath("/separate"); } else if (testId.equals("TD_COAP_CORE_10")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); request.setToken("AABBCCDD".getBytes()); } else if (testId.equals("TD_COAP_CORE_11")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_12")) { init(true, CoapRequestCode.GET); request.setUriPath("/seg1/seg2/seg3"); } else if (testId.equals("TD_COAP_CORE_13")) { init(true, CoapRequestCode.GET); request.setUriPath("/query"); request.setUriQuery("first=1&second=2&third=3"); } else if (testId.equals("TD_COAP_CORE_14")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_15")) { init(true, CoapRequestCode.GET); request.setUriPath("/separate"); } else if (testId.equals("TD_COAP_CORE_16")) { init(false, CoapRequestCode.GET); request.setUriPath("/separate"); } else if (testId.equals("TD_COAP_LINK_01")) { init(false, CoapRequestCode.GET); request.setUriPath("/.well-known/core"); } else if (testId.equals("TD_COAP_LINK_02")) { init(false, CoapRequestCode.GET); request.setUriPath("/.well-known/core"); request.setUriQuery("rt=" + this.filter); } else { System.out.println("===Failure=== (unknown test case)"); System.exit(-1); } run(); } public void init(boolean reliable, CoapRequestCode requestCode) { channelManager = BasicCoapChannelManager.getInstance(); channelManager.setMessageId(1000); try { clientChannel = channelManager.connect(this, InetAddress.getByName(this.serverAddress), this.serverPort); if (clientChannel == null){ System.out.println("Connect failed."); System.exit(-1); } request = clientChannel.createRequest(reliable, requestCode); } catch (UnknownHostException e) { e.printStackTrace(); System.exit(-1); } } public void run() { if(request.getPayload() != null){ System.out.println("Send Request: " + request.toString() + " (" + new String(request.getPayload()) +")"); }else { System.out.println("Send Request: " + request.toString()); } clientChannel.sendMessage(request); } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { System.out.println("Connection Failed"); System.exit(-1); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { if (response.getPayload() != null){ System.out.println("Response: " + response.toString() + " (" + new String(response.getPayload()) +")"); } else { System.out.println("Response: " + response.toString()); } if (exitAfterResponse){ System.out.println("===END==="); System.exit(0); } } public class WaitAndExit implements Runnable { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("===END==="); System.exit(0); } } }
Java
package org.ws4d.coap.connection; import java.net.InetAddress; public class ChannelKey { public InetAddress inetAddr; public int port; public ChannelKey(InetAddress inetAddr, int port) { this.inetAddr = inetAddr; this.port = port; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((inetAddr == null) ? 0 : inetAddr.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ChannelKey other = (ChannelKey) obj; if (inetAddr == null) { if (other.inetAddr != null) return false; } else if (!inetAddr.equals(other.inetAddr)) return false; if (port != other.port) return false; return true; } }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.connection; import java.net.InetAddress; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public abstract class BasicCoapChannel implements CoapChannel { /* use the logger of the channel manager */ private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class); protected CoapSocketHandler socketHandler = null; protected CoapChannelManager channelManager = null; protected InetAddress remoteAddress; protected int remotePort; protected int localPort; CoapBlockSize maxReceiveBlocksize = null; //null means no block option CoapBlockSize maxSendBlocksize = null; //null means no block option public BasicCoapChannel(CoapSocketHandler socketHandler, InetAddress remoteAddress, int remotePort) { this.socketHandler = socketHandler; channelManager = socketHandler.getChannelManager(); this.remoteAddress = remoteAddress; this.remotePort = remotePort; this.localPort = socketHandler.getLocalPort(); //FIXME:can be 0 when socketHandler is not yet ready } @Override public void sendMessage(CoapMessage msg) { msg.setChannel(this); socketHandler.sendMessage(msg); } @Override public CoapBlockSize getMaxReceiveBlocksize() { return maxReceiveBlocksize; } @Override public void setMaxReceiveBlocksize(CoapBlockSize maxReceiveBlocksize) { this.maxReceiveBlocksize = maxReceiveBlocksize; } @Override public CoapBlockSize getMaxSendBlocksize() { return maxSendBlocksize; } @Override public void setMaxSendBlocksize(CoapBlockSize maxSendBlocksize) { this.maxSendBlocksize = maxSendBlocksize; } @Override public InetAddress getRemoteAddress() { return remoteAddress; } @Override public int getRemotePort() { return remotePort; } /*A channel is identified (and therefore unique) by its remote address, remote port and the local port * TODO: identify channel also by a token */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + localPort; result = prime * result + ((remoteAddress == null) ? 0 : remoteAddress.hashCode()); result = prime * result + remotePort; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BasicCoapChannel other = (BasicCoapChannel) obj; if (localPort != other.localPort) return false; if (remoteAddress == null) { if (other.remoteAddress != null) return false; } else if (!remoteAddress.equals(other.remoteAddress)) return false; if (remotePort != other.remotePort) return false; return true; } }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.connection; import java.io.IOException; import java.net.InetAddress; import java.util.HashMap; import java.util.Random; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.Constants; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.BasicCoapRequest; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapChannelManager implements CoapChannelManager { // global message id private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class); private int globalMessageId; private static BasicCoapChannelManager instance; private HashMap<Integer, SocketInformation> socketMap = new HashMap<Integer, SocketInformation>(); CoapServer serverListener = null; private BasicCoapChannelManager() { logger.addAppender(new ConsoleAppender(new SimpleLayout())); // ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: logger.setLevel(Level.WARN); initRandom(); } public synchronized static CoapChannelManager getInstance() { if (instance == null) { instance = new BasicCoapChannelManager(); } return instance; } /** * Creates a new server channel */ @Override public synchronized CoapServerChannel createServerChannel(CoapSocketHandler socketHandler, CoapMessage message, InetAddress addr, int port){ SocketInformation socketInfo = socketMap.get(socketHandler.getLocalPort()); if (socketInfo.serverListener == null) { /* this is not a server socket */ throw new IllegalStateException("Invalid server socket"); } if (!message.isRequest()){ throw new IllegalStateException("Incomming message is not a request message"); } CoapServer server = socketInfo.serverListener.onAccept((BasicCoapRequest) message); if (server == null){ /* Server rejected channel */ return null; } CoapServerChannel newChannel= new BasicCoapServerChannel( socketHandler, server, addr, port); return newChannel; } /** * Creates a new, global message id for a new COAP message */ @Override public synchronized int getNewMessageID() { if (globalMessageId < Constants.MESSAGE_ID_MAX) { ++globalMessageId; } else globalMessageId = Constants.MESSAGE_ID_MIN; return globalMessageId; } @Override public synchronized void initRandom() { // generate random 16 bit messageId Random random = new Random(); globalMessageId = random.nextInt(Constants.MESSAGE_ID_MAX + 1); } @Override public void createServerListener(CoapServer serverListener, int localPort) { if (!socketMap.containsKey(localPort)) { try { SocketInformation socketInfo = new SocketInformation(new BasicCoapSocketHandler(this, localPort), serverListener); socketMap.put(localPort, socketInfo); } catch (IOException e) { e.printStackTrace(); } } else { /*TODO: raise exception: address already in use */ throw new IllegalStateException(); } } @Override public CoapClientChannel connect(CoapClient client, InetAddress addr, int port) { CoapSocketHandler socketHandler = null; try { socketHandler = new BasicCoapSocketHandler(this); SocketInformation sockInfo = new SocketInformation(socketHandler, null); socketMap.put(socketHandler.getLocalPort(), sockInfo); return socketHandler.connect(client, addr, port); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } private class SocketInformation { public CoapSocketHandler socketHandler = null; public CoapServer serverListener = null; public SocketInformation(CoapSocketHandler socketHandler, CoapServer serverListener) { super(); this.socketHandler = socketHandler; this.serverListener = serverListener; } } @Override public void setMessageId(int globalMessageId) { this.globalMessageId = globalMessageId; } }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.connection; import java.io.ByteArrayOutputStream; import java.net.InetAddress; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.BasicCoapRequest; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapBlockOption; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapPacketType; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapClientChannel extends BasicCoapChannel implements CoapClientChannel { CoapClient client = null; ClientBlockContext blockContext = null; CoapRequest lastRequest = null; Object trigger = null; public BasicCoapClientChannel(CoapSocketHandler socketHandler, CoapClient client, InetAddress remoteAddress, int remotePort) { super(socketHandler, remoteAddress, remotePort); this.client = client; } @Override public void close() { socketHandler.removeClientChannel(this); } @Override public void handleMessage(CoapMessage message) { if (message.isRequest()){ /* this is a client channel, no requests allowed */ message.getChannel().sendMessage(new CoapEmptyMessage(CoapPacketType.RST, message.getMessageID())); return; } if (message.isEmpty() && message.getPacketType() == CoapPacketType.ACK){ /* this is the ACK of a separate response */ //TODO: implement a handler or listener, that informs a client when a sep. resp. ack was received return; } if (message.getPacketType() == CoapPacketType.CON) { /* this is a separate response */ /* send ACK */ this.sendMessage(new CoapEmptyMessage(CoapPacketType.ACK, message.getMessageID())); } /* check for blockwise transfer */ CoapBlockOption block2 = message.getBlock2(); if (blockContext == null && block2 != null){ /* initiate blockwise transfer */ blockContext = new ClientBlockContext(block2, maxReceiveBlocksize); blockContext.setFirstRequest(lastRequest); blockContext.setFirstResponse((CoapResponse) message); } if (blockContext!= null){ /*blocking option*/ if (!blockContext.addBlock(message, block2)){ /*this was not a correct block*/ /* TODO: implement either a RST or ignore this packet */ } if (!blockContext.isFinished()){ /* TODO: implement a counter to avoid an infinity req/resp loop: * if the same block is received more than x times -> rst the connection * implement maxPayloadSize to avoid an infinity payload */ CoapBlockOption newBlock = blockContext.getNextBlock(); if (lastRequest == null){ /*TODO: this should never happen*/ System.out.println("ERROR: client channel: lastRequest == null"); } else { /* create a new request for the next block */ BasicCoapRequest request = new BasicCoapRequest(lastRequest.getPacketType(), lastRequest.getRequestCode(), channelManager.getNewMessageID()); request.copyHeaderOptions((BasicCoapRequest) blockContext.getFirstRequest()); request.setBlock2(newBlock); sendMessage(request); } /* TODO: implement handler, inform the client that a block (but not the complete message) was received*/ return; } /* blockwise transfer finished */ message.setPayload(blockContext.getPayload()); /* TODO: give the payload separately and leave the original message as they is*/ } /* normal or separate response */ client.onResponse(this, (BasicCoapResponse) message); } @Override public void lostConnection(boolean notReachable, boolean resetByServer) { client.onConnectionFailed(this, notReachable, resetByServer); } @Override public BasicCoapRequest createRequest(boolean reliable, CoapRequestCode requestCode) { BasicCoapRequest msg = new BasicCoapRequest( reliable ? CoapPacketType.CON : CoapPacketType.NON, requestCode, channelManager.getNewMessageID()); msg.setChannel(this); return msg; } @Override public void sendMessage(CoapMessage msg) { super.sendMessage(msg); //TODO: check lastRequest = (CoapRequest) msg; } // public DefaultCoapClientChannel(CoapChannelManager channelManager) { // super(channelManager); // } // // @Override // public void connect(String remoteHost, int remotePort) { // socket = null; // if (remoteHost!=null && remotePort!=-1) { // try { // socket = new DatagramSocket(); // } catch (SocketException e) { // e.printStackTrace(); // } // } // // try { // InetAddress address = InetAddress.getByName(remoteHost); // socket.connect(address, remotePort); // super.establish(socket); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // } private class ClientBlockContext{ ByteArrayOutputStream payload = new ByteArrayOutputStream(); boolean finished = false; CoapBlockSize blockSize; //null means no block option CoapRequest request; CoapResponse response; public ClientBlockContext(CoapBlockOption blockOption, CoapBlockSize maxBlocksize) { /* determine the right blocksize (min of remote and max)*/ if (maxBlocksize == null){ blockSize = blockOption.getBlockSize(); } else { int max = maxBlocksize.getSize(); int remote = blockOption.getBlockSize().getSize(); if (remote < max){ blockSize = blockOption.getBlockSize(); } else { blockSize = maxBlocksize; } } } public byte[] getPayload() { return payload.toByteArray(); } public boolean addBlock(CoapMessage msg, CoapBlockOption block){ int blockPos = block.getBytePosition(); int blockLength = msg.getPayloadLength(); int bufSize = payload.size(); /*TODO: check if payload length = blocksize (except for the last block)*/ if (blockPos > bufSize){ /* data is missing before this block */ return false; } else if ((blockPos + blockLength) <= bufSize){ /* data already received */ return false; } int offset = bufSize - blockPos; payload.write(msg.getPayload(), offset, blockLength - offset); if (block.isLast()){ /* was this the last block */ finished = true; } return true; } public CoapBlockOption getNextBlock() { int num = payload.size() / blockSize.getSize(); //ignore the rest (no rest should be there) return new CoapBlockOption(num, false, blockSize); } public boolean isFinished() { return finished; } public CoapRequest getFirstRequest() { return request; } public void setFirstRequest(CoapRequest request) { this.request = request; } public CoapResponse getFirstResponse() { return response; } public void setFirstResponse(CoapResponse response) { this.response = response; } } @Override public void setTrigger(Object o) { trigger = o; } @Override public Object getTrigger() { return trigger; } }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.connection; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.HashMap; import java.util.PriorityQueue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.AbstractCoapMessage; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapPacketType; import org.ws4d.coap.tools.TimeoutHashMap; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Nico Laum <nico.laum@uni-rostock.de> */ public class BasicCoapSocketHandler implements CoapSocketHandler { /* the socket handler has its own logger * TODO: implement different socket handler for client and server channels */ private final static Logger logger = Logger.getLogger(BasicCoapSocketHandler.class); protected WorkerThread workerThread = null; protected HashMap<ChannelKey, CoapClientChannel> clientChannels = new HashMap<ChannelKey, CoapClientChannel>(); protected HashMap<ChannelKey, CoapServerChannel> serverChannels = new HashMap<ChannelKey, CoapServerChannel>(); private CoapChannelManager channelManager = null; private DatagramChannel dgramChannel = null; public static final int UDP_BUFFER_SIZE = 66000; // max UDP size = 65535 byte[] sendBuffer = new byte[UDP_BUFFER_SIZE]; private int localPort; public BasicCoapSocketHandler(CoapChannelManager channelManager, int port) throws IOException { logger.addAppender(new ConsoleAppender(new SimpleLayout())); // ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: logger.setLevel(Level.WARN); this.channelManager = channelManager; dgramChannel = DatagramChannel.open(); dgramChannel.socket().bind(new InetSocketAddress(port)); //port can be 0, then a free port is chosen this.localPort = dgramChannel.socket().getLocalPort(); dgramChannel.configureBlocking(false); workerThread = new WorkerThread(); workerThread.start(); } public BasicCoapSocketHandler(CoapChannelManager channelManager) throws IOException { this(channelManager, 0); } protected class WorkerThread extends Thread { Selector selector = null; /* contains all received message keys of a remote (message id generated by the remote) to detect duplications */ TimeoutHashMap<MessageKey, Boolean> duplicateRemoteMap = new TimeoutHashMap<MessageKey, Boolean>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* contains all received message keys of the host (message id generated by the host) to detect duplications */ TimeoutHashMap<Integer, Boolean> duplicateHostMap = new TimeoutHashMap<Integer, Boolean>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* contains all messages that (possibly) needs to be retransmitted (ACK, RST)*/ TimeoutHashMap<MessageKey, CoapMessage> retransMsgMap = new TimeoutHashMap<MessageKey, CoapMessage>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* contains all messages that are not confirmed yet (CON), * MessageID is always generated by Host and therefore unique */ TimeoutHashMap<Integer, CoapMessage> timeoutConMsgMap = new TimeoutHashMap<Integer, CoapMessage>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* this queue handles the timeout objects in the right order*/ private PriorityQueue<TimeoutObject<Integer>> timeoutQueue = new PriorityQueue<TimeoutObject<Integer>>(); public ConcurrentLinkedQueue<CoapMessage> sendBuffer = new ConcurrentLinkedQueue<CoapMessage>(); /* Contains all sent messages sorted by message ID */ long startTime; static final int POLLING_INTERVALL = 10000; ByteBuffer dgramBuffer; public WorkerThread() { dgramBuffer = ByteBuffer.allocate(UDP_BUFFER_SIZE); startTime = System.currentTimeMillis(); try { selector = Selector.open(); dgramChannel.register(selector, SelectionKey.OP_READ); } catch (IOException e1) { e1.printStackTrace(); } } public void close() { if (clientChannels != null) clientChannels.clear(); if (serverChannels != null) serverChannels.clear(); try { dgramChannel.close(); } catch (IOException e) { e.printStackTrace(); } /* TODO: wake up thread and kill it*/ } @Override public void run() { logger.log(Level.INFO, "Receive Thread started."); long waitFor = POLLING_INTERVALL; InetSocketAddress addr = null; while (dgramChannel != null) { /* send all messages in the send buffer */ sendBufferedMessages(); /* handle incoming packets */ dgramBuffer.clear(); try { addr = (InetSocketAddress) dgramChannel.receive(dgramBuffer); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (addr != null){ logger.log(Level.INFO, "handle incomming msg"); handleIncommingMessage(dgramBuffer, addr); } /* handle timeouts */ waitFor = handleTimeouts(); /* TODO: find a good strategy when to update the timeout maps */ duplicateRemoteMap.update(); duplicateHostMap.update(); retransMsgMap.update(); timeoutConMsgMap.update(); /* wait until * 1. selector.wakeup() is called by sendMessage() * 2. incomming packet * 3. timeout */ try { /*FIXME: don't make a select, when something is in the sendQueue, otherwise the packet will be sent after some delay * move this check and the select to a critical section */ selector.select(waitFor); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } protected synchronized void addMessageToSendBuffer(CoapMessage msg){ sendBuffer.add(msg); /* send immediately */ selector.wakeup(); } private void sendBufferedMessages(){ CoapMessage msg = sendBuffer.poll(); while(msg != null){ sendUdpMsg(msg); msg = sendBuffer.poll(); } } private void handleIncommingMessage(ByteBuffer buffer, InetSocketAddress addr) { CoapMessage msg; try { msg = AbstractCoapMessage.parseMessage(buffer.array(), buffer.position()); } catch (Exception e) { logger.warn("Received invalid message: message dropped!"); e.printStackTrace(); return; } CoapPacketType packetType = msg.getPacketType(); int msgId = msg.getMessageID(); MessageKey msgKey = new MessageKey(msgId, addr.getAddress(), addr.getPort()); if (msg.isRequest()){ /* --- INCOMING REQUEST: This is an incoming client request with a message key generated by the remote client*/ if (packetType == CoapPacketType.ACK || packetType == CoapPacketType.RST){ logger.warn("Invalid Packet Type: Request can not be in a ACK or a RST packet"); return; } /* check for duplicates and retransmit the response if a duplication is detected */ if (isRemoteDuplicate(msgKey)){ retransmitRemoteDuplicate(msgKey); return; } /* find or create server channel and handle incoming message */ CoapServerChannel channel = serverChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ /*no server channel found -> create*/ channel = channelManager.createServerChannel(BasicCoapSocketHandler.this, msg, addr.getAddress(), addr.getPort()); if (channel != null){ /* add the new channel to the channel map */ addServerChannel(channel); logger.info("Created new server channel."); } else { /* create failed -> server doesn't accept the connection --> send RST*/ CoapChannel fakeChannel = new BasicCoapServerChannel(BasicCoapSocketHandler.this, null, addr.getAddress(), addr.getPort()); CoapEmptyMessage rstMsg = new CoapEmptyMessage(CoapPacketType.RST, msgId); rstMsg.setChannel(fakeChannel); sendMessage(rstMsg); return; } } msg.setChannel(channel); channel.handleMessage(msg); return; } else if (msg.isResponse()){ /* --- INCOMING RESPONSE: This is an incoming server response (message ID generated by host) * or a separate server response (message ID generated by remote)*/ if (packetType == CoapPacketType.RST){ logger.warn("Invalid Packet Type: RST packet must be empty"); return; } /* check for separate response */ if (packetType == CoapPacketType.CON){ /* This is a separate response, the message ID is generated by the remote */ if (isRemoteDuplicate(msgKey)){ retransmitRemoteDuplicate(msgKey); return; } /* This is a separate Response */ CoapClientChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ logger.warn("Could not find channel of incomming separat response: message dropped"); return; } msg.setChannel(channel); channel.handleMessage(msg); return; } /* normal response (ACK or NON), message id was generated by host */ if (isHostDuplicate(msgId)){ /* drop duplicate responses */ return; } /* confirm the request*/ /* confirm message by removing it from the non confirmedMsgMap*/ /* Corresponding to the spec the server should be aware of a NON as answer to a CON*/ timeoutConMsgMap.remove(msgId); CoapClientChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ logger.warn("Could not find channel of incomming response: message dropped"); return; } msg.setChannel(channel); channel.handleMessage(msg); return; } else if (msg.isEmpty()){ if (packetType == CoapPacketType.CON || packetType == CoapPacketType.NON){ /* TODO: is this always true? */ logger.warn("Invalid Packet Type: CON or NON packets cannot be empty"); return; } /* ACK or RST, Message Id was generated by the host*/ if (isHostDuplicate(msgId)){ /* drop duplicate responses */ return; } /* confirm */ timeoutConMsgMap.remove(msgId); /* get channel */ /* This can be an ACK/RST for a client or a server channel */ CoapChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ channel = serverChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); } if (channel == null){ logger.warn("Could not find channel of incomming response: message dropped"); return; } msg.setChannel(channel); if (packetType == CoapPacketType.ACK ){ /* separate response ACK */ channel.handleMessage(msg); return; } if (packetType == CoapPacketType.RST ){ /* connection closed by remote */ channel.handleMessage(msg); return; } } else { logger.error("Invalid Message Type: not a request, not a response, not empty"); } } private long handleTimeouts(){ long nextTimeout = POLLING_INTERVALL; while (true){ TimeoutObject<Integer> tObj = timeoutQueue.peek(); if (tObj == null){ /* timeout queue is empty */ nextTimeout = POLLING_INTERVALL; break; } nextTimeout = tObj.expires - System.currentTimeMillis(); if (nextTimeout > 0){ /* timeout not expired */ break; } /* timeout expired, sendMessage will send the message and create a new timeout * if the message was already confirmed, nonConfirmedMsgMap.get() will return null */ timeoutQueue.poll(); Integer msgId = tObj.object; /* retransmit message after expired timeout*/ sendUdpMsg((CoapMessage) timeoutConMsgMap.get(msgId)); } return nextTimeout; } private boolean isRemoteDuplicate(MessageKey msgKey){ if (duplicateRemoteMap.get(msgKey) != null){ logger.info("Detected duplicate message"); return true; } return false; } private void retransmitRemoteDuplicate(MessageKey msgKey){ CoapMessage retransMsg = (CoapMessage) retransMsgMap.get(msgKey); if (retransMsg == null){ logger.warn("Detected duplicate message but no response could be found"); } else { sendUdpMsg(retransMsg); } } private boolean isHostDuplicate(int msgId){ if (duplicateHostMap.get(msgId) != null){ logger.info("Detected duplicate message"); return true; } return false; } private void sendUdpMsg(CoapMessage msg) { if (msg == null){ return; } CoapPacketType packetType = msg.getPacketType(); InetAddress inetAddr = msg.getChannel().getRemoteAddress(); int port = msg.getChannel().getRemotePort(); int msgId = msg.getMessageID(); if (packetType == CoapPacketType.CON){ /* in case of a CON this is a Request * requests must be added to the timeout queue * except this was the last retransmission */ if(msg.maxRetransReached()){ /* the connection is broken */ timeoutConMsgMap.remove(msgId); msg.getChannel().lostConnection(true, false); return; } msg.incRetransCounterAndTimeout(); timeoutConMsgMap.put(msgId, msg); TimeoutObject<Integer> tObj = new TimeoutObject<Integer>(msgId, msg.getTimeout() + System.currentTimeMillis()); timeoutQueue.add(tObj); } if (packetType == CoapPacketType.ACK || packetType == CoapPacketType.RST){ /* save this type of messages for a possible retransmission */ retransMsgMap.put(new MessageKey(msgId, inetAddr, port), msg); } /* Nothing to do for NON*/ /* send message*/ ByteBuffer buf = ByteBuffer.wrap(msg.serialize()); /*TODO: check if serialization could fail... then do not put it to any Map!*/ try { dgramChannel.send(buf, new InetSocketAddress(inetAddr, port)); logger.log(Level.INFO, "Send Msg with ID: " + msg.getMessageID()); } catch (IOException e) { e.printStackTrace(); logger.error("Send UDP message failed"); } } } private class MessageKey{ public int msgID; public InetAddress inetAddr; public int port; public MessageKey(int msgID, InetAddress inetAddr, int port) { super(); this.msgID = msgID; this.inetAddr = inetAddr; this.port = port; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((inetAddr == null) ? 0 : inetAddr.hashCode()); result = prime * result + msgID; result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageKey other = (MessageKey) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (inetAddr == null) { if (other.inetAddr != null) return false; } else if (!inetAddr.equals(other.inetAddr)) return false; if (msgID != other.msgID) return false; if (port != other.port) return false; return true; } private BasicCoapSocketHandler getOuterType() { return BasicCoapSocketHandler.this; } } private class TimeoutObject<T> implements Comparable<TimeoutObject>{ private long expires; private T object; public TimeoutObject(T object, long expires) { this.expires = expires; this.object = object; } public T getObject() { return object; } public int compareTo(TimeoutObject o){ return (int) (this.expires - o.expires); } } private void addClientChannel(CoapClientChannel channel) { clientChannels.put(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort()), channel); } private void addServerChannel(CoapServerChannel channel) { serverChannels.put(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort()), channel); } @Override public int getLocalPort() { return localPort; } @Override public void removeClientChannel(CoapClientChannel channel) { clientChannels.remove(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort())); } @Override public void removeServerChannel(CoapServerChannel channel) { serverChannels.remove(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort())); } @Override public void close() { workerThread.close(); } @Override public void sendMessage(CoapMessage message) { if (workerThread != null) { workerThread.addMessageToSendBuffer(message); } } @Override public CoapClientChannel connect(CoapClient client, InetAddress remoteAddress, int remotePort) { if (client == null){ return null; } if (clientChannels.containsKey(new ChannelKey(remoteAddress, remotePort))){ /* channel already exists */ logger.warn("Cannot connect: Client channel already exists"); return null; } CoapClientChannel channel = new BasicCoapClientChannel(this, client, remoteAddress, remotePort); addClientChannel(channel); return channel; } @Override public CoapChannelManager getChannelManager() { return this.channelManager; } }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.connection; import java.net.InetAddress; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.BasicCoapRequest; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapPacketType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapServerChannel extends BasicCoapChannel implements CoapServerChannel{ CoapServer server = null; public BasicCoapServerChannel(CoapSocketHandler socketHandler, CoapServer server, InetAddress remoteAddress, int remotePort) { super(socketHandler, remoteAddress, remotePort); this.server = server; } @Override public void close() { socketHandler.removeServerChannel(this); } @Override public void handleMessage(CoapMessage message) { /* message MUST be a request */ if (message.isEmpty()){ return; } if (!message.isRequest()){ return; //throw new IllegalStateException("Incomming server message is not a request"); } BasicCoapRequest request = (BasicCoapRequest) message; CoapChannel channel = request.getChannel(); /* TODO make this cast safe */ server.onRequest((CoapServerChannel) channel, request); } /*TODO: implement */ public void lostConnection(boolean notReachable, boolean resetByServer){ server.onSeparateResponseFailed(this); } @Override public BasicCoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode) { return createResponse(request, responseCode, null); } @Override public BasicCoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode, CoapMediaType contentType){ BasicCoapResponse response; if (request.getPacketType() == CoapPacketType.CON) { response = new BasicCoapResponse(CoapPacketType.ACK, responseCode, request.getMessageID(), request.getToken()); } else if (request.getPacketType() == CoapPacketType.NON) { response = new BasicCoapResponse(CoapPacketType.NON, responseCode, request.getMessageID(), request.getToken()); } else { throw new IllegalStateException("Create Response failed, Request is neither a CON nor a NON packet"); } if (contentType != null && contentType != CoapMediaType.UNKNOWN){ response.setContentType(contentType); } response.setChannel(this); return response; } @Override public CoapResponse createSeparateResponse(CoapRequest request, CoapResponseCode responseCode) { BasicCoapResponse response = null; if (request.getPacketType() == CoapPacketType.CON) { /* The separate Response is CON (normally a Response is ACK or NON) */ response = new BasicCoapResponse(CoapPacketType.CON, responseCode, channelManager.getNewMessageID(), request.getToken()); /*send ack immediately */ sendMessage(new CoapEmptyMessage(CoapPacketType.ACK, request.getMessageID())); } else if (request.getPacketType() == CoapPacketType.NON){ /* Just a normal response*/ response = new BasicCoapResponse(CoapPacketType.NON, responseCode, request.getMessageID(), request.getToken()); } else { throw new IllegalStateException("Create Response failed, Request is neither a CON nor a NON packet"); } response.setChannel(this); return response; } @Override public void sendSeparateResponse(CoapResponse response) { sendMessage(response); } @Override public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber){ /*use the packet type of the request: if con than con otherwise non*/ if (request.getPacketType() == CoapPacketType.CON){ return createNotification(request, responseCode, sequenceNumber, true); } else { return createNotification(request, responseCode, sequenceNumber, false); } } @Override public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber, boolean reliable){ BasicCoapResponse response = null; CoapPacketType packetType; if (reliable){ packetType = CoapPacketType.CON; } else { packetType = CoapPacketType.NON; } response = new BasicCoapResponse(packetType, responseCode, channelManager.getNewMessageID(), request.getToken()); response.setChannel(this); response.setObserveOption(sequenceNumber); return response; } @Override public void sendNotification(CoapResponse response) { sendMessage(response); } }
Java
package org.ws4d.coap.tools; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class TimeoutHashMap<K, V> extends HashMap<Object, Object>{ private static final long serialVersionUID = 4987370276778256858L; /* chronological list to remove expired elements when update() is called */ LinkedList<TimoutType<K>> timeoutQueue = new LinkedList<TimoutType<K>>(); /* Default Timeout is one minute */ long timeout = 60000; public TimeoutHashMap(long timeout){ this.timeout = timeout; } @Override public Object put(Object key, Object value) { long expires = System.currentTimeMillis() + timeout; TimoutType<V> timeoutValue = new TimoutType<V>((V) value, expires); TimoutType<K> timeoutKey = new TimoutType<K>((K) key, expires); timeoutQueue.add(timeoutKey); timeoutValue = (TimoutType<V>) super.put((K) key, timeoutValue); if (timeoutValue != null){ return timeoutValue.object; } return null; } @Override public Object get(Object key) { TimoutType<V> timeoutValue = (TimoutType<V>) super.get(key); if (timeoutValueIsValid(timeoutValue)){ return timeoutValue.object; } return null; } @Override public Object remove(Object key) { TimoutType<V> timeoutValue = (TimoutType<V>) super.remove(key); if (timeoutValueIsValid(timeoutValue)){ return timeoutValue.object; } return null; } @Override public void clear() { super.clear(); timeoutQueue.clear(); } /* remove expired elements */ public void update(){ while(true) { TimoutType<K> timeoutKey = timeoutQueue.peek(); if (timeoutKey == null){ /* if the timeoutKey queue is empty, there must be no more elements in the hashmap * otherwise there is a bug in the implementation */ if (!super.isEmpty()){ throw new IllegalStateException("Error in TimeoutHashMap. Timeout queue is empty but hashmap not!"); } return; } long now = System.currentTimeMillis(); if (now > timeoutKey.expires){ timeoutQueue.poll(); TimoutType<V> timeoutValue = (TimoutType<V>) super.remove(timeoutKey.object); if (timeoutValueIsValid(timeoutValue)){ /* This is a very special case which happens if an entry is overridden: * - put V with K * - put V2 with K * - K is expired but V2 not * because this is expected to be happened very seldom, we "reput" V2 to the hashmap * wich is better than every time to making a get and than a remove */ super.put(timeoutKey.object, timeoutValue); } } else { /* Key is not expired -> break the loop */ break; } } } @Override public Object clone() { // TODO implement function throw new IllegalStateException(); // return super.clone(); } @Override public boolean containsKey(Object arg0) { // TODO implement function throw new IllegalStateException(); // return super.containsKey(arg0); } @Override public boolean containsValue(Object arg0) { // TODO implement function throw new IllegalStateException(); // return super.containsValue(arg0); } @Override public Set<Entry<Object, Object>> entrySet() { // TODO implement function throw new IllegalStateException(); // return super.entrySet(); } @Override public boolean isEmpty() { // TODO implement function throw new IllegalStateException(); // return super.isEmpty(); } @Override public Set<Object> keySet() { // TODO implement function throw new IllegalStateException(); // return super.keySet(); } @Override public void putAll(Map<? extends Object, ? extends Object> arg0) { // TODO implement function throw new IllegalStateException(); // super.putAll(arg0); } @Override public int size() { // TODO implement function throw new IllegalStateException(); // return super.size(); } @Override public Collection<Object> values() { // TODO implement function throw new IllegalStateException(); // return super.values(); } /* private classes and methods */ private boolean timeoutValueIsValid(TimoutType<V> timeoutValue){ return timeoutValue != null && System.currentTimeMillis() < timeoutValue.expires; } private class TimoutType<T>{ public T object; public long expires; public TimoutType(T object, long expires) { super(); this.object = object; this.expires = expires; } } }
Java
package org.ws4d.coap.messages; import java.io.UnsupportedEncodingException; import java.util.Vector; import org.ws4d.coap.interfaces.CoapRequest; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapRequest extends AbstractCoapMessage implements CoapRequest { CoapRequestCode requestCode; public BasicCoapRequest(byte[] bytes, int length) { /* length ought to be provided by UDP header */ this(bytes, length, 0); } public BasicCoapRequest(byte[] bytes, int length, int offset) { serialize(bytes, length, offset); /* check if request code is valid, this function throws an error in case of an invalid argument */ requestCode = CoapRequestCode.parseRequestCode(this.messageCodeValue); //TODO: check integrity of header options } public BasicCoapRequest(CoapPacketType packetType, CoapRequestCode requestCode, int messageId) { this.version = 1; this.packetType = packetType; this.requestCode = requestCode; this.messageCodeValue = requestCode.getValue(); this.messageId = messageId; } @Override public void setToken(byte[] token){ /* this function is only public for a request*/ super.setToken(token); } @Override public CoapRequestCode getRequestCode() { return requestCode; } @Override public void setUriHost(String host) { if (host == null) return; if (options.optionExists(CoapHeaderOptionType.Uri_Host)){ throw new IllegalArgumentException("Uri-Host option already exists"); } if (host.length() < 1 || host.length() > CoapHeaderOption.MAX_LENGTH){ throw new IllegalArgumentException("Invalid Uri-Host option length"); } /*TODO: check if host is a valid address */ options.addOption(CoapHeaderOptionType.Uri_Host, host.getBytes()); } @Override public void setUriPort(int port) { if (port < 0) return; if (options.optionExists(CoapHeaderOptionType.Uri_Port)){ throw new IllegalArgumentException("Uri-Port option already exists"); } byte[] value = long2CoapUint(port); if(value.length < 0 || value.length > 2){ throw new IllegalStateException("Illegal Uri-Port length"); } options.addOption(new CoapHeaderOption(CoapHeaderOptionType.Uri_Port, value)); } @Override public void setUriPath(String path) { if (path == null) return; if (path.length() > CoapHeaderOption.MAX_LENGTH ){ throw new IllegalArgumentException("Uri-Path option too long"); } /* delete old options if present */ options.removeOption(CoapHeaderOptionType.Uri_Path); /*create substrings */ String[] pathElements = path.split("/"); /* add a Uri Path option for each part */ for (String element : pathElements) { /* check length */ if(element.length() < 0 || element.length() > CoapHeaderOption.MAX_LENGTH){ throw new IllegalArgumentException("Invalid Uri-Path"); } else if (element.length() > 0){ /* ignore empty substrings */ options.addOption(CoapHeaderOptionType.Uri_Path, element.getBytes()); } } } @Override public void setUriQuery(String query) { if (query == null) return; if (query.length() > CoapHeaderOption.MAX_LENGTH ){ throw new IllegalArgumentException("Uri-Query option too long"); } /* delete old options if present */ options.removeOption(CoapHeaderOptionType.Uri_Query); /*create substrings */ String[] pathElements = query.split("&"); /* add a Uri Path option for each part */ for (String element : pathElements) { /* check length */ if(element.length() < 0 || element.length() > CoapHeaderOption.MAX_LENGTH){ throw new IllegalArgumentException("Invalid Uri-Path"); } else if (element.length() > 0){ /* ignore empty substrings */ options.addOption(CoapHeaderOptionType.Uri_Query, element.getBytes()); } } } @Override public void setProxyUri(String proxyUri) { if (proxyUri == null) return; if (options.optionExists(CoapHeaderOptionType.Proxy_Uri)){ throw new IllegalArgumentException("Proxy Uri already exists"); } if (proxyUri.length() < 1){ throw new IllegalArgumentException("Proxy Uri must be at least one byte long"); } if (proxyUri.length() > CoapHeaderOption.MAX_LENGTH ){ throw new IllegalArgumentException("Proxy Uri longer then 270 bytes are not supported yet (to be implemented)"); } options.addOption(CoapHeaderOptionType.Proxy_Uri, proxyUri.getBytes()); } @Override public Vector<String> getUriQuery(){ Vector<String> queryList = new Vector<String>(); for (CoapHeaderOption option : options) { if(option.getOptionType() == CoapHeaderOptionType.Uri_Query){ queryList.add(new String(option.getOptionData())); } } return queryList; } @Override public String getUriHost(){ return new String(options.getOption(CoapHeaderOptionType.Uri_Host).getOptionData()); } @Override public int getUriPort(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Uri_Port); if (option == null){ return -1; //TODO: return default Coap Port? } byte[] value = option.getOptionData(); if(value.length < 0 || value.length > 2){ /* should never happen because this is an internal variable and should be checked during serialization */ throw new IllegalStateException("Illegal Uri-Port Option length"); } /* checked length -> cast is safe*/ return (int)coapUint2Long(options.getOption(CoapHeaderOptionType.Uri_Port).getOptionData()); } @Override public String getUriPath() { if (options.getOption(CoapHeaderOptionType.Uri_Path) == null){ return null; } StringBuilder uriPathBuilder = new StringBuilder(); for (CoapHeaderOption option : options) { if (option.getOptionType() == CoapHeaderOptionType.Uri_Path) { String uriPathElement; try { uriPathElement = new String(option.getOptionData(), "UTF-8"); uriPathBuilder.append("/"); uriPathBuilder.append(uriPathElement); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Invalid Encoding"); } } } return uriPathBuilder.toString(); } @Override public void addAccept(CoapMediaType mediaType){ options.addOption(CoapHeaderOptionType.Accept, long2CoapUint(mediaType.getValue())); } @Override public Vector<CoapMediaType> getAccept(CoapMediaType mediaType){ if (options.getOption(CoapHeaderOptionType.Accept) == null){ return null; } Vector<CoapMediaType> acceptList = new Vector<CoapMediaType>(); for (CoapHeaderOption option : options) { if (option.getOptionType() == CoapHeaderOptionType.Accept) { CoapMediaType accept = CoapMediaType.parse((int)coapUint2Long(option.optionData)); // if (accept != CoapMediaType.UNKNOWN){ /* add also UNKNOWN types to list */ acceptList.add(accept); // } } } return acceptList; } @Override public String getProxyUri(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Proxy_Uri); if (option == null) return null; return new String(option.getOptionData()); } @Override public void addETag(byte[] etag) { if (etag == null){ throw new IllegalArgumentException("etag MUST NOT be null"); } if (etag.length < 1 || etag.length > 8){ throw new IllegalArgumentException("Invalid etag length"); } options.addOption(CoapHeaderOptionType.Etag, etag); } @Override public Vector<byte[]> getETag() { if (options.getOption(CoapHeaderOptionType.Etag) == null){ return null; } Vector<byte[]> etagList = new Vector<byte[]>(); for (CoapHeaderOption option : options) { if (option.getOptionType() == CoapHeaderOptionType.Etag) { byte[] data = option.getOptionData(); if (data.length >= 1 && data.length <= 8){ etagList.add(option.getOptionData()); } } } return etagList; } @Override public boolean isRequest() { return true; } @Override public boolean isResponse() { return false; } @Override public boolean isEmpty() { return false; } @Override public String toString() { return packetType.toString() + ", " + requestCode.toString() + ", MsgId: " + getMessageID() +", #Options: " + options.getOptionCount(); } @Override public void setRequestCode(CoapRequestCode requestCode) { this.requestCode = requestCode; } }
Java
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapResponseCode { Created_201(65), Deleted_202(66), Valid_203(67), Changed_204(68), Content_205(69), Bad_Request_400(128), Unauthorized_401(129), Bad_Option_402(130), Forbidden_403(131), Not_Found_404(132), Method_Not_Allowed_405(133), Precondition_Failed_412(140), Request_Entity_To_Large_413(141), Unsupported_Media_Type_415(143), Internal_Server_Error_500(160), Not_Implemented_501(161), Bad_Gateway_502(162), Service_Unavailable_503(163), Gateway_Timeout_504(164), Proxying_Not_Supported_505(165), UNKNOWN(-1); private int code; private CoapResponseCode(int code) { this.code = code; } public static CoapResponseCode parseResponseCode(int codeValue) { switch (codeValue) { /* 32..63: reserved */ /* 64 is not used anymore */ // case 64: // this.code = ResponseCode.OK_200; // break; case 65: return Created_201; case 66: return Deleted_202; case 67: return Valid_203; case 68: return Changed_204; case 69: return Content_205; case 128: return Bad_Request_400; case 129: return Unauthorized_401; case 130: return Bad_Option_402; case 131: return Forbidden_403; case 132: return Not_Found_404; case 133: return Method_Not_Allowed_405; case 140: return Precondition_Failed_412; case 141: return Request_Entity_To_Large_413; case 143: return Unsupported_Media_Type_415; case 160: return Internal_Server_Error_500; case 161: return Not_Implemented_501; case 162: return Bad_Gateway_502; case 163: return Service_Unavailable_503; case 164: return Gateway_Timeout_504; case 165: return Proxying_Not_Supported_505; default: if (codeValue >= 64 && codeValue <= 191) { return UNKNOWN; } else { throw new IllegalArgumentException("Invalid Response Code"); } } } public int getValue() { return code; } @Override public String toString() { switch (this) { case Created_201: return "Created_201"; case Deleted_202: return "Deleted_202"; case Valid_203: return "Valid_203"; case Changed_204: return "Changed_204"; case Content_205: return "Content_205"; case Bad_Request_400: return "Bad_Request_400"; case Unauthorized_401: return "Unauthorized_401"; case Bad_Option_402: return "Bad_Option_402"; case Forbidden_403: return "Forbidden_403"; case Not_Found_404: return "Not_Found_404"; case Method_Not_Allowed_405: return "Method_Not_Allowed_405"; case Precondition_Failed_412: return "Precondition_Failed_412"; case Request_Entity_To_Large_413: return "Request_Entity_To_Large_413"; case Unsupported_Media_Type_415: return "Unsupported_Media_Type_415"; case Internal_Server_Error_500: return "Internal_Server_Error_500"; case Not_Implemented_501: return "Not_Implemented_501"; case Bad_Gateway_502: return "Bad_Gateway_502"; case Service_Unavailable_503: return "Service_Unavailable_503"; case Gateway_Timeout_504: return "Gateway_Timeout_504"; case Proxying_Not_Supported_505: return "Proxying_Not_Supported_505"; default: return "Unknown_Response_Code"; } } }
Java
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoapBlockOption{ private int number; private boolean more; private CoapBlockSize blockSize; public CoapBlockOption(byte[] data){ if (data.length <1 || data.length > 3){ throw new IllegalArgumentException("invalid block option"); } long val = AbstractCoapMessage.coapUint2Long(data); this.blockSize = CoapBlockSize.parse((int) (val & 0x7)); if (blockSize == null){ throw new IllegalArgumentException("invalid block options"); } if ((val & 0x8) == 0){ //more bit not set more = false; } else { more = true; } number = (int) (val >> 4); } public CoapBlockOption(int number, boolean more, CoapBlockSize blockSize){ if (blockSize == null){ throw new IllegalArgumentException(); } if (number < 0 || number > 0xFFFFFF ){ //not an unsigned 20 bit value throw new IllegalArgumentException(); } this.blockSize = blockSize; this.number = number; this.more = more; } public int getNumber() { return number; } public boolean isLast() { return !more; } public CoapBlockSize getBlockSize() { return blockSize; } public int getBytePosition(){ return number << (blockSize.getExponent() + 4); } public byte[] getBytes(){ int value = number << 4; value |= blockSize.getExponent(); if (more){ value |= 0x8; } return AbstractCoapMessage.long2CoapUint(value); } public enum CoapBlockSize { BLOCK_16 (0), BLOCK_32 (1), BLOCK_64 (2), BLOCK_128(3), BLOCK_256 (4), BLOCK_512 (5), BLOCK_1024 (6); int exp; CoapBlockSize(int exponent){ exp = exponent; } public static CoapBlockSize parse(int exponent){ switch(exponent){ case 0: return BLOCK_16; case 1: return BLOCK_32; case 2: return BLOCK_64; case 3: return BLOCK_128; case 4: return BLOCK_256; case 5: return BLOCK_512; case 6: return BLOCK_1024; default : return null; } } public int getExponent(){ return exp; } public int getSize(){ return 1 << (exp+4); } } }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.messages; /** * Type-safe class for CoapPacketTypes * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Sebastian Unger <sebastian.unger@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapPacketType { CON(0x00), NON(0x01), ACK(0x02), RST(0x03); private int packetType; CoapPacketType(int packetType) { if (packetType >= 0x00 && packetType <= 0x03){ this.packetType = packetType; } else { throw new IllegalStateException("Unknown CoAP Packet Type"); } } public static CoapPacketType getPacketType(int packetType) { if (packetType == 0x00) return CON; else if (packetType == 0x01) return NON; else if (packetType == 0x02) return ACK; else if (packetType == 0x03) return RST; else throw new IllegalStateException("Unknown CoAP Packet Type"); } public int getValue() { return packetType; } }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* WS4D Java CoAP Implementation * (c) 2011 WS4D.org * * written by Sebastian Unger */ package org.ws4d.coap.messages; import java.nio.ByteBuffer; import java.util.Collections; import java.util.Iterator; import java.util.Random; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapMessage; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public abstract class AbstractCoapMessage implements CoapMessage { /* use the logger of the channel manager */ private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class); protected static final int HEADER_LENGTH = 4; /* Header */ protected int version; protected CoapPacketType packetType; protected int messageCodeValue; //protected int optionCount; protected int messageId; /* Options */ protected CoapHeaderOptions options = new CoapHeaderOptions(); /* Payload */ protected byte[] payload = null; protected int payloadLength = 0; /* corresponding channel */ CoapChannel channel = null; /* Retransmission State */ int timeout = 0; int retransmissionCounter = 0; protected void serialize(byte[] bytes, int length, int offset){ /* check length to avoid buffer overflow exceptions */ this.version = 1; this.packetType = (CoapPacketType.getPacketType((bytes[offset + 0] & 0x30) >> 4)); int optionCount = bytes[offset + 0] & 0x0F; this.messageCodeValue = (bytes[offset + 1] & 0xFF); this.messageId = ((bytes[offset + 2] << 8) & 0xFF00) + (bytes[offset + 3] & 0xFF); /* serialize options */ this.options = new CoapHeaderOptions(bytes, offset + HEADER_LENGTH, optionCount); /* get and check payload length */ payloadLength = length - HEADER_LENGTH - options.getDeserializedLength(); if (payloadLength < 0){ throw new IllegalStateException("Invaldid CoAP Message (payload length negative)"); } /* copy payload */ int payloadOffset = offset + HEADER_LENGTH + options.getDeserializedLength(); payload = new byte[payloadLength]; for (int i = 0; i < payloadLength; i++){ payload[i] = bytes[i + payloadOffset]; } } /* TODO: this function should be in another class */ public static CoapMessage parseMessage(byte[] bytes, int length){ return parseMessage(bytes, length, 0); } public static CoapMessage parseMessage(byte[] bytes, int length, int offset){ /* we "peek" the header to determine the kind of message * TODO: duplicate Code */ int messageCodeValue = (bytes[offset + 1] & 0xFF); if (messageCodeValue == 0){ return new CoapEmptyMessage(bytes, length, offset); } else if (messageCodeValue >= 0 && messageCodeValue <= 31 ){ return new BasicCoapRequest(bytes, length, offset); } else if (messageCodeValue >= 64 && messageCodeValue <= 191){ return new BasicCoapResponse(bytes, length, offset); } else { throw new IllegalArgumentException("unknown CoAP message"); } } public int getVersion() { return version; } @Override public int getMessageCodeValue() { return messageCodeValue; } @Override public CoapPacketType getPacketType() { return packetType; } public byte[] getPayload() { return payload; } public int getPayloadLength() { return payloadLength; } @Override public int getMessageID() { return messageId; } @Override public void setMessageID(int messageId) { this.messageId = messageId; } public byte[] serialize() { /* TODO improve memory allocation */ /* serialize header options first to get the length*/ int optionsLength = 0; byte[] optionsArray = null; if (options != null) { optionsArray = this.options.serialize(); optionsLength = this.options.getSerializedLength(); } /* allocate memory for the complete packet */ int length = HEADER_LENGTH + optionsLength + payloadLength; byte[] serializedPacket = new byte[length]; /* serialize header */ serializedPacket[0] = (byte) ((this.version & 0x03) << 6); serializedPacket[0] |= (byte) ((this.packetType.getValue() & 0x03) << 4); serializedPacket[0] |= (byte) (options.getOptionCount() & 0x0F); serializedPacket[1] = (byte) (this.getMessageCodeValue() & 0xFF); serializedPacket[2] = (byte) ((this.messageId >> 8) & 0xFF); serializedPacket[3] = (byte) (this.messageId & 0xFF); /* copy serialized options to the final array */ int offset = HEADER_LENGTH; if (options != null) { for (int i = 0; i < optionsLength; i++) serializedPacket[i + offset] = optionsArray[i]; } /* copy payload to the final array */ offset = HEADER_LENGTH + optionsLength; for (int i = 0; i < this.payloadLength; i++) { serializedPacket[i + offset] = payload[i]; } return serializedPacket; } public void setPayload(byte[] payload) { this.payload = payload; if (payload!=null) this.payloadLength = payload.length; else this.payloadLength = 0; } public void setPayload(char[] payload) { this.payload = new byte[payload.length]; for (int i = 0; i < payload.length; i++) { this.payload[i] = (byte) payload[i]; } this.payloadLength = payload.length; } public void setPayload(String payload) { setPayload(payload.toCharArray()); } @Override public void setContentType(CoapMediaType mediaType){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Content_Type); if (option != null){ /* content Type MUST only exists once */ throw new IllegalStateException("added content option twice"); } if ( mediaType == CoapMediaType.UNKNOWN){ throw new IllegalStateException("unknown content type"); } /* convert value */ byte[] data = long2CoapUint(mediaType.getValue()); /* no need to check result, mediaType is safe */ /* add option to Coap Header*/ options.addOption(new CoapHeaderOption(CoapHeaderOptionType.Content_Type, data)); } @Override public CoapMediaType getContentType(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Content_Type); if (option == null){ /* not content type TODO: return UNKNOWN ?*/ return null; } /* no need to check length, CoapMediaType parse function will do*/ int mediaTypeCode = (int) coapUint2Long(options.getOption(CoapHeaderOptionType.Content_Type).getOptionData()); return CoapMediaType.parse(mediaTypeCode); } @Override public byte[] getToken(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Token); if (option == null){ return null; } return option.getOptionData(); } protected void setToken(byte[] token){ if (token == null){ return; } if (token.length < 1 || token.length > 8){ throw new IllegalArgumentException("Invalid Token Length"); } options.addOption(CoapHeaderOptionType.Token, token); } @Override public CoapBlockOption getBlock1(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block1); if (option == null){ return null; } CoapBlockOption blockOpt = new CoapBlockOption(option.getOptionData()); return blockOpt; } @Override public void setBlock1(CoapBlockOption blockOption){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block1); if (option != null){ //option already exists options.removeOption(CoapHeaderOptionType.Block1); } options.addOption(CoapHeaderOptionType.Block1, blockOption.getBytes()); } @Override public CoapBlockOption getBlock2(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block2); if (option == null){ return null; } CoapBlockOption blockOpt = new CoapBlockOption(option.getOptionData()); return blockOpt; } @Override public void setBlock2(CoapBlockOption blockOption){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block2); if (option != null){ //option already exists options.removeOption(CoapHeaderOptionType.Block2); } options.addOption(CoapHeaderOptionType.Block2, blockOption.getBytes()); } @Override public Integer getObserveOption() { CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Observe); if (option == null){ return null; } byte[] data = option.getOptionData(); if (data.length < 0 || data.length > 2){ logger.warn("invalid observe option length, return null"); return null; } return (int) AbstractCoapMessage.coapUint2Long(data); } @Override public void setObserveOption(int sequenceNumber) { CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Observe); if (option != null){ options.removeOption(CoapHeaderOptionType.Observe); } byte[] data = long2CoapUint(sequenceNumber); if (data.length < 0 || data.length > 2){ throw new IllegalArgumentException("invalid observe option length"); } options.addOption(CoapHeaderOptionType.Observe, data); } public void copyHeaderOptions(AbstractCoapMessage origin){ options.removeAll(); options.copyFrom(origin.options); } public void removeOption(CoapHeaderOptionType optionType){ options.removeOption(optionType); } @Override public CoapChannel getChannel() { return channel; } @Override public void setChannel(CoapChannel channel) { this.channel = channel; } @Override public int getTimeout() { if (timeout == 0) { Random random = new Random(); timeout = RESPONSE_TIMEOUT_MS + random.nextInt((int) (RESPONSE_TIMEOUT_MS * RESPONSE_RANDOM_FACTOR) - RESPONSE_TIMEOUT_MS); } return timeout; } @Override public boolean maxRetransReached() { if (retransmissionCounter < MAX_RETRANSMIT) { return false; } return true; } @Override public void incRetransCounterAndTimeout() { /*TODO: Rename*/ retransmissionCounter += 1; timeout *= 2; } @Override public boolean isReliable() { if (packetType == CoapPacketType.NON){ return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((channel == null) ? 0 : channel.hashCode()); result = prime * result + getMessageID(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractCoapMessage other = (AbstractCoapMessage) obj; if (channel == null) { if (other.channel != null) return false; } else if (!channel.equals(other.channel)) return false; if (getMessageID() != other.getMessageID()) return false; return true; } protected static long coapUint2Long(byte[] data){ /* avoid buffer overflow */ if(data.length > 8){ return -1; } /* fill with leading zeros */ byte[] tmp = new byte[8]; for (int i = 0; i < data.length; i++) { tmp[i + 8 - data.length] = data[i]; } /* convert to long */ ByteBuffer buf = ByteBuffer.wrap(tmp); /* byte buffer contains 8 bytes */ return buf.getLong(); } protected static byte[] long2CoapUint(long value){ /* only unsigned values supported */ if (value < 0){ return null; } /* a zero length value implies zero */ if (value == 0){ return new byte[0]; } /* convert long to byte array with a fixed length of 8 byte*/ ByteBuffer buf = ByteBuffer.allocate(8); buf.putLong(value); byte[] tmp = buf.array(); /* remove leading zeros */ int leadingZeros = 0; for (int i = 0; i < tmp.length; i++) { if (tmp[i] == 0){ leadingZeros = i+1; } else { break; } } /* copy to byte array without leading zeros */ byte[] result = new byte[8 - leadingZeros]; for (int i = 0; i < result.length; i++) { result[i] = tmp[i + leadingZeros]; } return result; } public enum CoapHeaderOptionType { UNKNOWN(-1), Content_Type (1), Max_Age (2), Proxy_Uri(3), Etag (4), Uri_Host (5), Location_Path (6), Uri_Port (7), Location_Query (8), Uri_Path (9), Observe (10), Token (11), Accept (12), If_Match (13), Uri_Query (15), If_None_Match (21), Block1 (19), Block2 (17); int value; CoapHeaderOptionType(int optionValue){ value = optionValue; } public static CoapHeaderOptionType parse(int optionTypeValue){ switch(optionTypeValue){ case 1: return Content_Type; case 2: return Max_Age; case 3: return Proxy_Uri; case 4: return Etag; case 5: return Uri_Host; case 6: return Location_Path; case 7: return Uri_Port; case 8: return Location_Query; case 9: return Uri_Path; case 10: return Observe; case 11:return Token; case 12:return Accept; case 13:return If_Match; case 15:return Uri_Query; case 21:return If_None_Match; case 19:return Block1; case 17:return Block2; default: return UNKNOWN; } } public int getValue(){ return value; } /* TODO: implement validity checks */ /*TODO: implement isCritical(int optionTypeValue), isElective()*/ } protected class CoapHeaderOption implements Comparable<CoapHeaderOption> { CoapHeaderOptionType optionType; int optionTypeValue; /* integer representation of optionType*/ byte[] optionData; int shortLength; int longLength; int deserializedLength; static final int MAX_LENGTH = 270; public int getDeserializedLength() { return deserializedLength; } public CoapHeaderOption(CoapHeaderOptionType optionType, byte[] value) { if (optionType == CoapHeaderOptionType.UNKNOWN){ /*TODO: implement check if it is a critical option */ throw new IllegalStateException("Unknown header option"); } if (value == null){ throw new IllegalArgumentException("Header option value MUST NOT be null"); } this.optionTypeValue = optionType.getValue(); this.optionData = value; if (value.length < 15) { shortLength = value.length; longLength = 0; } else { shortLength = 15; longLength = value.length - shortLength; } } public CoapHeaderOption(byte[] bytes, int offset, int lastOptionNumber){ int headerLength; /* parse option type */ optionTypeValue = ((bytes[offset] & 0xF0) >> 4) + lastOptionNumber; optionType = CoapHeaderOptionType.parse(optionTypeValue); if (optionType == CoapHeaderOptionType.UNKNOWN){ if (optionTypeValue % 14 == 0){ /* no-op: no operation for deltas > 14 */ } else { /*TODO: implement check if it is a critical option */ throw new IllegalArgumentException("Unknown header option"); } } /* parse length */ if ((bytes[offset] & 0x0F) < 15) { shortLength = bytes[offset] & 0x0F; longLength = 0; headerLength = 1; } else { shortLength = 15; longLength = bytes[offset + 1]; headerLength = 2; /* additional length byte */ } /* copy value */ optionData = new byte[shortLength + longLength]; for (int i = 0; i < shortLength + longLength; i++){ optionData[i] = bytes[i + headerLength + offset]; } deserializedLength += headerLength + shortLength + longLength; } @Override public int compareTo(CoapHeaderOption option) { /* compare function for sorting * TODO: check what happens in case of equal option values * IMPORTANT: order must be the same for e.g., URI path*/ if (this.optionTypeValue != option.optionTypeValue) return this.optionTypeValue < option.optionTypeValue ? -1 : 1; else return 0; } public boolean hasLongLength(){ if (shortLength == 15){ return true; } else return false; } public int getLongLength() { return longLength; } public int getShortLength() { return shortLength; } public int getOptionTypeValue() { return optionTypeValue; } public byte[] getOptionData() { return optionData; } public int getSerializeLength(){ if (hasLongLength()){ return optionData.length + 2; } else { return optionData.length + 1; } } @Override public String toString() { char[] printableOptionValue = new char[optionData.length]; for (int i = 0; i < optionData.length; i++) printableOptionValue[i] = (char) optionData[i]; return "Option Number: " + " (" + optionTypeValue + ")" + ", Option Value: " + String.copyValueOf(printableOptionValue); } public CoapHeaderOptionType getOptionType() { return optionType; } } protected class CoapHeaderOptions implements Iterable<CoapHeaderOption>{ private Vector<CoapHeaderOption> headerOptions = new Vector<CoapHeaderOption>(); private int deserializedLength; private int serializedLength = 0; public CoapHeaderOptions(byte[] bytes, int option_count){ this(bytes, option_count, option_count); } public CoapHeaderOptions(byte[] bytes, int offset, int optionCount){ /* note: we only receive deltas and never concrete numbers */ /* TODO: check integrity */ deserializedLength = 0; int lastOptionNumber = 0; int optionOffset = offset; for (int i = 0; i < optionCount; i++) { CoapHeaderOption option = new CoapHeaderOption(bytes, optionOffset, lastOptionNumber); lastOptionNumber = option.getOptionTypeValue(); deserializedLength += option.getDeserializedLength(); optionOffset += option.getDeserializedLength(); addOption(option); } } public CoapHeaderOptions() { /* creates empty header options */ } public CoapHeaderOption getOption(int optionNumber) { for (CoapHeaderOption headerOption : headerOptions) { if (headerOption.getOptionTypeValue() == optionNumber) { return headerOption; } } return null; } public CoapHeaderOption getOption(CoapHeaderOptionType optionType) { for (CoapHeaderOption headerOption : headerOptions) { if (headerOption.getOptionType() == optionType) { return headerOption; } } return null; } public boolean optionExists(CoapHeaderOptionType optionType) { CoapHeaderOption option = getOption(optionType); if (option == null){ return false; } else return true; } public void addOption(CoapHeaderOption option) { headerOptions.add(option); /*TODO: only sort when options are serialized*/ Collections.sort(headerOptions); } public void addOption(CoapHeaderOptionType optionType, byte[] value){ addOption(new CoapHeaderOption(optionType, value)); } public void removeOption(CoapHeaderOptionType optionType){ CoapHeaderOption headerOption; // get elements of Vector /* note: iterating over and changing a vector at the same time is not allowed */ int i = 0; while (i < headerOptions.size()){ headerOption = headerOptions.get(i); if (headerOption.getOptionType() == optionType) { headerOptions.remove(i); } else { /* only increase when no element was removed*/ i++; } } Collections.sort(headerOptions); } public void removeAll(){ headerOptions.clear(); } public void copyFrom(CoapHeaderOptions origin){ for (CoapHeaderOption option : origin) { addOption(option); } } public int getOptionCount() { return headerOptions.size(); } public byte[] serialize() { /* options are serialized here to be more efficient (only one byte array necessary)*/ int length = 0; /* calculate the overall length first */ for (CoapHeaderOption option : headerOptions) { length += option.getSerializeLength(); } byte[] data = new byte[length]; int arrayIndex = 0; int lastOptionNumber = 0; /* let's keep track of this */ for (CoapHeaderOption headerOption : headerOptions) { /* TODO: move the serialization implementation to CoapHeaderOption */ int optionDelta = headerOption.getOptionTypeValue() - lastOptionNumber; lastOptionNumber = headerOption.getOptionTypeValue(); // set length(s) data[arrayIndex++] = (byte) (((optionDelta & 0x0F) << 4) | (headerOption.getShortLength() & 0x0F)); if (headerOption.hasLongLength()) { data[arrayIndex++] = (byte) (headerOption.getLongLength() & 0xFF); } // copy option value byte[] value = headerOption.getOptionData(); for (int i = 0; i < value.length; i++) { data[arrayIndex++] = value[i]; } } serializedLength = length; return data; } public int getDeserializedLength(){ return deserializedLength; } public int getSerializedLength() { return serializedLength; } @Override public Iterator<CoapHeaderOption> iterator() { return headerOptions.iterator(); } @Override public String toString() { String result = "\tOptions:\n"; for (CoapHeaderOption option : headerOptions) { result += "\t\t" + option.toString() + "\n"; } return result; } } }
Java
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapMediaType { text_plain (0), //text/plain; charset=utf-8 link_format (40), //application/link-format xml(41), //application/xml octet_stream (42), //application/octet-stream exi(47), //application/exi json(50), //application/json UNKNOWN (-1); int mediaType; private CoapMediaType(int mediaType){ this.mediaType = mediaType; } public static CoapMediaType parse(int mediaType){ switch(mediaType){ case 0: return text_plain; case 40:return link_format; case 41:return xml; case 42:return octet_stream; case 47:return exi; case 50:return json; default: return UNKNOWN; } } public int getValue(){ return mediaType; } }
Java
package org.ws4d.coap.messages; import org.ws4d.coap.interfaces.CoapResponse; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapResponse extends AbstractCoapMessage implements CoapResponse { CoapResponseCode responseCode; public BasicCoapResponse(byte[] bytes, int length){ this(bytes, length, 0); } public BasicCoapResponse(byte[] bytes, int length, int offset){ serialize(bytes, length, offset); /* check if response code is valid, this function throws an error in case of an invalid argument */ responseCode = CoapResponseCode.parseResponseCode(this.messageCodeValue); //TODO: check integrity of header options } /* token can be null */ public BasicCoapResponse(CoapPacketType packetType, CoapResponseCode responseCode, int messageId, byte[] requestToken){ this.version = 1; this.packetType = packetType; this.responseCode = responseCode; if (responseCode == CoapResponseCode.UNKNOWN){ throw new IllegalArgumentException("UNKNOWN Response Code not allowed"); } this.messageCodeValue = responseCode.getValue(); this.messageId = messageId; setToken(requestToken); } @Override public CoapResponseCode getResponseCode() { return responseCode; } @Override public void setMaxAge(int maxAge){ if (options.optionExists(CoapHeaderOptionType.Max_Age)){ throw new IllegalStateException("Max Age option already exists"); } if (maxAge < 0){ throw new IllegalStateException("Max Age MUST be an unsigned value"); } options.addOption(CoapHeaderOptionType.Max_Age, long2CoapUint(maxAge)); } @Override public long getMaxAge(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Max_Age); if (option == null){ return -1; } return coapUint2Long((options.getOption(CoapHeaderOptionType.Max_Age).getOptionData())); } @Override public void setETag(byte[] etag){ if (etag == null){ throw new IllegalArgumentException("etag MUST NOT be null"); } if (etag.length < 1 || etag.length > 8){ throw new IllegalArgumentException("Invalid etag length"); } options.addOption(CoapHeaderOptionType.Etag, etag); } @Override public byte[] getETag(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Etag); if (option == null){ return null; } return option.getOptionData(); } @Override public boolean isRequest() { return false; } @Override public boolean isResponse() { return true; } @Override public boolean isEmpty() { return false; } @Override public String toString() { return packetType.toString() + ", " + responseCode.toString() + ", MsgId: " + getMessageID() +", #Options: " + options.getOptionCount(); } @Override public void setResponseCode(CoapResponseCode responseCode) { if (responseCode != CoapResponseCode.UNKNOWN){ this.responseCode = responseCode; this.messageCodeValue = responseCode.getValue(); } } }
Java
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoapEmptyMessage extends AbstractCoapMessage { public CoapEmptyMessage(byte[] bytes, int length){ this(bytes, length, 0); } public CoapEmptyMessage(byte[] bytes, int length, int offset){ serialize(bytes, length, offset); /* check if response code is valid, this function throws an error in case of an invalid argument */ if (this.messageCodeValue != 0){ throw new IllegalArgumentException("Not an empty CoAP message."); } if (length != HEADER_LENGTH){ throw new IllegalArgumentException("Invalid length of an empty message"); } } public CoapEmptyMessage(CoapPacketType packetType, int messageId) { this.version = 1; this.packetType = packetType; this.messageCodeValue = 0; this.messageId = messageId; } @Override public boolean isRequest() { return false; } @Override public boolean isResponse() { return false; } @Override public boolean isEmpty() { return true; } }
Java
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapRequestCode { GET(1), POST(2), PUT(3), DELETE(4); private int code; private CoapRequestCode(int code) { this.code = code; } public static CoapRequestCode parseRequestCode(int codeValue){ switch (codeValue) { case 1: return GET; case 2: return POST; case 3: return PUT; case 4: return DELETE; default: throw new IllegalArgumentException("Invalid Request Code"); } } public int getValue() { return code; } @Override public String toString() { switch (this) { case GET: return "GET"; case POST: return "POST"; case PUT: return "PUT"; case DELETE: return "DELETE"; } return null; } }
Java
package org.ws4d.coap.rest; import java.util.Vector; /** * A resource known from the REST architecture style. A resource has a type, * name and data associated with it. * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public interface Resource { /** * Get the MIME Type of the resource (e.g., "application/xml") * @return The MIME Type of this resource as String. */ public String getMimeType(); /** * Get the unique name of this resource * @return The unique name of the resource. */ public String getPath(); public String getShortName(); public byte[] getValue(); public byte[] getValue(Vector<String> query); //TODO: bad api: no return value public void post(byte[] data); public String getResourceType(); public void registerServerListener(ResourceServer server); public void unregisterServerListener(ResourceServer server); }
Java
package org.ws4d.coap.rest; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.messages.CoapMediaType; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapResource extends Resource { /* returns the CoAP Media Type */ public CoapMediaType getCoapMediaType(); /* called by the application, when the resource state changed -> used for observation */ public void changed(); /* called by the server to register a new observer, returns false if resource is not observable */ public boolean addObserver(CoapRequest request); /* removes an observer from the list */ public void removeObserver(CoapChannel channel); /* returns if the resource is observable */ public boolean isObservable(); /* returns if the resource is observable */ public int getObserveSequenceNumber(); /* returns the unix time when resource expires, -1 for never */ public long expires(); public boolean isExpired(); }
Java
package org.ws4d.coap.rest; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.util.Enumeration; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.Constants; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoapResourceServer implements CoapServer, ResourceServer { private int port = 0; private final static Logger logger = Logger.getLogger(CoapResourceServer.class); protected HashMap<String, Resource> resources = new HashMap<String, Resource>(); private CoreResource coreResource = new CoreResource(this); public CoapResourceServer(){ logger.addAppender(new ConsoleAppender(new SimpleLayout())); logger.setLevel(Level.WARN); } public HashMap<String, Resource> getResources(){ return resources; } private void addResource(Resource resource){ resource.registerServerListener(this); resources.put(resource.getPath(), resource); coreResource.registerResource(resource); } @Override public boolean createResource(Resource resource) { if (resource==null) return false; if (!resources.containsKey(resource.getPath())) { addResource(resource); logger.info("created ressource: " + resource.getPath()); return true; } else return false; } @Override public boolean updateResource(Resource resource) { if (resource==null) return false; if (resources.containsKey(resource.getPath())) { addResource(resource); logger.info("updated ressource: " + resource.getPath()); return true; } else return false; } @Override public boolean deleteResource(String path) { if (null != resources.remove(path)) { logger.info("deleted ressource: " + path); return true; } else return false; } @Override public final Resource readResource(String path) { logger.info("read ressource: " + path); return resources.get(path); } /*corresponding to the coap spec the put is an update or create (or error)*/ public CoapResponseCode CoapResponseCode(Resource resource) { Resource res = readResource(resource.getPath()); //TODO: check results if (res == null){ createResource(resource); return CoapResponseCode.Created_201; } else { updateResource(resource); return CoapResponseCode.Changed_204; } } @Override public void start() throws Exception { start(Constants.COAP_DEFAULT_PORT); } public void start(int port) throws Exception { resources.put(coreResource.getPath(), coreResource); CoapChannelManager channelManager = BasicCoapChannelManager .getInstance(); this.port = port; channelManager.createServerListener(this, port); } @Override public void stop() { } public int getPort() { return port; } @Override public URI getHostUri() { URI hostUri = null; try { hostUri = new URI("coap://" + this.getLocalIpAddress() + ":" + getPort()); } catch (URISyntaxException e) { e.printStackTrace(); } return hostUri; } @Override public void resourceChanged(Resource resource) { logger.info("Resource changed: " + resource.getPath()); } @Override public CoapServer onAccept(CoapRequest request) { return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { CoapMessage response = null; CoapRequestCode requestCode = request.getRequestCode(); String targetPath = request.getUriPath(); //TODO make this cast safe (send internal server error if it is not a CoapResource) CoapResource resource = (CoapResource) readResource(targetPath); /* TODO: check return values of create, read, update and delete * TODO: implement forbidden * TODO: implement ETag * TODO: implement If-Match... * TODO: check for well known addresses (do not override well known core) * TODO: check that path begins with "/" */ switch (requestCode) { case GET: if (resource != null) { // URI queries Vector<String> uriQueries = request.getUriQuery(); final byte[] responseValue; if (uriQueries != null) { responseValue = resource.getValue(uriQueries); } else { responseValue = resource.getValue(); } response = channel.createResponse(request, CoapResponseCode.Content_205, resource.getCoapMediaType()); response.setPayload(responseValue); if (request.getObserveOption() != null){ /*client wants to observe this resource*/ if (resource.addObserver(request)){ /* successfully added observer */ response.setObserveOption(resource.getObserveSequenceNumber()); } } } else { response = channel.createResponse(request, CoapResponseCode.Not_Found_404); } break; case DELETE: /* CoAP: "A 2.02 (Deleted) response SHOULD be sent on success or in case the resource did not exist before the request.*/ deleteResource(targetPath); response = channel.createResponse(request, CoapResponseCode.Deleted_202); break; case POST: if (resource != null){ resource.post(request.getPayload()); response = channel.createResponse(request, CoapResponseCode.Changed_204); } else { /* if the resource does not exist, a new resource will be created */ createResource(parseRequest(request)); response = channel.createResponse(request, CoapResponseCode.Created_201); } break; case PUT: if (resource == null){ /* create*/ createResource(parseRequest(request)); response = channel.createResponse(request,CoapResponseCode.Created_201); } else { /*update*/ updateResource(parseRequest(request)); response = channel.createResponse(request, CoapResponseCode.Changed_204); } break; default: response = channel.createResponse(request, CoapResponseCode.Bad_Request_400); break; } channel.sendMessage(response); } private CoapResource parseRequest(CoapRequest request) { CoapResource resource = new BasicCoapResource(request.getUriPath(), request.getPayload(), request.getContentType()); // TODO add content type return resource; } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { logger.error("Separate response failed but server never used separate responses"); } protected String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf .getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { } return null; } }
Java
package org.ws4d.coap.rest; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapResource implements CoapResource { /* use the logger of the resource server */ private final static Logger logger = Logger.getLogger(CoapResourceServer.class); private CoapMediaType mediaType; private String path; private byte[] value; ResourceHandler resourceHandler = null; ResourceServer serverListener = null; //could be a list of listener String resourceType = null; HashMap<CoapChannel, CoapRequest> observer = new HashMap<CoapChannel, CoapRequest>(); boolean observable = false; int observeSequenceNumber = 0; //MUST NOT greater than 0xFFFF (2 byte integer) Boolean reliableNotification = null; long expires = -1; //DEFAULT: expires never public BasicCoapResource(String path, byte[] value, CoapMediaType mediaType) { this.path = path; this.value = value; this.mediaType = mediaType; } public void setCoapMediaType(CoapMediaType mediaType) { this.mediaType = mediaType; } @Override public CoapMediaType getCoapMediaType() { return mediaType; } public String getMimeType(){ //TODO: implement return null; } @Override public String getPath() { return path; } @Override public String getShortName() { return null; } @Override public byte[] getValue() { return value; } @Override public byte[] getValue(Vector<String> query) { return value; } public void setValue(byte[] value) { this.value = value; } @Override public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } public Boolean getReliableNotification() { return reliableNotification; } /* NULL lets the client decide */ public void setReliableNotification(Boolean reliableNotification) { this.reliableNotification = reliableNotification; } @Override public String toString() { return getPath(); //TODO implement } @Override public void post(byte[] data) { if (resourceHandler != null){ resourceHandler.onPost(data); } return; } @Override public void changed() { if (serverListener != null){ serverListener.resourceChanged(this); } observeSequenceNumber++; if (observeSequenceNumber > 0xFFFF){ observeSequenceNumber = 0; } /* notify all observers */ for (CoapRequest obsRequest : observer.values()) { CoapServerChannel channel = (CoapServerChannel) obsRequest.getChannel(); CoapResponse response; if (reliableNotification == null){ response = channel.createNotification(obsRequest, CoapResponseCode.Content_205, observeSequenceNumber); } else { response = channel.createNotification(obsRequest, CoapResponseCode.Content_205, observeSequenceNumber, reliableNotification); } response.setPayload(getValue()); channel.sendNotification(response); } } public void registerResourceHandler(ResourceHandler handler){ this.resourceHandler = handler; } public void registerServerListener(ResourceServer server){ this.serverListener = server; } public void unregisterServerListener(ResourceServer server){ this.serverListener = null; } @Override public boolean addObserver(CoapRequest request) { observer.put(request.getChannel(), request); return true; } public void removeObserver(CoapChannel channel){ observer.remove(channel); } public boolean isObservable(){ return observable; } public void setObservable(boolean observable) { this.observable = observable; } public int getObserveSequenceNumber(){ return observeSequenceNumber; } @Override public long expires() { return expires; } @Override public boolean isExpired(){ if (expires == -1){ return false; //-1 == never expires } if(expires < System.currentTimeMillis()){ return true; } else { return false; } } public void setExpires(long expires){ this.expires = expires; } }
Java
package org.ws4d.coap.rest; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.messages.CoapMediaType; /** * Well-Known CoRE support (draft-ietf-core-link-format-05) * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoreResource implements CoapResource { /* use the logger of the resource server */ private final static Logger logger = Logger.getLogger(CoapResourceServer.class); private final static String uriPath = "/.well-known/core"; private HashMap<Resource, String> coreStrings = new HashMap<Resource, String>(); ResourceServer serverListener = null; CoapResourceServer server = null; public CoreResource (CoapResourceServer server){ this.server = server; } /*Hide*/ @SuppressWarnings("unused") private CoreResource (){ } @Override public String getMimeType() { return null; } @Override public String getPath() { return uriPath; } @Override public String getShortName() { return getPath(); } @Override public byte[] getValue() { return buildCoreString(null).getBytes(); } public void registerResource(Resource resource) { if (resource != null) { StringBuilder coreLine = new StringBuilder(); coreLine.append("<"); coreLine.append(resource.getPath()); coreLine.append(">"); // coreLine.append(";ct=???"); coreLine.append(";rt=\"" + resource.getResourceType() + "\""); // coreLine.append(";if=\"observations\""); coreStrings.put(resource, coreLine.toString()); } } private String buildCoreString(String resourceType) { /* TODO: implement filtering also with ct and if*/ HashMap<String, Resource> resources = server.getResources(); StringBuilder returnString = new StringBuilder(); for (Resource resource : resources.values()){ if (resourceType == null || resource.getResourceType() == resourceType) { returnString.append("<"); returnString.append(resource.getPath()); returnString.append(">"); // coreLine.append(";ct=???"); if (resource.getResourceType() != null) { returnString.append(";rt=\"" + resource.getResourceType() + "\""); } // coreLine.append(";if=\"observations\""); returnString.append(","); } } return returnString.toString(); } @Override public byte[] getValue(Vector<String> queries) { for (String query : queries) { if (query.startsWith("rt=")) return buildCoreString(query.substring(3)).getBytes(); } return getValue(); } @Override public String getResourceType() { // TODO implement return null; } @Override public CoapMediaType getCoapMediaType() { return CoapMediaType.link_format; } @Override public void post(byte[] data) { /* nothing happens in case of a post */ return; } @Override public void changed() { } @Override public void registerServerListener(ResourceServer server) { this.serverListener = server; } @Override public void unregisterServerListener(ResourceServer server) { this.serverListener = null; } @Override public boolean addObserver(CoapRequest request) { // TODO: implement. Is this resource observeable? (should) return false; } @Override public void removeObserver(CoapChannel channel) { // TODO: implement. Is this resource observeable? (should) } @Override public boolean isObservable() { return false; } public int getObserveSequenceNumber(){ return 0; } @Override public long expires() { /* expires never */ return -1; } @Override public boolean isExpired() { return false; } }
Java
package org.ws4d.coap.rest; import java.net.URI; /** * A ResourceServer provides network access to resources via a network protocol such as HTTP or CoAP. * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface ResourceServer { /** * * @param resource The resource to be handled. */ /* creates a resource. resource must not exist. if resource exists, false is returned */ public boolean createResource(Resource resource); /* returns the resource at the given path, null if no resource exists*/ public Resource readResource(String path); /* updates a resource. resource must exist. if does not resource exist, false is returned. Resource is NOT created. */ public boolean updateResource(Resource resource); /* deletes resource, returns false is resource does not exist */ public boolean deleteResource(String path); /** * Start the ResourceServer. This usually opens network ports and makes the * resources available through a certain network protocol. */ public void start() throws Exception; /** * Stops the ResourceServer. */ public void stop(); /** * Returns the Host Uri */ public URI getHostUri(); public void resourceChanged(Resource resource); }
Java
package org.ws4d.coap.rest; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface ResourceHandler { public void onPost(byte[] data); }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public final class Constants { public final static int MESSAGE_ID_MIN = 0; public final static int MESSAGE_ID_MAX = 65535; public final static int COAP_MESSAGE_SIZE_MAX = 1152; public final static int COAP_DEFAULT_PORT = 5683; public final static int COAP_DEFAULT_MAX_AGE_S = 60; public final static int COAP_DEFAULT_MAX_AGE_MS = COAP_DEFAULT_MAX_AGE_S * 1000; }
Java
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapServer extends CoapChannelListener { public CoapServer onAccept(CoapRequest request); public void onRequest(CoapServerChannel channel, CoapRequest request); public void onSeparateResponseFailed(CoapServerChannel channel); }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.interfaces; import org.ws4d.coap.messages.AbstractCoapMessage.CoapHeaderOptionType; import org.ws4d.coap.messages.CoapBlockOption; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapPacketType; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapMessage { public static final int RESPONSE_TIMEOUT_MS = 2000; public static final double RESPONSE_RANDOM_FACTOR = 1.5; public static final int MAX_RETRANSMIT = 4; /* TODO: what is the right value? */ public static final int ACK_RST_RETRANS_TIMEOUT_MS = 120000; /* returns the value of the internal message code * in case of an error this function returns -1 */ public int getMessageCodeValue(); public int getMessageID(); public void setMessageID(int msgID); public byte[] serialize(); public void incRetransCounterAndTimeout(); public CoapPacketType getPacketType(); public byte[] getPayload(); public void setPayload(byte[] payload); public void setPayload(char[] payload); public void setPayload(String payload); public int getPayloadLength(); public void setContentType(CoapMediaType mediaType); public CoapMediaType getContentType(); public byte[] getToken(); // public URI getRequestUri(); // // public void setRequestUri(URI uri); //TODO:allow this method only for Clients, Define Token Type CoapBlockOption getBlock1(); void setBlock1(CoapBlockOption blockOption); CoapBlockOption getBlock2(); void setBlock2(CoapBlockOption blockOption); public Integer getObserveOption(); public void setObserveOption(int sequenceNumber); public void removeOption(CoapHeaderOptionType optionType); //TODO: could this compromise the internal state? public String toString(); public CoapChannel getChannel(); public void setChannel(CoapChannel channel); public int getTimeout(); public boolean maxRetransReached(); public boolean isReliable(); public boolean isRequest(); public boolean isResponse(); public boolean isEmpty(); /* unique by remote address, remote port, local port and message id */ public int hashCode(); public boolean equals(Object obj); }
Java
package org.ws4d.coap.interfaces; import java.util.Vector; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapRequest extends CoapMessage{ public void setUriHost(String host); public void setUriPort(int port); public void setUriPath(String path); public void setUriQuery(String query); public void setProxyUri(String proxyUri); public void setToken(byte[] token); public void addAccept(CoapMediaType mediaType); public Vector<CoapMediaType> getAccept(CoapMediaType mediaType); public String getUriHost(); public int getUriPort(); public String getUriPath(); public Vector<String> getUriQuery(); public String getProxyUri(); public void addETag(byte[] etag); public Vector<byte[]> getETag(); public CoapRequestCode getRequestCode(); public void setRequestCode(CoapRequestCode requestCode); }
Java
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; public interface CoapServerChannel extends CoapChannel { /* creates a normal response */ public CoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode); /* creates a normal response */ public CoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode, CoapMediaType contentType); /* creates a separate response and acks the current request witch an empty ACK in case of a CON. * The separate response can be send later using sendSeparateResponse() */ public CoapResponse createSeparateResponse(CoapRequest request, CoapResponseCode responseCode); /* used by a server to send a separate response */ public void sendSeparateResponse(CoapResponse response); /* used by a server to create a notification (observing resources), reliability is base on the request packet type (con or non) */ public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber); /* used by a server to create a notification (observing resources) */ public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber, boolean reliable); /* used by a server to send a notification (observing resources) */ public void sendNotification(CoapResponse response); }
Java
package org.ws4d.coap.interfaces; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapClientChannel extends CoapChannel { public CoapRequest createRequest(boolean reliable, CoapRequestCode requestCode); public void setTrigger(Object o); public Object getTrigger(); }
Java
package org.ws4d.coap.interfaces; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapResponse extends CoapMessage{ /* TODO: Response Code is part of BasicCoapResponse */ public CoapResponseCode getResponseCode(); public void setMaxAge(int maxAge); public long getMaxAge(); public void setETag(byte[] etag); public byte[] getETag(); public void setResponseCode(CoapResponseCode responseCode); }
Java
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ import java.net.InetAddress; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; public interface CoapChannel { public void sendMessage(CoapMessage msg); /*TODO: close when finished, & abort()*/ public void close(); public InetAddress getRemoteAddress(); public int getRemotePort(); /* handles an incomming message */ public void handleMessage(CoapMessage message); /*TODO: implement Error Type*/ public void lostConnection(boolean notReachable, boolean resetByServer); public CoapBlockSize getMaxReceiveBlocksize(); public void setMaxReceiveBlocksize(CoapBlockSize maxReceiveBlocksize); public CoapBlockSize getMaxSendBlocksize(); public void setMaxSendBlocksize(CoapBlockSize maxSendBlocksize); }
Java
/* Copyright [2011] [University of Rostock] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ import java.net.InetAddress; import org.ws4d.coap.messages.BasicCoapRequest; public interface CoapChannelManager { public int getNewMessageID(); /* called by the socket Listener to create a new Server Channel * the Channel Manager then asked the Server Listener if he wants to accept a new connection */ public CoapServerChannel createServerChannel(CoapSocketHandler socketHandler, CoapMessage message, InetAddress addr, int port); /* creates a server socket listener for incoming connections */ public void createServerListener(CoapServer serverListener, int localPort); /* called by a client to create a connection * TODO: allow client to bind to a special port */ public CoapClientChannel connect(CoapClient client, InetAddress addr, int port); /* This function is for testing purposes only, to have a determined message id*/ public void setMessageId(int globalMessageId); public void initRandom(); }
Java
package org.ws4d.coap.interfaces; import java.net.InetAddress; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapSocketHandler { // public void registerResponseListener(CoapResponseListener // responseListener); // public void unregisterResponseListener(CoapResponseListener // responseListener); // public int sendRequest(CoapMessage request); // public void sendResponse(CoapResponse response); // public void establish(DatagramSocket socket); // public void testConfirmation(int msgID); // // public boolean isOpen(); /* TODO */ public CoapClientChannel connect(CoapClient client, InetAddress remoteAddress, int remotePort); public void close(); public void sendMessage(CoapMessage msg); public CoapChannelManager getChannelManager(); int getLocalPort(); void removeClientChannel(CoapClientChannel channel); void removeServerChannel(CoapServerChannel channel); }
Java
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapChannelListener { }
Java
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapClient extends CoapChannelListener { public void onResponse(CoapClientChannel channel, CoapResponse response); public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer); }
Java
package org.ws4d.coap.proxy; import org.apache.log4j.Logger; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.rest.BasicCoapResource; public class ProxyResource extends BasicCoapResource { static Logger logger = Logger.getLogger(Proxy.class); private ProxyResourceKey key = null; public ProxyResource(String path, byte[] value, CoapMediaType mediaType) { super(path, value, mediaType); } public ProxyResourceKey getKey() { return key; } public void setKey(ProxyResourceKey key) { this.key = key; } }
Java
package org.ws4d.coap.proxy; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.rest.BasicCoapResource; import org.ws4d.coap.rest.CoapResourceServer; public class ProxyRestInterface { static Logger logger = Logger.getLogger(Proxy.class); private CoapResourceServer resourceServer; public void start(){ if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); resourceServer.createResource(new ProxyStatisticResource()); try { resourceServer.start(5684); } catch (Exception e) { e.printStackTrace(); } } public class ProxyStatisticResource extends BasicCoapResource{ private ProxyStatisticResource(String path, byte[] value, CoapMediaType mediaType) { super(path, value, mediaType); } public ProxyStatisticResource(){ this("/statistic", null, CoapMediaType.text_plain); } @Override public byte[] getValue(Vector<String> query) { StringBuilder val = new StringBuilder(); ProxyMapper.getInstance().getCoapRequestCount(); val.append("Number of HTTP Requests: " + ProxyMapper.getInstance().getHttpRequestCount() + "\n"); val.append("Number of CoAP Requests: " + ProxyMapper.getInstance().getCoapRequestCount() + "\n"); val.append("Number of Reqeusts served from cache: " + ProxyMapper.getInstance().getServedFromCacheCount() + "\n"); return val.toString().getBytes(); } } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.net.InetAddress; import java.net.URI; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class ProxyMessageContext { /*unique for reqMessageID, remoteHost, remotePort*/ /* * Server Client * inRequest +--------+ TRANSFORM +--------+ outRequest * ------------->| |-----|||---->| |-------------> * | | | | * outResponse | | TRANSFORM | | inResponse * <-------------| |<----|||-----| |<------------- * +--------+ +--------+ * */ /* incomming messages */ private CoapRequest inCoapRequest; //the coapRequest of the origin client (maybe translated) private HttpRequest inHttpRequest; //the httpRequest of the origin client (maybe translated) private CoapResponse inCoapResponse; //the coap response of the final server private HttpResponse inHttpResponse; //the http response of the final server /* generated outgoing messages */ private CoapResponse outCoapResponse; //the coap response send to the client private CoapRequest outCoapRequest; private HttpResponse outHttpResponse; private HttpUriRequest outHttpRequest; /* trigger and channels*/ private CoapClientChannel outCoapClientChannel; NHttpResponseTrigger trigger; //needed by http /* corresponding cached resource*/ private ProxyResource resource; private URI uri; private InetAddress clientAddress; private int clientPort; private InetAddress serverAddress; private int serverPort; /* is true if a translation was done (always true for incoming http requests)*/ private boolean translate; //translate from coap to http /* indicates that the response comes from the cache*/ private boolean cached = false; /* in case of a HTTP Head this is true, GET and HEAD are both mapped to CoAP GET */ private boolean httpHeadMethod = false; /* times */ long requestTime; long responseTime; public ProxyMessageContext(CoapRequest request, boolean translate, URI uri) { this.inCoapRequest = request; this.translate = translate; this.uri = uri; } public ProxyMessageContext(HttpRequest request, boolean translate, URI uri, NHttpResponseTrigger trigger) { this.inHttpRequest = request; this.translate = translate; this.uri = uri; this.trigger = trigger; } public boolean isCoapRequest(){ return inCoapRequest != null; } public boolean isHttpRequest(){ return inHttpRequest != null; } public CoapRequest getInCoapRequest() { return inCoapRequest; } public void setInCoapRequest(CoapRequest inCoapRequest) { this.inCoapRequest = inCoapRequest; } public HttpRequest getInHttpRequest() { return inHttpRequest; } public void setInHttpRequest(HttpRequest inHttpRequest) { this.inHttpRequest = inHttpRequest; } public CoapResponse getInCoapResponse() { return inCoapResponse; } public void setInCoapResponse(CoapResponse inCoapResponse) { this.inCoapResponse = inCoapResponse; } public HttpResponse getInHttpResponse() { return inHttpResponse; } public void setInHttpResponse(HttpResponse inHttpResponse) { this.inHttpResponse = inHttpResponse; } public CoapResponse getOutCoapResponse() { return outCoapResponse; } public void setOutCoapResponse(CoapResponse outCoapResponse) { this.outCoapResponse = outCoapResponse; } public CoapRequest getOutCoapRequest() { return outCoapRequest; } public void setOutCoapRequest(CoapRequest outCoapRequest) { this.outCoapRequest = outCoapRequest; } public HttpResponse getOutHttpResponse() { return outHttpResponse; } public void setOutHttpResponse(HttpResponse outHttpResponse) { this.outHttpResponse = outHttpResponse; } public HttpUriRequest getOutHttpRequest() { return outHttpRequest; } public void setOutHttpRequest(HttpUriRequest outHttpRequest) { this.outHttpRequest = outHttpRequest; } public CoapClientChannel getOutCoapClientChannel() { return outCoapClientChannel; } public void setOutCoapClientChannel(CoapClientChannel outClientChannel) { this.outCoapClientChannel = outClientChannel; } public InetAddress getClientAddress() { return clientAddress; } public void setClientAddress(InetAddress clientAddress, int clientPort) { this.clientAddress = clientAddress; this.clientPort = clientPort; } public InetAddress getServerAddress() { return serverAddress; } public void setServerAddress(InetAddress serverAddress, int serverPort) { this.serverAddress = serverAddress; this.serverPort = serverPort; } public int getClientPort() { return clientPort; } public int getServerPort() { return serverPort; } public boolean isTranslate() { return translate; } public void setTranslatedCoapRequest(CoapRequest request) { this.inCoapRequest = request; } public void setTranslatedHttpRequest(HttpRequest request) { this.inHttpRequest = request; } public URI getUri() { return uri; } public NHttpResponseTrigger getTrigger() { return trigger; } public boolean isCached() { return cached; } public void setCached(boolean cached) { this.cached = cached; } public ProxyResource getResource() { return resource; } public void setResource(ProxyResource resource) { this.resource = resource; } public void setHttpHeadMethod(boolean httpHeadMethod) { this.httpHeadMethod = httpHeadMethod; } public boolean isHttpHeadMethod() { return httpHeadMethod; } public long getRequestTime() { return requestTime; } public void setRequestTime(long requestTime) { this.requestTime = requestTime; } public long getResponseTime() { return responseTime; } public void setResponseTime(long responseTime) { this.responseTime = responseTime; } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import net.sf.ehcache.config.CacheConfiguration; import net.sf.ehcache.store.MemoryStoreEvictionPolicy; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ /* * TODO's: * - implement Date option as described in "Connecting the Web with the Web of Things: Lessons Learned From Implementing a CoAP-HTTP Proxy" * - caching of HTTP resources not supported as HTTP servers may have enough resources (in terms of RAM/ROM/batery/computation) * * */ public class ProxyCache { static Logger logger = Logger.getLogger(Proxy.class); private static final int MAX_LIFETIME = Integer.MAX_VALUE; private static Cache cache; private static CacheManager cacheManager; private boolean enabled = true; private static final int defaultMaxAge = org.ws4d.coap.Constants.COAP_DEFAULT_MAX_AGE_S; private static final ProxyCacheTimePolicy cacheTimePolicy = ProxyCacheTimePolicy.Halftime; public ProxyCache() { cacheManager = CacheManager.create(); cache = new Cache(new CacheConfiguration("proxy", 100) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) .overflowToDisk(true) .eternal(false) .diskPersistent(false) .diskExpiryThreadIntervalSeconds(0)); cacheManager.addCache(cache); } public void removeKey(URI uri) { cache.remove(uri); } // public void put(ProxyMessageContext context) { // if (isEnabled() || context == null){ // return; // } // //TODO: check for overwrites // // // insertElement(context.getResource().getKey(), context.getResource()); //// URI uri = context.getUri(); //// if (uri.getScheme().equalsIgnoreCase("coap")){ //// putCoapRes(uri, context.getCoapResponse()); //// } else if (uri.getScheme().equalsIgnoreCase("http")){ //// putHttpRes(uri, context.getHttpResponse()); //// } // } // private void putHttpRes(URI uri, HttpResponse response){ // if (response == null){ // return; // } // logger.info( "Cache HTTP Resource (" + uri.toString() + ")"); // //first determine what to do // int code = response.getStatusLine().getStatusCode(); // // //make some garbage collection to avoid a cache overflow caused by many expired elements (when 80% charged as first idea) // if (cache.getSize() > cache.getCacheConfiguration().getMaxElementsInMemory()*0.8) { // cache.evictExpiredElements(); // } // // //set the max-age of new element // //use the http-header-options expires and date // //difference is the same value as the corresponding max-age from coap-response, but at this point we only have a http-response // int timeToLive = 0; // Header[] expireHeaders = response.getHeaders("Expires"); // if (expireHeaders.length == 1) { // String expire = expireHeaders[0].getValue(); // Date expireDate = StringToDate(expire); // // Header[] dateHeaders = response.getHeaders("Date"); // if (dateHeaders.length == 1) { // String dvalue = dateHeaders[0].getValue(); // Date date = StringToDate(dvalue); // // timeToLive = (int) ((expireDate.getTime() - date.getTime()) / 1000); // } // } // // //cache-actions are dependent of response-code, as described in coap-rfc-draft-7 // switch(code) { // case HttpStatus.SC_CREATED: { // if (cache.isKeyInCache(uri)) { // markExpired(uri); // } // break; // } // case HttpStatus.SC_NO_CONTENT: { // if (cache.isKeyInCache(uri)) { // markExpired(uri); // } // break; // } // case HttpStatus.SC_NOT_MODIFIED: { // if (cache.isKeyInCache(uri)) { // insertElement(uri, response, timeToLive); //should update the response if req is already in cache // } // break; // } // default: { // insertElement(uri, response, timeToLive); // break; // } // } // } // private void putCoapRes(ProxyResourceKey key, CoapResponse response){ // if (response == null){ // return; // } // logger.debug( "Cache CoAP Resource (" + uri.toString() + ")"); // // long timeToLive = response.getMaxAge(); // if (timeToLive < 0){ // timeToLive = defaultTimeToLive; // } // insertElement(key, response); // } // // public HttpResponse getHttpRes(URI uri) { // if (defaultTimeToLive == 0) return null; // if (cache.getQuiet(uri) != null) { // Object o = cache.get(uri).getObjectValue(); // logger.debug( "Found in cache (" + uri.toString() + ")"); // return (HttpResponse) o; // } else { // logger.debug( "Not in cache (" + uri.toString() + ")"); // return null; // } // } // // public CoapResponse getCoapRes(URI uri) { // if (defaultTimeToLive == 0) return null; // // if (cache.getQuiet(uri) != null) { // Object o = cache.get(uri).getObjectValue(); // logger.debug( "Found in cache (" + uri.toString() + ")"); // return (CoapResponse) o; // }else{ // logger.debug( "Not in cache (" + uri.toString() + ")"); // return null; // } // } public boolean isInCache(ProxyResourceKey key) { if (!isEnabled()){ return false; } if (cache.isKeyInCache(key)) { return true; } else { return false; } } //for some operations it is necessary to build an http-date from string private static Date StringToDate(String string_date) { Date date = null; //this pattern is the official http-date format final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_RFC1123, Locale.US); formatter.setTimeZone(TimeZone.getDefault()); //CEST, default is GMT try { date = (Date) formatter.parse(string_date); } catch (ParseException e) { e.printStackTrace(); } return date; } // //mark an element as expired // private void markExpired(ProxyResourceKey key) { // if (cache.getQuiet(key) != null) { // cache.get(key).setTimeToLive(0); // } // } private boolean insertElement(ProxyResourceKey key, ProxyResource resource) { Element elem = new Element(key, resource); if (resource.expires() == -1) { /* never expires */ cache.put(elem); } else { long ttl = resource.expires() - System.currentTimeMillis(); if (ttl > 0) { /* limit the maximum lifetime */ if (ttl > MAX_LIFETIME) { ttl = MAX_LIFETIME; } elem.setTimeToLive((int) ttl); cache.put(elem); logger.debug("cache insert: " + resource.getPath() ); } else { /* resource is already expired */ return false; } } return true; } private void updateTtl(ProxyResourceKey key, long newExpires) { /*getQuiet is used to not update statistics */ Element elem = cache.getQuiet(key); if (elem != null) { long ttl = newExpires - System.currentTimeMillis(); if (ttl > 0 || newExpires == -1 ) { /* limit the maximum lifetime */ if (ttl > MAX_LIFETIME) { ttl = MAX_LIFETIME; } elem.setTimeToLive((int) ttl); } } } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public ProxyResource get(ProxyMessageContext context) { if (!isEnabled()){ return null; } String path = context.getUri().getPath(); if(path == null){ /* no caching */ return null; } Element elem = cache.get(new ProxyResourceKey(context.getServerAddress(), context.getServerPort(), path)); logger.debug("cache get: " + context.getServerAddress().toString() + " " + context.getServerPort() + " " + path); if (elem != null) { /* found cached entry */ ProxyResource res = (ProxyResource) elem.getObjectValue(); if (!res.isExpired()) { return res; } } return null; } public void cacheHttpResponse(ProxyMessageContext context) { if (!isEnabled()){ return; } /* TODO caching of HTTP responses currently not supported (not use to unload HTTP servers) */ return; } public void cacheCoapResponse(ProxyMessageContext context) { if (!isEnabled()){ return; } CoapResponse response = context.getInCoapResponse(); String path = context.getUri().getPath(); if(path == null){ /* no caching */ return; } ProxyResourceKey key = new ProxyResourceKey(context.getServerAddress(), context.getServerPort(), path); /* NOTE: * - currently caching is only implemented for success error codes (2.xx) * - not fresh resources are removed (could be used for validation model)*/ switch (context.getInCoapResponse().getResponseCode()) { case Created_201: /* A cache SHOULD mark any stored response for the created resource as not fresh. This response is not cacheable.*/ cache.remove(key); break; case Deleted_202: /* This response is not cacheable. However, a cache SHOULD mark any stored response for the deleted resource as not fresh.*/ cache.remove(key); break; case Valid_203: /* When a cache receives a 2.03 (Valid) response, it needs to update the stored response with the value of the Max-Age Option included in the response (see Section 5.6.2). */ //TODO break; case Changed_204: /* This response is not cacheable. However, a cache SHOULD mark any stored response for the changed resource as not fresh. */ cache.remove(key); break; case Content_205: /* This response is cacheable: Caches can use the Max-Age Option to determine freshness (see Section 5.6.1) and (if present) the ETag Option for validation (see Section 5.6.2).*/ /* CACHE RESOURCE */ ProxyResource resource = new ProxyResource(path, response.getPayload(), response.getContentType()); resource.setExpires(cacheTimePolicy.calcExpires(context.getRequestTime(), context.getResponseTime(), response.getMaxAge())); insertElement(key, resource); break; default: break; } } public enum ProxyCacheTimePolicy{ Request(0), Response(1), Halftime(2); int state; private ProxyCacheTimePolicy(int state){ this.state = state; } public long calcExpires(long requestTime, long responseTime, long maxAge){ if (maxAge == -1){ maxAge = defaultMaxAge; } switch (this) { case Request: return requestTime + (maxAge * 1000) ; case Response: return responseTime + (maxAge * 1000); case Halftime: return requestTime + ((responseTime - requestTime) / 2) + (maxAge * 1000); } return 0; } } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.concurrent.ArrayBlockingQueue; import org.apache.log4j.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class CoapServerProxy implements CoapServer{ static Logger logger = Logger.getLogger(Proxy.class); private static final int LOCAL_PORT = 5683; //port on which the server is listening ProxyMapper mapper = ProxyMapper.getInstance(); //coapOUTq_ receives a coap-response from mapper in case of coap-http CoapChannelManager channelManager; //constructor of coapserver-class, initiates the jcoap-components and starts CoapSender public CoapServerProxy() { channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(this, LOCAL_PORT); } //interface-function for the message-queue public void sendResponse(ProxyMessageContext context) { CoapServerChannel channel = (CoapServerChannel) context.getInCoapRequest().getChannel(); channel.sendMessage(context.getOutCoapResponse()); channel.close(); //TODO: implement strategy when to close a channel } @Override public CoapServer onAccept(CoapRequest request) { logger.info("new incomming CoAP connection"); /* accept every incoming connection */ return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { /* draft-08: * CoAP distinguishes between requests to an origin server and a request made through a proxy. A proxy is a CoAP end-point that can be tasked by CoAP clients to perform requests on their behalf. This may be useful, for example, when the request could otherwise not be made, or to service the response from a cache in order to reduce response time and network bandwidth or energy consumption. CoAP requests to a proxy are made as normal confirmable or non- confirmable requests to the proxy end-point, but specify the request URI in a different way: The request URI in a proxy request is specified as a string in the Proxy-Uri Option (see Section 5.10.3), while the request URI in a request to an origin server is split into the Uri-Host, Uri-Port, Uri-Path and Uri-Query Options (see Section 5.10.2). */ URI proxyUri = null; /* we need to cast to allow an efficient header copy */ //create a prototype response, will be changed during the translation process try { BasicCoapResponse response = (BasicCoapResponse) channel.createResponse(request, CoapResponseCode.Internal_Server_Error_500); try { proxyUri = new URI(request.getProxyUri()); } catch (Exception e) { proxyUri = null; } if (proxyUri == null) { /* PROXY URI MUST BE AVAILABLE */ logger.warn("received CoAP request without Proxy-Uri option"); channel.sendMessage(channel.createResponse(request, CoapResponseCode.Bad_Request_400)); channel.close(); return; } /* check scheme if we should translate */ boolean translate; if (proxyUri.getScheme().compareToIgnoreCase("http") == 0) { translate = true; } else if (proxyUri.getScheme().compareToIgnoreCase("coap") == 0) { translate = false; } else { /* unknown scheme */ logger.warn("invalid proxy uri scheme"); channel.sendMessage(channel.createResponse(request, CoapResponseCode.Bad_Request_400)); channel.close(); return; } /* parse URL */ InetAddress serverAddress = InetAddress.getByName(proxyUri.getHost()); int serverPort = proxyUri.getPort(); if (serverPort == -1) { if (translate) { /* HTTP Server */ serverPort = 80; // FIXME: use constant for HTTP well known // port } else { /* CoAP Server */ serverPort = org.ws4d.coap.Constants.COAP_DEFAULT_PORT; } } /* generate context and forward message */ ProxyMessageContext context = new ProxyMessageContext(request, translate, proxyUri); context.setServerAddress(serverAddress, serverPort); context.setOutCoapResponse(response); mapper.handleCoapServerRequest(context); } catch (Exception e) { logger.warn("invalid message"); channel.sendMessage(channel.createResponse(request, CoapResponseCode.Bad_Request_400)); channel.close(); } } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { // TODO Auto-generated method stub } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.io.IOException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.MethodNotSupportedException; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.UnsupportedHttpVersionException; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate; import org.apache.http.nio.entity.NByteArrayEntity; import org.apache.http.nio.entity.NHttpEntityWrapper; import org.apache.http.nio.entity.ProducingNHttpEntity; import org.apache.http.nio.protocol.NHttpHandlerBase; import org.apache.http.nio.protocol.NHttpRequestHandler; import org.apache.http.nio.protocol.NHttpRequestHandlerResolver; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.DefaultedHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpExpectationVerifier; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.EncodingUtils; /** * Fully asynchronous HTTP server side protocol handler implementation that * implements the essential requirements of the HTTP protocol for the server * side message processing as described by RFC . It is capable of processing * HTTP requests with nearly constant memory footprint. Only HTTP message heads * are stored in memory, while content of message bodies is streamed directly * from the entity to the underlying channel (and vice versa) * {@link ConsumingNHttpEntity} and {@link ProducingNHttpEntity} interfaces. * <p/> * When using this class, it is important to ensure that entities supplied for * writing implement {@link ProducingNHttpEntity}. Doing so will allow the * entity to be written out asynchronously. If entities supplied for writing do * not implement {@link ProducingNHttpEntity}, a delegate is added that buffers * the entire contents in memory. Additionally, the buffering might take place * in the I/O thread, which could cause I/O to block temporarily. For best * results, ensure that all entities set on {@link HttpResponse}s from * {@link NHttpRequestHandler}s implement {@link ProducingNHttpEntity}. * <p/> * If incoming requests enclose a content entity, {@link NHttpRequestHandler}s * are expected to return a {@link ConsumingNHttpEntity} for reading the * content. After the entity is finished reading the data, * {@link NHttpRequestHandler#handle(HttpRequest, HttpResponse, NHttpResponseTrigger, HttpContext)} * is called to generate a response. * <p/> * Individual {@link NHttpRequestHandler}s do not have to submit a response * immediately. They can defer transmission of the HTTP response back to the * client without blocking the I/O thread and to delegate the processing the * HTTP request to a worker thread. The worker thread in its turn can use an * instance of {@link NHttpResponseTrigger} passed as a parameter to submit * a response as at a later point of time once the response becomes available. * * @see ConsumingNHttpEntity * @see ProducingNHttpEntity * * @since 4.0 */ /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class ModifiedAsyncNHttpServiceHandler extends NHttpHandlerBase implements NHttpServiceHandler { protected final HttpResponseFactory responseFactory; protected NHttpRequestHandlerResolver handlerResolver; protected HttpExpectationVerifier expectationVerifier; public ModifiedAsyncNHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final ByteBufferAllocator allocator, final HttpParams params) { super(httpProcessor, connStrategy, allocator, params); if (responseFactory == null) { throw new IllegalArgumentException("Response factory may not be null"); } this.responseFactory = responseFactory; } public ModifiedAsyncNHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final HttpParams params) { this(httpProcessor, responseFactory, connStrategy, new HeapByteBufferAllocator(), params); } public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) { this.expectationVerifier = expectationVerifier; } public void setHandlerResolver(final NHttpRequestHandlerResolver handlerResolver) { this.handlerResolver = handlerResolver; } public void connected(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = new ServerConnState(); context.setAttribute(CONN_STATE, connState); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); if (this.eventListener != null) { this.eventListener.connectionOpen(conn); } } public void requestReceived(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); HttpRequest request = conn.getHttpRequest(); request.setParams(new DefaultedHttpParams(request.getParams(), this.params)); connState.setRequest(request); NHttpRequestHandler requestHandler = getRequestHandler(request); connState.setRequestHandler(requestHandler); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } HttpResponse response; try { if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; if (entityRequest.expectContinue()) { response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_CONTINUE, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); if (this.expectationVerifier != null) { try { this.expectationVerifier.verify(request, response, context); } catch (HttpException ex) { response = this.responseFactory.newHttpResponse( HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(ex, response); } } if (response.getStatusLine().getStatusCode() < 200) { // Send 1xx response indicating the server expections // have been met conn.submitResponse(response); } else { conn.resetInput(); sendResponse(conn, request, response); } } // Request content is expected. ConsumingNHttpEntity consumingEntity = null; // Lookup request handler for this request if (requestHandler != null) { consumingEntity = requestHandler.entityRequest(entityRequest, context); } if (consumingEntity == null) { consumingEntity = new ConsumingNHttpEntityTemplate( entityRequest.getEntity(), new ByteContentListener()); } entityRequest.setEntity(consumingEntity); connState.setConsumingEntity(consumingEntity); } else { // No request content is expected. // Process request right away conn.suspendInput(); processRequest(conn, request); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void closed(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); try { connState.reset(); } catch (IOException ex) { if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } if (this.eventListener != null) { this.eventListener.connectionClosed(conn); } } public void exception(final NHttpServerConnection conn, final HttpException httpex) { if (conn.isResponseSubmitted()) { // There is not much that we can do if a response head // has already been submitted closeConnection(conn, httpex); if (eventListener != null) { eventListener.fatalProtocolException(httpex, conn); } return; } HttpContext context = conn.getContext(); try { HttpResponse response = this.responseFactory.newHttpResponse( HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(httpex, response); response.setEntity(null); sendResponse(conn, null, response); } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void exception(final NHttpServerConnection conn, final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } public void timeout(final NHttpServerConnection conn) { handleTimeout(conn); } public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); HttpRequest request = connState.getRequest(); ConsumingNHttpEntity consumingEntity = connState.getConsumingEntity(); try { consumingEntity.consumeContent(decoder, conn); if (decoder.isCompleted()) { conn.suspendInput(); processRequest(conn, request); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void responseReady(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); if (connState.isHandled()) { return; } HttpRequest request = connState.getRequest(); try { IOException ioex = connState.getIOException(); if (ioex != null) { throw ioex; } HttpException httpex = connState.getHttpException(); if (httpex != null) { HttpResponse response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(httpex, response); connState.setResponse(response); } HttpResponse response = connState.getResponse(); if (response != null) { connState.setHandled(true); sendResponse(conn, request, response); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); HttpResponse response = conn.getHttpResponse(); try { ProducingNHttpEntity entity = connState.getProducingEntity(); entity.produceContent(encoder, conn); if (encoder.isCompleted()) { connState.finishOutput(); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready to process new request connState.reset(); conn.requestInput(); } responseComplete(response, context); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } } private void handleException(final HttpException ex, final HttpResponse response) { int code = HttpStatus.SC_INTERNAL_SERVER_ERROR; if (ex instanceof MethodNotSupportedException) { code = HttpStatus.SC_NOT_IMPLEMENTED; } else if (ex instanceof UnsupportedHttpVersionException) { code = HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED; } else if (ex instanceof ProtocolException) { code = HttpStatus.SC_BAD_REQUEST; } response.setStatusCode(code); byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage()); NByteArrayEntity entity = new NByteArrayEntity(msg); entity.setContentType("text/plain; charset=US-ASCII"); response.setEntity(entity); } /** * @throws HttpException - not thrown currently */ private void processRequest( final NHttpServerConnection conn, final HttpRequest request) throws IOException, HttpException { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } NHttpResponseTrigger trigger = new ResponseTriggerImpl(connState, conn); try { this.httpProcessor.process(request, context); NHttpRequestHandler handler = connState.getRequestHandler(); if (handler != null) { HttpResponse response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_OK, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handler.handle( request, response, trigger, context); } else { HttpResponse response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_NOT_IMPLEMENTED, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); trigger.submitResponse(response); } } catch (HttpException ex) { trigger.handleException(ex); } } private void sendResponse( final NHttpServerConnection conn, final HttpRequest request, final HttpResponse response) throws IOException, HttpException { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); // Now that a response is ready, we can cleanup the listener for the request. connState.finishInput(); // Some processers need the request that generated this response. context.setAttribute(ExecutionContext.HTTP_REQUEST, request); this.httpProcessor.process(response, context); context.setAttribute(ExecutionContext.HTTP_REQUEST, null); if (response.getEntity() != null && !canResponseHaveBody(request, response)) { response.setEntity(null); } HttpEntity entity = response.getEntity(); if (entity != null) { if (entity instanceof ProducingNHttpEntity) { connState.setProducingEntity((ProducingNHttpEntity) entity); } else { connState.setProducingEntity(new NHttpEntityWrapper(entity)); } } conn.submitResponse(response); if (entity == null) { if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready to process new request connState.reset(); conn.requestInput(); } responseComplete(response, context); } } /** * Signals that this response has been fully sent. This will be called after * submitting the response to a connection, if there is no entity in the * response. If there is an entity, it will be called after the entity has * completed. */ protected void responseComplete(HttpResponse response, HttpContext context) { } private NHttpRequestHandler getRequestHandler(HttpRequest request) { NHttpRequestHandler handler = null; if (this.handlerResolver != null) { String requestURI = request.getRequestLine().getUri(); handler = this.handlerResolver.lookup(requestURI); } return handler; } protected static class ServerConnState { private volatile NHttpRequestHandler requestHandler; private volatile HttpRequest request; private volatile ConsumingNHttpEntity consumingEntity; private volatile HttpResponse response; private volatile ProducingNHttpEntity producingEntity; private volatile IOException ioex; private volatile HttpException httpex; private volatile boolean handled; public void finishInput() throws IOException { if (this.consumingEntity != null) { this.consumingEntity.finish(); this.consumingEntity = null; } } public void finishOutput() throws IOException { if (this.producingEntity != null) { this.producingEntity.finish(); this.producingEntity = null; } } public void reset() throws IOException { finishInput(); this.request = null; finishOutput(); this.handled = false; this.response = null; this.ioex = null; this.httpex = null; this.requestHandler = null; } public NHttpRequestHandler getRequestHandler() { return this.requestHandler; } public void setRequestHandler(final NHttpRequestHandler requestHandler) { this.requestHandler = requestHandler; } public HttpRequest getRequest() { return this.request; } public void setRequest(final HttpRequest request) { this.request = request; } public ConsumingNHttpEntity getConsumingEntity() { return this.consumingEntity; } public void setConsumingEntity(final ConsumingNHttpEntity consumingEntity) { this.consumingEntity = consumingEntity; } public HttpResponse getResponse() { return this.response; } public void setResponse(final HttpResponse response) { this.response = response; } public ProducingNHttpEntity getProducingEntity() { return this.producingEntity; } public void setProducingEntity(final ProducingNHttpEntity producingEntity) { this.producingEntity = producingEntity; } public IOException getIOException() { return this.ioex; } @Deprecated public IOException getIOExepction() { return this.ioex; } public void setIOException(final IOException ex) { this.ioex = ex; } @Deprecated public void setIOExepction(final IOException ex) { this.ioex = ex; } public HttpException getHttpException() { return this.httpex; } @Deprecated public HttpException getHttpExepction() { return this.httpex; } public void setHttpException(final HttpException ex) { this.httpex = ex; } @Deprecated public void setHttpExepction(final HttpException ex) { this.httpex = ex; } public boolean isHandled() { return this.handled; } public void setHandled(boolean handled) { this.handled = handled; } } private static class ResponseTriggerImpl implements NHttpResponseTrigger { private final ServerConnState connState; private final IOControl iocontrol; private volatile boolean triggered; public ResponseTriggerImpl(final ServerConnState connState, final IOControl iocontrol) { super(); this.connState = connState; this.iocontrol = iocontrol; } public void submitResponse(final HttpResponse response) { if (response == null) { throw new IllegalArgumentException("Response may not be null"); } if (this.triggered) { throw new IllegalStateException("Response already triggered"); } this.triggered = true; this.connState.setResponse(response); this.iocontrol.requestOutput(); } public void handleException(final HttpException ex) { if (this.triggered) { throw new IllegalStateException("Response already triggered"); } this.triggered = true; this.connState.setHttpException(ex); this.iocontrol.requestOutput(); } public void handleException(final IOException ex) { if (this.triggered) { throw new IllegalStateException("Response already triggered"); } this.triggered = true; this.connState.setIOException(ex); this.iocontrol.requestOutput(); } } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.impl.nio.client.DefaultHttpAsyncClient; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.client.HttpAsyncClient; import org.apache.http.nio.concurrent.FutureCallback; import org.apache.http.nio.reactor.IOReactorException; import org.apache.log4j.Logger; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class HttpClientNIO extends Thread { static Logger logger = Logger.getLogger(Proxy.class); ProxyMapper mapper = ProxyMapper.getInstance(); HttpAsyncClient httpClient; public HttpClientNIO() { try { httpClient = new DefaultHttpAsyncClient(); } catch (IOReactorException e) { System.exit(-1); e.printStackTrace(); } httpClient.start(); logger.info("HTTP client started"); } public void sendRequest(ProxyMessageContext context) { // future is used to receive response asynchronous, without blocking //ProxyHttpFutureCallback allows to associate a ProxyMessageContext logger.info("send HTTP request"); ProxyHttpFutureCallback fc = new ProxyHttpFutureCallback(); fc.setContext(context); httpClient.execute(context.getOutHttpRequest(), fc); } private class ProxyHttpFutureCallback implements FutureCallback<HttpResponse>{ private ProxyMessageContext context = null; public void setContext(ProxyMessageContext context) { this.context = context; } // this is called when response is received public void completed(final HttpResponse response) { if (context != null) { context.setInHttpResponse(response); mapper.handleHttpClientResponse(context); } } public void failed(final Exception ex) { logger.warn("HTTP client request failed"); if (context != null) { context.setInHttpResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, ex.getMessage())); mapper.handleHttpClientResponse(context); } } public void cancelled() { logger.warn("HTTP Client Request cancelled"); if (context != null) { /* null indicates no response */ context.setInHttpResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "http connection canceled")); mapper.handleHttpClientResponse(context); } } } }
Java