Dúvidas: J2SE+J2ME+Bluetooth+Marge+BlueCove

4 respostas
F

Pessoal, boa tarde …

Sou extremamente iniciante em programação Orientada a Objetos, sou amante da forma estruturada e cabeça dura para aprender novos métodos (hehehe)
Estou fazendo meu projeto de Monografia, utilizando tecnologia Bluetooth para fazer uma comunicação entre o Celular (J2ME) e um Servidor (J2SE). Após pesquisar muito em fórum, google, etc … acabei por conhecer um pouco da linguagem, realizei diversos testes com a IDE NetBeans e acabei conhecendo as APIs, Bluecove, JSR-82 e o framework Marge.

Adquiri a revista WebMobile edição 8, que vinha com exemplos de conexão bluetooth entre celular e servidor:

(fontes)http://www.devmedia.com.br/webmobile/downloads/ed08/WM8_bluecove.rar

Abri ambos os projetos no NetBeans, converti ambos para a versão mais nova da IDE e troquei a API BlueCove que estava antiga para a versão atual (2.0.3). Acertei alguns erros de tradução que estavam dando problema e acabou que funcionando o servidor.
Peguei a parte do celular, gerei os .jar e .jad, joguei no meu celular V3i e instalei normalmente a aplicação no celular.

Pois bem, executei pelo NetBeans a aplicação servidor e a mensagem apareceu:
“Aguardando conexão dos usuários” (ótimo, pensei …)

No celular, iniciei a aplicação, setei para procurar dispositivos e encontrou o meu servidor (uhull), porém, quando eu clico para conectar, apenas aparece a mensagem “*** ENVIANDO MENSAGEM PARA O SERVIDOR***” e não faz mais nada.

Qual poderia ser o problema ?

Não satisfeito com este teste, realizei outros. Adquiri o framwork Marge e também uma aplicação deles para estudo:

(fontes) http://www.mundojava.com.br/NovoSite/codigos/ed30/marge.zip

Abri ambos os projetos no NetBeans e adicionei o .JAR do BlueCove e Marge no Servidor e apenas a Marge no cliente.
Executei o servidor e instalei a aplicação no meu celular;

Novamente a aplicação encontrou o meu servidor, porém não conseguiu se conectar ao serviço;

Alguém poderia me dar uma luz do que está acontecendo ? Testei com meu notebook que Windows Vista e bluetooth imbutido e com meu outro computador com Windows XP SP 3 e um adaptador bluetooth instalado e configurado.

4 Respostas

P

Posta o source da aplicação pra galera. Eu nem conheço J2ME mas talvez, olhando, de pra achar algo.

[]'s

F

Exemplo do Marge

Servidor

Bibliotecas:
marge-core-0.5.jar
bluecove-2.0.3.jar

/*
 * Marge, Java Bluetooth Framework
 * Copyright (C) 2006  Project Marge
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * [email removido]
 * http://marge.dev.java.net
 */
package net.java.dev.marge.bluechatjm;

import java.io.IOException;
import javax.bluetooth.RemoteDevice;
import net.java.dev.marge.communication.CommunicationListener;
import net.java.dev.marge.communication.ConnectionListener;
import net.java.dev.marge.entity.Device;
import net.java.dev.marge.entity.ServerDevice;
import net.java.dev.marge.entity.config.ServerConfiguration;
import net.java.dev.marge.factory.CommunicationFactory;
import net.java.dev.marge.factory.RFCOMMCommunicationFactory;

public class BluechatRFCOMMEchoServer implements CommunicationListener, ConnectionListener {

    private CommunicationFactory communicationFactory;
    private Device device;

    public BluechatRFCOMMEchoServer(CommunicationFactory communicationFactory) {
        this.communicationFactory = communicationFactory;
    }

    public void startServer() {
        ServerConfiguration config = new ServerConfiguration(this);
        config.setMaxNumberOfConnections(5);
        communicationFactory.waitClients(config, this);
    }

    public void errorOnConnection(IOException e) {
        System.err.println(e.getMessage());
    }

    public void connectionEstablished(ServerDevice device, RemoteDevice remote) {
        System.out.println(remote.getBluetoothAddress());
        this.device = device;
        device.startListening();
        device.setEnableBroadcast(true);
    }

    public void receiveMessage(byte[] receivedString) {
        String s = new String(receivedString);
        System.out.println("Recebido:"+s);
        device.send(("echo: " + s).getBytes());
        System.out.println("Echo enviado...");
    }

    public void errorOnReceiving(IOException e) {
        System.err.println(e.getMessage());
    }

    public void errorOnSending(IOException e) {
        System.err.println(e.getMessage());
    }
    
     public static void main(String[] args) {
        BluechatRFCOMMEchoServer server = new BluechatRFCOMMEchoServer(new RFCOMMCommunicationFactory());
        System.out.println("Recebendo conexão dos usuários:");
        server.startServer();
    }
}

Exemplo do Marge

Cliente - são vários arquivos

Bibliotecas:
marge-core-0.5.jar

BlueChatMIDlet.java
/*
 * Marge, Java Bluetooth Framework
 * Copyright (C) 2006  Project Marge
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * [email removido]
 * http://marge.dev.java.net
 */
package net.java.dev.marge.bluechatjm;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import net.java.dev.marge.entity.Device;

public class BlueChatMIDlet extends MIDlet {

    private static BlueChatMIDlet instance;
    private Display display;
    private Device device;
    private MainMenu mainMenu;

    public BlueChatMIDlet() {
        display = Display.getDisplay(this);
        instance = this;
    }

    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
        notifyDestroyed();
    }

    protected void pauseApp() {
    }

    protected void startApp() throws MIDletStateChangeException {
        setCurrent(this.mainMenu = new MainMenu());
    }

    public void exit() {
        try {
            this.destroyApp(true);
        } catch (MIDletStateChangeException e) {
            e.printStackTrace();
        }
    }

    public void setCurrent(Displayable d) {
        this.display.setCurrent(d);
    }
    
    public void setCurrent(Alert a, Displayable d) {
        this.display.setCurrent(a, d);
    }

    public Device getDevice() {
        return device;
    }

    public void setDevice(Device device) {
        this.device = device;
    }

    public void showError(String message, Displayable d) {
        Alert alert = new Alert("Erro", message, null, AlertType.ERROR);
        alert.setTimeout(2000);
        display.setCurrent(alert, d);
    }
    
    public static BlueChatMIDlet getInstance() {
        return instance;
    }

    public void showMainMenu() {
        this.setCurrent(this.mainMenu);
    }
}
ChatForm,java
/*
 * Marge, Java Bluetooth Framework
 * Copyright (C) 2006  Project Marge
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * [email removido]
 * http://marge.dev.java.net
 */
package net.java.dev.marge.bluechatjm;

import java.io.IOException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import net.java.dev.marge.communication.CommunicationListener;
import net.java.dev.marge.entity.Device;

public class ChatForm extends Form implements CommunicationListener,
        CommandListener {

    private Device device;
    private Command back;
    private TextField chatField;

    public ChatForm() {
        super("Chat...");
        this.chatField = new TextField("Mensagem", null, 100, TextField.ANY);
        this.append(this.chatField);
        this.addCommand(new Command("Enviar", Command.OK, 1));
        this.addCommand(this.back = new Command("Voltar", Command.BACK, 1));
        this.setCommandListener(this);
    }

    public void receiveMessage(byte[] receivedString) {
        this.insert(1, new StringItem("Recebido: ", new String(receivedString)));
    }

    public void errorOnReceiving(IOException e) {
        e.printStackTrace();
        this.leaveChat();
    }

    public void errorOnSending(IOException e) {
        e.printStackTrace();
        this.leaveChat();
    }

    public void sendMessage(String message) {
        this.device.send(message.getBytes());
        this.insert(1, new StringItem("Enviado: ", message));
    }

    public void setDevice(Device device) {
        this.device = device;
    }

    public void leaveChat() {
        this.deleteAll();
        this.append(this.chatField);
        this.device.close();
        BlueChatMIDlet.getInstance().showMainMenu();
    }

    public void commandAction(Command c, Displayable d) {
        if (c == this.back) {
            this.leaveChat();
        } else {
            this.sendMessage(this.chatField.getString());
        }
    }
}
InquiryList.java
/*
 * Marge, Java Bluetooth Framework
 * Copyright (C) 2006  Project Marge
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * [email removido]
 * http://marge.dev.java.net
 */
package net.java.dev.marge.bluechatjm;

import java.io.IOException;
import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import net.java.dev.marge.entity.ClientDevice;
import net.java.dev.marge.entity.config.ClientConfiguration;
import net.java.dev.marge.factory.CommunicationFactory;
import net.java.dev.marge.inquiry.DeviceDiscoverer;
import net.java.dev.marge.inquiry.InquiryListener;
import net.java.dev.marge.inquiry.ServiceDiscoverer;
import net.java.dev.marge.inquiry.ServiceSearchListener;

public class InquiryList extends List implements CommandListener,
        ServiceSearchListener, InquiryListener {

    private MainMenu mainMenu;
    private Command select;
    private Command stopOrBack;
    private Vector devices;
    private CommunicationFactory factory;

    public InquiryList(MainMenu menu, CommunicationFactory factory) {
        super("Buscando...", List.IMPLICIT);
        this.select = null;
        this.mainMenu = menu;
        this.factory = factory;
        this.devices = new Vector(5);
        this.addCommand(this.stopOrBack = new Command("Parar",
                Command.CANCEL, 1));
        this.setCommandListener(this);
        new Thread() {

            public void run() {
                try {
                    DeviceDiscoverer.getInstance().startInquiryGIAC(InquiryList.this);
                } catch (BluetoothStateException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void commandAction(Command c, Displayable d) {
        if (c == this.stopOrBack) {
            if (c.getCommandType() == Command.CANCEL) {
                try {
                    DeviceDiscoverer.getInstance().cancelInquiry();
                    this.removeCommand(c);
                    this.stopOrBack = new Command("Voltar", Command.BACK, 1);
                    this.addCommand(this.stopOrBack);
                } catch (BluetoothStateException ex) {
                    ex.printStackTrace();
                }
            } else {
                BlueChatMIDlet.getInstance().showMainMenu();
            }
        } else {
            if (this.select != null) {
                try {
                    DeviceDiscoverer.getInstance().cancelInquiry();
                    ServiceDiscoverer.getInstance().startSearch((RemoteDevice) this.devices.elementAt(this.getSelectedIndex()), this);
                } catch (BluetoothStateException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void deviceNotReachable() {
        BlueChatMIDlet.getInstance().setCurrent(new Alert("Info", "Device not reachable", null, AlertType.INFO), this);
    }

    public void serviceSearchCompleted(RemoteDevice remoteDevice,
            ServiceRecord[] services) {
        try {
            ClientConfiguration config = new ClientConfiguration(services[0],
                    this.mainMenu.getChatForm());
            ClientDevice clientDevice = this.factory.connectToServer(config);
            this.mainMenu.changeToChatScreen(clientDevice);
        } catch (IOException e) {
            this.mainMenu.errorOnConnection(e);
        }
    }

    public void serviceSearchError() {
        BlueChatMIDlet.getInstance().setCurrent(new Alert("Error", "Service search error", null, AlertType.ERROR), this);
    }

    public void deviceDiscovered(RemoteDevice device, DeviceClass deviceClass) {
        if (this.select == null) {
            this.select = new Command("Selec", Command.OK, 1);
            this.addCommand(select);
        }

        this.devices.addElement(device);
        this.setTitle("Buscando... " + this.devices.size());
        try {
            this.append(device.getFriendlyName(false), null);
        } catch (IOException e) {
            this.append(device.getBluetoothAddress(), null);
            e.printStackTrace();
        }
    }

    public void inquiryCompleted(RemoteDevice[] devices) {
        this.setTitle(Integer.toString(this.devices.size()) + " encontrados");
        this.removeCommand(this.stopOrBack);
        this.stopOrBack = new Command("Voltar", Command.BACK, 1);
        this.addCommand(this.stopOrBack);
    }

    public void inquiryError() {
        BlueChatMIDlet.getInstance().setCurrent(new Alert("Error", "Inquiry error", null, AlertType.ERROR), this);
    }
}
LoadingScreen.java
/*
 * Marge, Java Bluetooth Framework
 * Copyright (C) 2006  Project Marge
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * [email removido]
 * http://marge.dev.java.net
 */

package net.java.dev.marge.bluechatjm;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;

public class LoadingScreen extends Form implements CommandListener {

	private MainMenu menu;
	
	public LoadingScreen(MainMenu menu) {
		super("Esperando...");
		this.menu = menu;
		this.append(new Gauge("Esperando conexões", false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING));
		this.addCommand(new Command("Cancelar", Command.CANCEL, 1));
		this.setCommandListener(this);
	}

	public void commandAction(Command arg0, Displayable arg1) {
		this.menu.setCancelled();
		BlueChatMIDlet.getInstance().showMainMenu();
	}
}
MainMenu.java
/*
 * Marge, Java Bluetooth Framework
 * Copyright (C) 2006  Project Marge
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * [email removido]
 * http://marge.dev.java.net
 */
package net.java.dev.marge.bluechatjm;

import java.io.IOException;

import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import net.java.dev.marge.communication.ConnectionListener;
import net.java.dev.marge.entity.ClientDevice;
import net.java.dev.marge.entity.ServerDevice;
import net.java.dev.marge.entity.config.ServerConfiguration;
import net.java.dev.marge.factory.CommunicationFactory;
import net.java.dev.marge.factory.L2CAPCommunicationFactory;
import net.java.dev.marge.factory.RFCOMMCommunicationFactory;

public class MainMenu extends List implements ConnectionListener, CommandListener {

    private final String SELEC_COMMAND_NAME = "Selec";
    private ChatForm chatForm;
    private boolean cancelled;

    public MainMenu() {
        super("BlueChat", List.IMPLICIT);

        this.append("Cliente", null);
        this.append("Servidor", null);
        this.append("Sair", null);

        this.addCommand(new Command(SELEC_COMMAND_NAME, Command.OK, 1));
        this.setCommandListener(this);
        this.chatForm = new ChatForm();
        this.cancelled = false;
    }

    public void commandAction(Command c, Displayable d) {
        try {
            LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
            switch (this.getSelectedIndex()) {
                case 0:
                    this.performInquiry(new RFCOMMCommunicationFactory());
                    break;
                case 1:
                    this.cancelled = false;
                    this.startServer();
                    break;
                default:
                    BlueChatMIDlet.getInstance().exit();
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void performInquiry(CommunicationFactory factory) {
        BlueChatMIDlet.getInstance().setCurrent(new InquiryList(this, factory));
    }

    private void startServer() {
        BlueChatMIDlet.getInstance().setCurrent(new LoadingScreen(this));
        ServerConfiguration config = new ServerConfiguration(chatForm);
        config.setMaxNumberOfConnections(7);
        CommunicationFactory communicationFactory = new RFCOMMCommunicationFactory();
        communicationFactory.waitClients(config, this);
    }

    public ChatForm getChatForm() {
        return chatForm;
    }

    public void errorOnConnection(IOException exception) {
        BlueChatMIDlet.getInstance().showError(exception.getMessage(), this);
    }

    public void changeToChatScreen(ClientDevice device) {
        if (!this.cancelled) {
            device.startListening();
            this.chatForm.setDevice(device);
            BlueChatMIDlet.getInstance().setCurrent(this.chatForm);
        }
    }

    public void connectionEstablished(ServerDevice device, RemoteDevice remote) {
        if (!this.cancelled) {
            device.startListening();
            device.setEnableBroadcast(true);
            this.chatForm.setDevice(device);
            BlueChatMIDlet.getInstance().setCurrent(this.chatForm);
        }
    }

    public void setCancelled() {
        this.cancelled = true;
    }
}
F

Obtive um certo avançoo.

A aplicação desse .zip http://www.mundojava.com.br/NovoSite/codigos/ed30/marge.zip, na parte do mobile, funcionou a comunicação entre dois celulares, 1 como servidor e outro como cliente.
E um amigo meu, conseguiu fazer funcionar apenas 1 vez pelo desktop e celular (depois começou o mesmo problema meu)

Alguém sabe se existe alguma incompatibilidade de celulares motorola com bluetooth ?

geidivan

Meu amigo, acertou na mosca! O problema são os celulares da Motorola.

Estou utilizando o Marge também e aconteceu o mesmo. Ele acha os dispositivos mas não acha os serviços de jeito nenhum. Mandei um email pra comunidade do Marge e eles disseram que não sabiam o que poderia ser.
Quebrei a cabeça semanas testando o aplicativo em um Z3. Para minha surpresa nem o BlueChat (codigo exemplo do site do Marge) funcionava. Foi aí que desconfiei do celular.
No grupo de usuários do Marge há várias reclamações sobre o funcionamento do framework no V3, mas parece que não é só ele.
Testei em um celular Nokia e em um Palm qualquer, e adivinha, funcionou perfeitamente.

Parece que os serviços e meio de comunição bluetooth dos aparelhos Motorola tem alguma coisa fora do padrão.

Criado 12 de agosto de 2008
Ultima resposta 17 de nov. de 2008
Respostas 4
Participantes 3