将使用Processing.org创建的应用程序迁移到Eclipse

时间:2012-08-18 14:20:59

标签: java serial-port xmpp processing

我在Processing中制作了一个简单的程序,效果很好。我现在正试图将我的初学者Java技能带到Eclipse,以便重新制作相同的程序。该程序采用来自Com端口的Rs232字符串,并通过Xmpp发送。

我遇到的问题是我无法调用newChat.sendMessage(消息),就像我可以从任何类/选项卡中处理一样。有人能告诉我应该寻找什么来解决这个问题。我猜测扩展,或者实现Xmpp类是我需要做的。我喜欢简单的处理处理它..

任何帮助将不胜感激。

Fyi:Smack库位于代码文件夹中进行处理。

主要应用:

import processing.net.*;




void setup() {
  size(400, 200);
  noStroke();
  background(0);
  LoadSerialPort();
  OpenChatConnection();
  setupFilterThread ();
}

void draw() {
}



String timestampTime() {
  Calendar now = Calendar.getInstance();
  return String.format("%1$tH:%1$tM:%1$tS", now);
}


String timestampDate() {
  Calendar now = Calendar.getInstance();
  return String.format("%1$tm/%1$td/%1$tY", now);
}

过滤器类/标签:

FilterThread thread1;

List FilteredArchAddressList = new ArrayList();
ArrayList CallList = new ArrayList();

void  setupFilterThread () {

  thread1 = new  FilterThread(100, "a");
  thread1.start();
}

void checkForNewCalls() {
  if (CallList.size() >=1) {
    println("New Call In List, Size: "+CallList.size());
    FilterComPortString((String) CallList.get(0));
    CallList.remove(0);
  }
}

void FilterComPortString(String s) {

    Message message = new Message("icu1@broadcast.server", Message.Type.normal);
    //message.setTo("icu1@broadcast.x-dev");
    message.setSubject("MSG_TYPE_NORMAL");
    message.setBody(s);
    message.setProperty("systemID", "JS1");
    message.setProperty("serverTime", trim(timestampTime()));
    message.setProperty("serverDate", trim(timestampDate()));

    try {
      newChat.sendMessage(message);
    }
    catch (Exception e) {
      println(e);
    }
  }
}

class  FilterThread extends  Thread {

  boolean  running;           // Is the thread running?  Yes or no?
  int  wait;                  // How many milliseconds should we wait in between executions?
  String  id;                 // Thread name
  int  count;                 // counter

  // Constructor, create the thread
  // It is not running by default
  FilterThread (int  w, String  s) {
    wait = w;
    running = false ;
    id = s;
    count = 0;
  }

  int  getCount() {
    return  count;
  }

  // Overriding "start()"
  void  start () {
    // Set running equal to true
    running = true ;
    // Print messages
    println ("Starting thread (will execute every " + wait + " milliseconds.)"); 
    // Do whatever start does in Thread, don't forget this!
    super .start();
  }


  // We must implement run, this gets triggered by start()
  void  run () {
    while  (running) {
      checkForNewCalls();
      // Ok, let's wait for however long we should wait
      try {
        sleep((long )(wait));
      } 
      catch  (Exception e) {
      }
    }
    System.out.println (id + " thread is done!");  // The thread is done when we get to    the end of run()
  }


  // Our method that quits the thread
  void  quit() {
    System.out.println ("Quitting."); 
    running = false ;  // Setting running to false ends the loop in run()
    // IUn case the thread is waiting. . .
    interrupt();
  }
}

Rs232 Class / Tab:

import processing.serial.*;

Serial myPort; // Rs232, Serial Port
String inString;  // Input string from serial port: 
int lf = 10;      // ASCII linefeed 


String SelectedCom;

void LoadSerialPort() {


  println(Serial.list()); 
  println("________________________________________________________");

  try {
    myPort = new Serial(this, Serial.list()[0], 9600); 
    myPort.bufferUntil(lf);
    SelectedCom = Serial.list()[0];
    println("Connected to Serial Port:");
    println("________________________________________________________");
  } 
  catch (ArrayIndexOutOfBoundsException e) {
    String exception = e.toString();
    if (exception.contains("ArrayIndexOutOfBoundsException: 0")) {
      println("NO AVAILABLE COM PORT FOUND");
    } 
    else {
      println(e);
    }
  }
}

void serialEvent(Serial p) { 
  inString = p.readString();   
  CallList.add(new String(inString));
}

Xmpp Class / Tab:

String FromXmpp = "";
Chat newChat;
ChatManager chatmanager;


XMPPConnection connection;

public void OpenChatConnection() {

  // This is the connection to google talk. If you use jabber, put other stuff in here. 
  ConnectionConfiguration config = new ConnectionConfiguration("192.168.0.103", 5222, "Jabber/XMPP");
  config.setSASLAuthenticationEnabled(false);

  configure(ProviderManager.getInstance());

  connection = new XMPPConnection(config);

  println("Connecting");
  try {
    //connection.DEBUG_ENABLED = true;
    connection.connect();
    println("Connected to: "+connection.getServiceName() );
  } 

  catch (XMPPException e1) {
    println("NOT Connected");
  }

  if (connection.isConnected()) {

    try {

      // This is the username and password of the chat client that is to run within Processing.  
      println("Connecting");
      connection.login("System1", "test"); 
      //connection.login("inside_processing_username@gmail.com", "yourpassword");
    } 
    catch (XMPPException e1) {
      // would probably be a good idea to put some user friendly action here.
      e1.printStackTrace();
    }  
    println("Logged in as: "+connection.getUser() );
  }
  chatmanager = connection.getChatManager();
  // Eventhandler, to catch incoming chat events
  newChat = chatmanager.createChat("icu@broadcast.server", new MessageListener() {   //icu1@broadcast.x-dev   //admin@x-dev
    public void processMessage(Chat chat, Message message) {
      // Here you do what you do with the message
      FromXmpp = message.getBody();
      // Process commands
      //println(FromXmpp);
    }
  }
  );


  Roster roster = connection.getRoster();
  Collection<RosterEntry> entries = roster.getEntries();
  for (RosterEntry entry : entries) {
    System.out.println(entry);
  }
}


public void configure(ProviderManager pm) {

  //  Private Data Storage
  pm.addIQProvider("query", "jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider());

  //  Time
  try {
    pm.addIQProvider("query", "jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time"));
  } 
  catch (ClassNotFoundException e) {
    println(("TestClient "+" Can't load class for org.jivesoftware.smackx.packet.Time"));
  }

  //  Roster Exchange
  pm.addExtensionProvider("x", "jabber:x:roster", new RosterExchangeProvider());

  //  Message Events
  pm.addExtensionProvider("x", "jabber:x:event", new MessageEventProvider());

  //  Chat State
  pm.addExtensionProvider("active", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
  pm.addExtensionProvider("composing", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider()); 
  pm.addExtensionProvider("paused", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
  pm.addExtensionProvider("inactive", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
  pm.addExtensionProvider("gone", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());

  //  XHTML
  pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider());

  //  Group Chat Invitations
  pm.addExtensionProvider("x", "jabber:x:conference", new GroupChatInvitation.Provider());

  //  Service Discovery # Items    
  pm.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());

  //  Service Discovery # Info
  pm.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());

  //  Data Forms
  pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());

  //  MUC User
  pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user", new MUCUserProvider());

  //  MUC Admin    
  pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin", new MUCAdminProvider());

  //  MUC Owner    
  pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());

  //  Delayed Delivery
  pm.addExtensionProvider("x", "jabber:x:delay", new DelayInformationProvider());

  //  Version
  try {
    pm.addIQProvider("query", "jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version"));
  } 
  catch (ClassNotFoundException e) {
    //  Not sure what's happening here.
  }

  //  VCard
  pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());

  //  Offline Message Requests
  pm.addIQProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());

  //  Offline Message Indicator
  pm.addExtensionProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());

  //  Last Activity
  pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());

  //  User Search
  pm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider());

  //  SharedGroupsInfo
  pm.addIQProvider("sharedgroup", "http://www.jivesoftware.org/protocol/sharedgroup", new SharedGroupsInfo.Provider());

  //  JEP-33: Extended Stanza Addressing
  pm.addExtensionProvider("addresses", "http://jabber.org/protocol/address", new MultipleAddressesProvider());

  //   FileTransfer
  pm.addIQProvider("si", "http://jabber.org/protocol/si", new StreamInitiationProvider());

  pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams", new BytestreamsProvider());

  //  Privacy
  pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());
  pm.addIQProvider("command", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider());
  pm.addExtensionProvider("malformed-action", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.MalformedActionError());
  pm.addExtensionProvider("bad-locale", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadLocaleError());
  pm.addExtensionProvider("bad-payload", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadPayloadError());
  pm.addExtensionProvider("bad-sessionid", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadSessionIDError());
  pm.addExtensionProvider("session-expired", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.SessionExpiredError());
}

2 个答案:

答案 0 :(得分:1)

如果您了解eclipse的方法,首先需要创建一个新的Java项目,并将Processing的core.jar添加到构建路径,然后创建一个PApplet的子级。如果没有,那么使用名为Proclipsing的eclipse插件和视频指南就可以轻松使用它。

proclipsing

将您的代码从Processing带到eclipse:

您需要了解处理草图(包括选项卡)中的所有代码都合并到一个.java文件中,草图名称是类名。您在草图中的选项卡中定义的任何类都将成为主要单个类中的嵌套类。最简单的方法是导出applet并查看SketchName.java文件的生成文件夹。请记住,标签一个类(虽然它可以包含一个)。

所以你有几个选择。以下是两种基本方法:

  1. 创建一个新的PApplet子类并开始粘贴其中的整个代码(包括选项卡的内容)。您需要明确关于访问器(例如public void setup()而不仅仅是void setup())并注意double / float值(例如,如果eclipse抱怨1.0,则显式: 1.0f

  2. 另一种选择是创建多个类,正如我想你在使用eclipse时打算做的那样。问题是,在Processing中,选项卡中定义的变量实际上是“全局”变量。如果您在顶部的主选项卡中声明它们,那么您的代码将以相同的方式工作。此外,使用PApplet函数需要重构。可以使用Java的类(而不是PApplet)调用某些函数来破坏依赖性:例如System.out.println()代替println(),但您可能希望您的类可以访问PApplet实例:

  3. e.g。

    public class  FilterThread extends  Thread {
    
      boolean  running;           // Is the thread running?  Yes or no?
      int  wait;                  // How many milliseconds should we wait in between executions?
      String  id;                 // Thread name
      int  count;                 // counter
      YourSketchClass parent;
    
      // Constructor, create the thread
      // It is not running by default
      FilterThread (int  w, String  s,YourSketchClass p) {
        wait = w;
        running = false ;
        id = s;
        count = 0;
        parent = p;
      }
    
      int  getCount() {
        return  count;
      }
    
      // Overriding "start()"
      public void  start () {
        // Set running equal to true
        running = true ;
        // Print messages
        System.out.println ("Starting thread (will execute every " + wait + " milliseconds.)"); 
        // Do whatever start does in Thread, don't forget this!
        super .start();
      }
    
    
      // We must implement run, this gets triggered by start()
      public void  run () {
        while  (running) {
          parent.checkForNewCalls();
          // Ok, let's wait for however long we should wait
          try {
            sleep((long )(wait));
          } 
          catch  (Exception e) {
          }
        }
        System.out.println (id + " thread is done!");  // The thread is done when we get to    the end of run()
      }
    
    
      // Our method that quits the thread
      void  quit() {
        System.out.println ("Quitting."); 
        running = false ;  // Setting running to false ends the loop in run()
        // IUn case the thread is waiting. . .
        interrupt();
      }
    }
    

答案 1 :(得分:0)

每个使用聊天功能的班级都需要知道聊天对象。您可以将所有不在单独的类中的变量和函数放在主源文件中。

在Processing中声明变量时,可以在任何选项卡中使用它,在java全局变量中不存在。您可以获得类似这样的功能:使用以下内容创建新文件 GlobalVars.java

public class GlobalVars {
   public static Chat myChat;
}

现在,每当您想要访问聊天功能时,您必须编写例如GlobalVars.myChat.sendMessage("Hi!");

顺便说一下,你必须包含net.jar文件。在Mac上,它位于: Processing.app/Contents/Resources/Java/modes/java/libraries/net/library/net.jar