⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bluepad.java

📁 E-WhiteBoard with Bluetooth
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
//------------------------------------------------------------------
//  ____                      _____      _                           
// / ___|  ___  _ __  _   _  | ____|_ __(_) ___ ___ ___  ___  _ __   
// \___ \ / _ \| '_ \| | | | |  _| | '__| |/ __/ __/ __|/ _ \| '_ \  
//  ___) | (_) | | | | |_| | | |___| |  | | (__\__ \__ \ (_) | | | | 
// |____/ \___/|_| |_|\__, | |_____|_|  |_|\___|___/___/\___/|_| |_| 
//                    |___/                                          
//------------------------------------------------------------------
// Copyright (c) 2003 Sony Ericsson Mobile Communications AB
//                    Research Trinagle Park, NC 27709
//  
// This software is provided "AS IS," without a warranty of any kind. 
// ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, 
// INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A 
// PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED.
//
//------------------------------------------------------------------
package example.bluetooth;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.bluetooth.*;  
import java.io.IOException;
import java.util.*;
import javax.microedition.io.*;

/**
 * The BluePad MIDlet. 
 * This MIDlet creates a canvas which is a scratch pad or white board 
 * when connected to another phone running this same MIDlet, anything 
 * you draw on one screen will automatically appear on the other screen.
 * The mobile phone must support touch screen and the BlueTooth API.
 *
 * @author Paul H. Nichols
 * @version 1.0
 */
public class BluePad extends MIDlet implements CommandListener, DiscoveryListener, Runnable {

    Display display;

    static int DISCONNECT = 1;
    static int CONNECTING = 2;
    static int CONNECT    = 3;

    private int state = DISCONNECT;

    private BluePadServer server = null;
    private BluePadClient client = null;
    private boolean serverMode = false;

    Timer checkXmtTimer = null;
    Vector drawLineStack = new Vector();

    // Displayables
    BluePadCanvas canvas;
    List colorList;
    List clientServerList;
    TextBox debugTextBox;
    List deviceList;

    private static String CMD_CLEARDBG    = "Clear Debug";
    private static String CMD_BACK        = "Back";
    private static String CMD_OK          = "OK";
    private static String CMD_CANCEL      = "Cancel";
    private static String CMD_PENCOLOR    = "Pen Color";
    private static String CMD_CLEARSCREEN = "Clear Screen";
    private static String CMD_CONNECT     = "Connect";
    private static String CMD_REFRESH     = "Refresh";
    private static String CMD_DISCONNECT  = "Disconnect";
    private static String CMD_DEBUGINFO   = "Debug Info";
    private static String CMD_EXIT        = "Exit";
    private static String CMD_ABOUT       = "About";

    // COMMANDS
    private Command disconnectCommand;
    private Command connectCommand;
    private Command exitCommand;

    private static boolean DEBUG = false;

    private static String COLOR_BLACK = "Black";
    private static String COLOR_RED   = "Red";
    private static String COLOR_GREEN = "Green";
    private static String COLOR_BLUE  = "Blue";

    private static String ERASER  = "Eraser";

    private static String CONNECT_CLIENT  = "Client";
    private static String CONNECT_SERVER  = "Server";


    private static byte COMMAND_DRAW_LINE = 0x01;
    private static byte COMMAND_CLEAR_SCREEN = 0x02;
    private static byte COMMAND_ERASE_RECT = 0x03;


    public static String MY_SERVICE_NUMBER =  "1020304050d0708093a1b121d1e1f100";
    private static long UDI_L2CAP        = 0x0100;

    public static BluePad test;


    // Receive processing
    // Bytes left over from previous DS
    private byte currentRcvBuf[] = null;
    private int currentRcvIdx = 0;

    private Vector rcvDataStack = new Vector();

    // Transmit processing
    private byte xmtBuffer[];
    private int xmtIndex;
    private L2CAPConnection conn;

    // Bluetooth discovery
    private DiscoveryAgent discoveryAgent;
    private Hashtable bluetoothDevices = new Hashtable();
    private ServiceRecord record;
    private boolean foundService = false;

    // About Box
    private About about = new About();


    /**
     * Constructor for BluePad MIDlet.
     */
    public BluePad()
    {
        // Handle to self
        test = this;

        // Get a handle on the display object
        display = Display.getDisplay(this);

        disconnectCommand = new Command(CMD_DISCONNECT, Command.STOP, 8);
        connectCommand = new Command(CMD_CONNECT, Command.SCREEN, 8);
        exitCommand = new Command(CMD_EXIT, Command.EXIT, 99);

        // debugTextBox
        debugTextBox = new TextBox("Debug Info", null, 4096, TextField.ANY);
        debugTextBox.addCommand(new Command(CMD_CLEARDBG, Command.SCREEN, 1));
        debugTextBox.addCommand(new Command(CMD_BACK, Command.SCREEN, 2));
        debugTextBox.addCommand(exitCommand);
        debugTextBox.setCommandListener(this);

        // Create the BluePad Canvas
        canvas = new BluePadCanvas(this);
        canvas.addCommand(new Command(CMD_PENCOLOR, Command.SCREEN, 1));
        canvas.addCommand(new Command(CMD_CLEARSCREEN, Command.SCREEN, 2));
        canvas.addCommand(new Command(CMD_ABOUT, Command.HELP, 3));
        canvas.addCommand(connectCommand);
        if (DEBUG) {
            canvas.addCommand(new Command(CMD_DEBUGINFO, Command.SCREEN, 90));
        }
        canvas.addCommand(exitCommand);
        canvas.setCommandListener(this);

        // Color List
        colorList = new List("Set Pen Color", List.EXCLUSIVE);
        colorList.append(COLOR_BLACK, null);
        colorList.append(COLOR_RED, null);
        colorList.append(COLOR_GREEN, null);
        colorList.append(COLOR_BLUE, null);
        colorList.append(ERASER, null);
        colorList.addCommand(new Command(CMD_OK, Command.OK, 1));
        colorList.setCommandListener(this);

        // Client Server List
        clientServerList = new List("Connect Mode", List.EXCLUSIVE);
        clientServerList.append(CONNECT_SERVER, null);
        clientServerList.append(CONNECT_CLIENT, null);
        clientServerList.addCommand(new Command(CMD_OK, Command.OK, 1));
        clientServerList.addCommand(new Command(CMD_CANCEL, Command.CANCEL, 2));
        if (DEBUG) {
            clientServerList.addCommand(new Command(CMD_DEBUGINFO, Command.SCREEN, 90));
        }
        clientServerList.addCommand(exitCommand);
        clientServerList.setCommandListener(this);

        // Device List
        deviceList = new List("Select Device", List.EXCLUSIVE);
        deviceList.addCommand(new Command(CMD_OK, Command.OK, 1));
        deviceList.addCommand(new Command(CMD_REFRESH, Command.SCREEN, 2));
        deviceList.addCommand(new Command(CMD_CANCEL, Command.CANCEL, 3));
        if (DEBUG) {
            deviceList.addCommand(new Command(CMD_DEBUGINFO, Command.SCREEN, 90));
        }
        deviceList.addCommand(exitCommand);
        deviceList.setCommandListener(this);

    }  

    public int getState() {
        return state;
    }

    // ******* Implement MIDlet API ******* 
    public void startApp() throws MIDletStateChangeException {
        display.setCurrent(canvas);

        // Start a BT device search
        doBluetoothDiscovery();
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) 
    throws MIDletStateChangeException 
    {
        notifyDestroyed();
    }

    /*
     * Respond to a command issued on the Canvas.
     */
    public void commandAction(Command c, Displayable s) {
        printString("CommandAction: " + c.getLabel());

        // Exit
        if (c.getLabel().equals(CMD_EXIT) && c == exitCommand) {
            try {
                destroyApp(false);
            }
            catch (MIDletStateChangeException ex) {
            }
            return;

        }       

        // Set Pen Color
        if (c.getLabel().equals(CMD_PENCOLOR)) {
            display.setCurrent(colorList);
            return;
        }

        // Clear debug info
        if (DEBUG) {
            if (c.getLabel().equals(CMD_CLEARDBG)) {
                if (debugTextBox.size() > 0) {
                    debugTextBox.delete(0, debugTextBox.size());
                }
                return;
            }
        }

        // Clear the drawing canvas
        if (c.getLabel().equals(CMD_CLEARSCREEN)) {
            canvas.clearScreen(true);
            clearScreenRemote();
            return;
        }

        // Show debug info
        if (c.getLabel().equals(CMD_DEBUGINFO)) {
            display.setCurrent(debugTextBox);
            return;
        }

        // Connect
        if (c.getLabel().equals(CMD_CONNECT)) {
            display.setCurrent(clientServerList);
            return;
        }

        // Disconnect
        if (c.getLabel().equals(CMD_DISCONNECT)) {
            doDisconnect();
            return;
        }

        // OK
        if (c.getLabel().equals(CMD_OK)) {
            if (s == colorList) {
                int idx = colorList.getSelectedIndex();
                printString("color = " + colorList.getString(idx));
                setColorFromString(colorList.getString(idx));
                display.setCurrent(canvas);
            }
            else if (s == clientServerList) {
                int idx = clientServerList.getSelectedIndex();
                String mode = clientServerList.getString(idx);
                if (mode.equals(CONNECT_SERVER)) {
                    serverMode = true;
                    doStartServerMode();
                }
                else {
                    serverMode = false;
                    display.setCurrent(deviceList);
                }
            }
            else if (s == deviceList) {
                doConnectClientMode();
            }
            return;
        }

        // CANCEL
        if (c.getLabel().equals(CMD_CANCEL)) {
            if (s == clientServerList) {
                display.setCurrent(canvas);
            }
            else if (s == deviceList) {
                display.setCurrent(clientServerList);
            }
            return;
        }

        // Back
        if (c.getLabel().equals(CMD_BACK)) {
            if (s == debugTextBox) {
                display.setCurrent(canvas);
            }
            return;
        }

        // Refresh Device List
        if (c.getLabel().equals(CMD_REFRESH)) {
            doRefreshDeviceList();
            return;
        }

        if (c.getLabel().equals(CMD_ABOUT)) {
            About.showAbout(display);
            return;
        }
    }

    /**
     * Set the color of the pen from a string.
     */
    private void setColorFromString(String color) {
        canvas.setEraserMode(false);
        if (color.equals(ERASER)) {
            canvas.setEraserMode(true);
        }
        else if (color.equals(COLOR_RED)) {
            canvas.setPenColor(255, 0, 0);
        }
        else if (color.equals(COLOR_GREEN)) {
            canvas.setPenColor(0, 255, 0);
        }
        else if (color.equals(COLOR_BLUE)) {
            canvas.setPenColor(0, 0, 255);
        }
        else {
            canvas.setPenColor(0, 0, 0);
        }
    }

    /**
     * Process data received from BT.
     */
    public void receiveData(byte buf[], int offset, int length) {
        if (length <= 2) {
            printString("Dropped len=" + length);
            return;
        }

        length = (buf[0] << 8 & 0xFF) | (buf[1] & 0xFF);
        length = length - 2;

        if (length < 0) {
            printString("Dropped adj len=" + length);
            return;
        }

        byte tmp[] = new byte[length];

        for (int i=0; i < length; i++) {
            tmp[i] = buf[i+2];
        }

        synchronized (rcvDataStack) {

            rcvDataStack.addElement(tmp);
            rcvDataStack.notify();
        }
    }


    // Read a single byte, blocks if data not available
    private byte read() {
        byte rc;

        while (true) {

            if (currentRcvBuf != null) {
                rc = currentRcvBuf[currentRcvIdx++];
                if (currentRcvIdx >= currentRcvBuf.length) {
                    currentRcvBuf = null;
                }
                return rc;
            }

            synchronized (rcvDataStack) {

                // Process drawing messages received from peer
                while (rcvDataStack.size() == 0 ) {
                    try {
                        rcvDataStack.wait();
                    }
                    catch (InterruptedException e) {
                    }
                }
                currentRcvBuf = (byte []) rcvDataStack.elementAt(0);
                rcvDataStack.removeElementAt(0);
                currentRcvIdx = 0;
            }
        }
    }

    /**
     * Parse incomming commands and then draw them on the canvas.
     */
    private int handleReceiveData() {

        int x1, y1, x2, y2, cR, cG, cB;
        int height, width;
        byte b;

        while (true) {

            b = read();

            if (b == COMMAND_DRAW_LINE) {
                x1 = ((int) read() & 0xFF);
                y1 = ((int) read() & 0xFF);
                x2 = ((int) read() & 0xFF);
                y2 = ((int) read() & 0xFF);
                cR = ((int) read() & 0xFF);
                cG = ((int) read() & 0xFF);
                cB = ((int) read() & 0xFF);
                canvas.drawLine(x1, y1, x2, y2, cR, cG, cB);
            }
            else if (b == COMMAND_CLEAR_SCREEN) {
                canvas.clearScreen(true);
            }
            else if (b == COMMAND_ERASE_RECT) {
                x1 = ((int) read() & 0xFF);
                y1 = ((int) read() & 0xFF);
                width = ((int) read() & 0xFF);
                height = ((int) read() & 0xFF);
                canvas.eraseRect(x1, y1, width, height);
            }
            else {
                printString("Bad: " + (int) b);
            }

        }
    }

    class ReaderThread extends Thread {
        public void run() {
            handleReceiveData();
        }
    }

    public void sendDataIfNecessary() {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -