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

📄 bluepad.java

📁 E-WhiteBoard with Bluetooth
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        byte tmp[];

        if (state == CONNECT) {
            try {
                // Send Drawing messages to peer
                while (drawLineStack.size() > 0) {
                    tmp = (byte []) drawLineStack.elementAt(0);
                    drawLineStack.removeElementAt(0);
                    write(tmp, 0, tmp.length);
                }
                flush();
            }
            catch (EmptyStackException e) {
            }
        }
    }

    class MyTimerTask extends TimerTask {
        public void run() {
            sendDataIfNecessary();
        }
    }


    /**
     * Draw a line on the remote device.
     * Does nothing if not connected.
     */
    public void drawLineRemote(int x1, int y1, int x2, int y2, int cR, int cG, int cB ) {
        // If not connected, return.
        if (state != CONNECT) {
            return;
        }

        byte buf[] = new byte[8];
        buf[0] = COMMAND_DRAW_LINE;
        buf[1] = (byte)  (x1 & 0xFF);
        buf[2] = (byte)  (y1 & 0xFF);
        buf[3] = (byte)  (x2 & 0xFF);
        buf[4] = (byte)  (y2 & 0xFF);
        buf[5] = (byte)  (cR & 0xFF);
        buf[6] = (byte)  (cG & 0xFF);
        buf[7] = (byte)  (cB & 0xFF);

        drawLineStack.addElement(buf);
    }

    /**
     * Clear the remote screen.
     */
    public void clearScreenRemote() {
        if (state != CONNECT) {
            return;
        }

        byte buf[] = new byte[1];
        buf[0] = COMMAND_CLEAR_SCREEN;

        drawLineStack.addElement(buf);
    }

    /**
     * Erase on the remote screen.
     */
    public void eraseRectRemote(int x, int y, int width, int height) {
        if (state != CONNECT) {
            return;
        }

        byte buf[] = new byte[5];
        buf[0] = COMMAND_ERASE_RECT;
        buf[1] = (byte)  (x & 0xFF);
        buf[2] = (byte)  (y & 0xFF);
        buf[3] = (byte)  (width & 0xFF);
        buf[4] = (byte)  (height & 0xFF);
        drawLineStack.addElement(buf);
    }

    /**
     * Print string to system.out and add it to the TextBox
     */
    public void printString(String s) {
        //    System.out.println(s);
        if (DEBUG) {
            if (debugTextBox != null) {
                debugTextBox.insert(s, debugTextBox.getCaretPosition());
                debugTextBox.insert(" \r\n", debugTextBox.getCaretPosition());
            }
        }
    }

    /**
     * Start in Server Mode.
     */
    private void doStartServerMode() {
        if (state != DISCONNECT) {
            return;
        }
        // Starts a thread
        state = CONNECTING;
        canvas.repaintStatusIcon();
        canvas.removeCommand(connectCommand);
        canvas.addCommand(disconnectCommand);
        display.setCurrent(canvas);
        server = new BluePadServer(this);
    }

    /*
     * Start in Client Mode.
     */
    private void doConnectClientMode() {
        if (state != DISCONNECT) {
            return;
        }
        state = CONNECTING;
        canvas.repaintStatusIcon();
        canvas.removeCommand(connectCommand);
        canvas.addCommand(disconnectCommand);
        display.setCurrent(canvas);
        searchForServices();
    }

    /**
     * Refresh list of devices.
     */
    private void doRefreshDeviceList() {
        doBluetoothDiscovery();
    }


    /**
     * User requests a disconnect.
     */
    private void doDisconnect() {
        printString("doDisconnect called!");
        if (state == DISCONNECT) {
            return;
        }
        state = DISCONNECT;

        if (checkXmtTimer != null) {
            checkXmtTimer.cancel();
            checkXmtTimer = null;
        }
        if (serverMode && server != null) {
            server.close();
            server = null;
        }
        else if (client != null) {
            client.close();
            client = null;
        }

        drawLineStack.removeAllElements();

        // Remove Disconnect command and replace it with the connect command
        canvas.removeCommand(disconnectCommand);
        canvas.addCommand(connectCommand);
        canvas.repaintStatusIcon();
    }


    public void write(byte buf[], int offset, int length) {
        synchronized (xmtBuffer) {

            for (int i = 0; i < length; i++) {
                xmtBuffer[xmtIndex++] = buf[offset+i];
                if (xmtIndex >= xmtBuffer.length) {
                    sendXmtBuf();
                }
            }
        }
    }

    public void flush() {
        synchronized (xmtBuffer) {
            // If there is data to send, then send it!
            if (xmtIndex > 2) {
                sendXmtBuf();
            }
        }
    }

    private void sendXmtBuf() {
        if (conn == null) {
            return;
        }

        try {
            // Store the length in the first two bytes of the array
            xmtBuffer[0] = (byte) (xmtIndex >> 8 & 0xFF);
            xmtBuffer[1] = (byte) (xmtIndex & 0xFF);
            conn.send(xmtBuffer);
            xmtIndex = 2;
        }
        catch (IOException e) {
            printString("conn.send exception: " + e);
        }

    }



    /**
     * Call-back when BT has connected.
     */
    public void setStateConnected(L2CAPConnection c) {
        printString("setStateConnected called");

        try {

            this.conn = c;
            xmtBuffer = new byte[conn.getTransmitMTU()];
            xmtIndex = 2;  // reserve first 2 bytes for length of payload
        }
        catch (IOException e) {
            printString("Exception (b1): " + e);
        }

        state = CONNECT;
        canvas.repaintStatusIcon();
        canvas.clearScreen(true);
        display.setCurrent(canvas);

        checkXmtTimer = new Timer();
        checkXmtTimer.schedule(new MyTimerTask(), 300, 300);
        ReaderThread readerThread = new ReaderThread();
        readerThread.start();

        printString("setStateConnected return");
    }

    /**
     * Call-back when BT has disconnected.
     */
    public void setStateDisconnected() {
        printString("Disconnected!");
        doDisconnect();
    }


    /**
     * Start a search for BT services.
     */
    private void searchForServices() {

        foundService = false;

        // 
        printString("Searching for services ...");

        // Get Selected device

        int idx = deviceList.getSelectedIndex();
        if (idx == -1) {
            printString("Nothing selected!");
            return;
        }

        try {
            String devName = deviceList.getString(idx);
            RemoteDevice remoteDevice;
            remoteDevice = (RemoteDevice) bluetoothDevices.get(devName);
            if (remoteDevice == null) {
                printString("No remote device!");
                return;
            }

            // Look for Services on remoteDevice
            printString("Starting inquery on " + devName);

            /*
             * Add the UUID for L2CAP to make sure that the service record
             * found will support L2CAP.  This value is defined in the
             * Bluetooth Assigned Numbers document.
             */
            UUID[] searchList = { 
                new UUID(UDI_L2CAP), 
                new UUID(MY_SERVICE_NUMBER, false) 
            };

            try {
                int trans = discoveryAgent.searchServices(null, searchList, remoteDevice, this);
            }
            catch (BluetoothStateException e) {
                printString("Exception (b6): " + e);
            }
        }
        catch (Exception e) {
            printString("Exception (b7): " + e);
        }
    }


    /**
     * Copy all keys from the device table into the list.
     * Remove old entries in list if they exist.
     */
    private void bluetoothCopyDeviceTableToList() {
        // Remove old entries
        for (int i=deviceList.size(); i > 0; i--) {
            deviceList.delete(i-1);
        }      

        // Append keys from table
        for (Enumeration e = bluetoothDevices.keys(); e.hasMoreElements(); ) {
            try {

                String name = (String) e.nextElement();
                deviceList.append( name, null );
            }
            catch (Exception exception) {
            }
        } 
    }

    private void doBluetoothDiscovery() {
        Thread t = new Thread(this);
        t.start();
    }

    // Implement Runnable
    public void run() {
        bluetoothDiscovery();
    }


    private void bluetoothDiscovery() 
    {
        LocalDevice localDevice;
        try {
            localDevice = LocalDevice.getLocalDevice();
            // P900 throws an exception if the BT is not turned on in the device.
        }
        catch (BluetoothStateException e) {
            printString("BluetoothStateException: " + e);
            return;
        }

        discoveryAgent = localDevice.getDiscoveryAgent();

        RemoteDevice devices[]; 

        try {
            devices = discoveryAgent.retrieveDevices(DiscoveryAgent.CACHED);
            if (devices != null) {
                for (int i=0; i < devices.length; i++) {
                    bluetoothDevices.put(devices[i].getFriendlyName(false), devices[i]);
                    printString("Device (cached): " + devices[i].getFriendlyName(false) + 
                                " " + devices[i].getBluetoothAddress() );
                }
                //   return;
            }

            devices = discoveryAgent.retrieveDevices(DiscoveryAgent.PREKNOWN);
            if (devices != null) {
                for (int i=0; i < devices.length; i++) {
                    bluetoothDevices.put(devices[i].getFriendlyName(false), devices[i]);
                    printString("Device (cached): " + devices[i].getFriendlyName(false) + 
                                " " + devices[i].getBluetoothAddress() );
                }
                // return;
            }
        }
        catch (IOException e) {
            printString("Exception (b2): " + e);
        }

        try {
            discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
        }
        catch (BluetoothStateException e) {
            printString("Exception (b3): " + e);
        }

        printString("return from bluetoothDiscovery()");
    }


    // ************************************************
    // Implement BT DiscoveryListener
    // ************************************************
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {

        try {
            printString("deviceDisc: " + btDevice.getFriendlyName(false));

            // Add Device to table
            bluetoothDevices.put(btDevice.getFriendlyName(false), btDevice);
        }
        catch (Exception e) {
            printString("Exception (b4): " + e);
        }

    }


    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        printString("servicesDisc: " + transID + " length = " + servRecord.length);
        int attribs[];
        DataElement data;

        if (foundService) {
            return;
        }

        for (int i=0; i < servRecord.length; i++) {
            try {
                attribs = servRecord[i].getAttributeIDs();
                for (int j=0; j < attribs.length; j++) {
                    printString(" " + attribs[j]);
                }

                String conURL = servRecord[i].getConnectionURL( ServiceRecord.NOAUTHENTICATE_NOENCRYPT , false );
                int index = conURL.indexOf(':');
                String protocol= conURL.substring(0, index);

                if (protocol.equals("btl2cap")) {
                    record = servRecord[i];
                    printString("record URL=" + conURL );
                    foundService = true;
                    break;
                }
            }
            catch (Exception e) {
                printString("Exception (b5): " + e);
            }
        }
    }

    public void serviceSearchCompleted(int transID, int respCode) {
        printString("serviceSearchComplete! " + transID + " " + respCode);

        // Start the Connection using the located service.
        if (foundService) {
            //
            client = new BluePadClient(this, record);
            client.start();
        }
    }

    public void inquiryCompleted(int discType) {
        printString("inquiryCompleted! " + discType);
        bluetoothCopyDeviceTableToList();
    }

    // ************************************************
    // ************************************************



}   







⌨️ 快捷键说明

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