0

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

我遇到的问题是我不能像在处理任何类/选项卡时那样调用 newChat.sendMessage(message)。有人可以告诉我我应该寻找什么来解决这个问题。我猜想扩展或实现 Xmpp 类是我需要做的。我喜欢简单的处理方式。

任何帮助将不胜感激。

仅供参考: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 类/选项卡:

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 类/选项卡:

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());
}
4

2 回答 2

1

如果您熟悉 eclipse,首先您需要创建一个新的 Java 项目并将 Processing 的 core.jar 添加到构建路径中,然后从创建 PApplet 的子类开始。如果没有,有一个非常容易使用的名为Proclipsing的 eclipse 插件和视频指南开始使用它。

断断续续的

将您的代码从处理带到日食:

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

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

  1. 创建一个新的 PApplet 子类并开始在其中粘贴整个代码(包括选项卡的内容)。您将需要明确访问器(例如public void setup(),而不是 just void setup())并注意双精度/浮点值(例如,如果 eclipse 抱怨 1.0,请明确:1.0f

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

例如

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();
  }
}
于 2012-08-19T09:14:35.390 回答
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

于 2013-06-20T08:26:09.360 回答