Ejemplo n.º 1
0
  private void init() {

    try {
      if (m_out == null) {
        m_PortIdPrinter = CommPortIdentifier.getPortIdentifier(m_sPort); // Tomamos el puerto
        m_CommPortPrinter = m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto

        m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura

        if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          ((SerialPort) m_CommPortPrinter)
              .setSerialPortParams(
                  9600,
                  SerialPort.DATABITS_8,
                  SerialPort.STOPBITS_1,
                  SerialPort.PARITY_NONE); // Configuramos el puerto
        } else if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
          ((ParallelPort) m_CommPortPrinter).setMode(1);
        }
      }
    } catch (Exception e) {
      m_PortIdPrinter = null;
      m_CommPortPrinter = null;
      m_out = null;
      m_in = null;
      //        } catch (NoSuchPortException e) {
      //        } catch (PortInUseException e) {
      //        } catch (UnsupportedCommOperationException e) {
      //        } catch (IOException e) {
    }
  }
  public ProgrammerDialog(ProjectDriver plp, java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();

    this.plp = plp;

    plptool.PLPToolbox.attachHideOnEscapeListener(this);

    cmbPort.removeAllItems();
    if (plp.isSerialSupported() && Config.prgAutoDetectPorts) {
      Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        Msg.D("rxtx portId name: " + portId.getName() + " type: " + portId.getPortType(), 2, null);
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          cmbPort.addItem(portId.getName());
        }
      }
    } else {
      if (PLPToolbox.getOS(false) == Constants.PLP_OS_LINUX_32
          || PLPToolbox.getOS(false) == Constants.PLP_OS_LINUX_64) {
        cmbPort.addItem("/dev/ttyUSB0");
        cmbPort.addItem("/dev/ttyUSB1");
        cmbPort.addItem("/dev/ttyS0");
        cmbPort.addItem("/dev/ttyS1");
      } else if (PLPToolbox.getOS(false) == Constants.PLP_OS_WIN_32
          || PLPToolbox.getOS(false) == Constants.PLP_OS_WIN_64) {
        cmbPort.addItem("COM1");
        cmbPort.addItem("COM2");
        cmbPort.addItem("COM3");
        cmbPort.addItem("COM4");
      } else cmbPort.addItem("Specify your serial port here.");
    }

    javax.swing.KeyStroke escapeKeyStroke =
        javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0, false);
    javax.swing.Action escapeAction =
        new javax.swing.AbstractAction() {
          public void actionPerformed(java.awt.event.ActionEvent e) {
            setVisible(false);
            close();
          }
        };

    getRootPane()
        .getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(escapeKeyStroke, "ESCAPE");
    getRootPane().getActionMap().put("ESCAPE", escapeAction);

    this.setLocationRelativeTo(null);
  }
Ejemplo n.º 3
0
 /**
  * Initialize this device and open the serial port.
  *
  * @throws InitializationException if port can not be opened
  */
 void initialize() throws InitializationException {
   try {
     // parse ports and if the default port is found, initialized the reader
     portId = CommPortIdentifier.getPortIdentifier(port);
     // initialize serial port
     serialPort = portId.open("openHAB", 2000);
     // set port parameters
     serialPort.setSerialPortParams(baud, databits, stopbit, parity);
     inputStream = serialPort.getInputStream();
     outputStream = serialPort.getOutputStream();
   } catch (UnsupportedCommOperationException e) {
     throw new InitializationException(e);
   } catch (IOException e) {
     throw new InitializationException(e);
   } catch (PortInUseException e) {
     throw new InitializationException(e);
   } catch (NoSuchPortException e) {
     // enumerate the port identifiers in the exception to be helpful
     final StringBuilder sb = new StringBuilder();
     @SuppressWarnings("unchecked")
     Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
     while (portList.hasMoreElements()) {
       final CommPortIdentifier id = portList.nextElement();
       if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
         sb.append(id.getName() + "\n");
       }
     }
     throw new InitializationException(
         "Serial port '" + port + "' could not be found. Available ports are:\n" + sb.toString());
   }
 }
Ejemplo n.º 4
0
  public static boolean checkPort(){
	  SerialPort testPort = null;
	  String iname = Preferences.get("serial.port");
	  if(iname == null)
		  return false;
	  Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId =
          (CommPortIdentifier) portList.nextElement();

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
         // System.out.println("found " + portId.getName());
          if (portId.getName().equals(iname)) {
        	  try {
				 testPort = (SerialPort)portId.open("serial madness", 2000);
			} catch (PortInUseException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				System.out.println("[Serial]Port is already in use, press reset button!");
				//testPort.close();
				return false;
				
			}
        	 // System.out.println("[SERIAL]port is ok!");
        	  testPort.close();
        	  return true;
          }
        }
      }
      //System.out.println("[SERIAL]port is not ok!");
    //testPort.close();
	return false;
	  
  }
Ejemplo n.º 5
0
  public static boolean touchPort(String iname, int irate) throws SerialException {
    SerialPort port;
    boolean result = false;
    try {
      Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if ((CommPortIdentifier.PORT_SERIAL == portId.getPortType()) && (portId.getName().equals(iname))) {
          port = (SerialPort) portId.open("tap", 2000);
          port.setSerialPortParams(irate, 8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
          port.close();				
          result = true;
        }
      }
    } catch (PortInUseException e) {
      throw new SerialException(
        I18n.format(_("Serial port ''{0}'' already in use. Try quitting any programs that may be using it."), iname)
      );
    } catch (Exception e) {
      throw new SerialException(
        I18n.format(_("Error touching serial port ''{0}''."), iname), e
      );
    }
	return result;
  }
Ejemplo n.º 6
0
  /**
   * If this just hangs and never completes on Windows, 
   * it may be because the DLL doesn't have its exec bit set.
   * Why the hell that'd be the case, who knows.
   */
  static public List<String> list() {
    List<String> list = new ArrayList<String>();
    try {
      //System.err.println("trying");
      @SuppressWarnings("unchecked")
      Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      //System.err.println("got port list");
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId = 
          (CommPortIdentifier) portList.nextElement();
        //System.out.println(portId);

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          String name = portId.getName();
          list.add(name);
        }
      }

    } catch (UnsatisfiedLinkError e) {
      //System.err.println("1");
      errorMessage("ports", e);

    } catch (Exception e) {
      //System.err.println("2");
      errorMessage("ports", e);
    }
    //System.err.println("move out");
    return list;
  }
Ejemplo n.º 7
0
 public static void initSerial() {
   Enumeration portList = CommPortIdentifier.getPortIdentifiers();
   CommPortIdentifier portId = null;
   boolean portFound = false;
   while (portList.hasMoreElements()) {
     portId = (CommPortIdentifier) portList.nextElement();
     if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       if (portId.getName().equals("COM3")) {
         portFound = true;
       }
     }
   }
   if (!portFound) {
     System.out.println("port COM3 not found.");
     return;
   }
   SerialPort port;
   try {
     port = (SerialPort) portId.open("COM3", 2000);
     port.setSerialPortParams(
         115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
     comOS = new DataOutputStream(port.getOutputStream());
   } catch (PortInUseException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (UnsupportedCommOperationException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Ejemplo n.º 8
0
  public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        if (portId.getName().equals("COM17")) {
          // if (portId.getName().equals("/dev/term/a")) {
          try {
            serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
          } catch (PortInUseException e) {
          }

          try {
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {
          }
          try {
            serialPort.setSerialPortParams(
                9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {
          }

          try {
            outputStream.write(messageString.getBytes());
          } catch (IOException e) {
          }
        }
      }
    }
  }
Ejemplo n.º 9
0
 static void listPorts() {
   Enumeration portEnums = CommPortIdentifier.getPortIdentifiers();
   while (portEnums.hasMoreElements()) {
     CommPortIdentifier portId = (CommPortIdentifier) portEnums.nextElement();
     System.out.println(portId.getName() + " - " + getPortTypeName(portId.getPortType()));
     // System.out.println(portId.getName());
   }
 }
Ejemplo n.º 10
0
  @SuppressWarnings("unchecked")
  protected void refreshSerialPortList() {

    log.info("Refreshing serial port list...");
    Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
    availablePortNames = new ArrayList<String>();

    // Build a list of all serial ports found.
    while (portEnum != null && portEnum.hasMoreElements()) {

      CommPortIdentifier port = portEnum.nextElement();
      if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        log.info("Port name={}, Port type={}", port.getName(), port.getPortType());
        availablePortNames.add(port.getName());
      }
    }
  }
Ejemplo n.º 11
0
 public static void listPorts() {
   Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
   while (portEnum.hasMoreElements()) {
     CommPortIdentifier portIdentifier = portEnum.nextElement();
     System.out.println(
         portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType()));
   }
 }
Ejemplo n.º 12
0
  public static Serial open(String defaultPort) {
    boolean portFound = false;
    final int mComPortIdentifier = CommPortIdentifier.PORT_SERIAL;
    final Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    final int BAUD = 115200;

    while (portList.hasMoreElements()) {
      final CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
      System.out.println("Found port id: " + portId);

      if (portId.getPortType() == mComPortIdentifier) {
        System.out.println("Found CommPortIdentifier.");

        if (portId.getName().equals(defaultPort)) {
          System.out.println("Found port " + defaultPort);

          SerialPort serialPort;
          OutputStream outputStream = null;

          try {
            serialPort = (SerialPort) portId.open("SimpleWrite", 2000);
          } catch (PortInUseException e) {
            System.out.println("Port in use.");
            continue;
          }

          try {
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {
            e.printStackTrace();
          }

          try {
            serialPort.setSerialPortParams(
                BAUD, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {
            e.printStackTrace();
          }

          try {
            serialPort.notifyOnOutputEmpty(true);
          } catch (Exception e) {
            System.out.println("Error setting event notification");
            System.out.println(e.toString());
            System.exit(-1);
          }

          return new Serial(serialPort, outputStream);
        }
      }
    }

    if (!portFound) {
      System.out.println("port " + defaultPort + " not found.");
    }
    return null;
  }
Ejemplo n.º 13
0
 public static List<String> getAvailablePorts() {
   List<String> portNames = new ArrayList<>();
   Enumeration identifiers = CommPortIdentifier.getPortIdentifiers();
   while (identifiers.hasMoreElements()) {
     CommPortIdentifier identifier = (CommPortIdentifier) identifiers.nextElement();
     if (identifier.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       portNames.add(identifier.getName());
     }
   }
   return portNames;
 }
Ejemplo n.º 14
0
  // search for all the serial ports
  // pre: none
  // post: adds all the found ports to a combo box on the GUI
  public void searchForPorts() {
    ports = CommPortIdentifier.getPortIdentifiers();

    while (ports.hasMoreElements()) {
      CommPortIdentifier curPort = (CommPortIdentifier) ports.nextElement();

      // get only serial ports
      if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        portMap.put(curPort.getName(), curPort);
      }
    }
  }
Ejemplo n.º 15
0
  /*
   * Open the port, wait for chip init
   */
  public static int initialize(String portName) {
    System.out.println("Enumerating serial ports:");
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        // DDT
        System.out.println(portId.getName());

        if (portId.getName().equals(portName)) {
          System.out.println("Name match on port " + portName);
          // Init the port, matches name we were given
          try {
            serialPort = (SerialPort) portId.open("tx-skeleton", 64);
          } catch (PortInUseException e) {
            e.printStackTrace();
            System.out.println("Port in use!");
            return (4);
          }
          try {
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {
            System.out.println("Unable to connect to I/O streams");
            return (3);
          }

          try {
            System.out.println("Initializing ADXL202 board...");
            // 38400N81
            serialPort.setSerialPortParams(
                38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            // ADXL202 is powered via DTR line, so set it on
            serialPort.setDTR(true);

            try {
              // Wait a couple of seconds for chip to initialize (blinking LED)
              Thread.sleep(2000);
            } catch (InterruptedException ie) {
            }

          } catch (UnsupportedCommOperationException e) {
            System.out.println("Unable to configure serial port!");
            return (1);
          }
          return (0);
        }
      }
    }

    return (1);
  }
 private HashMap<String, CommPortIdentifier> getAvailablePorts() {
   HashMap<String, CommPortIdentifier> result = new HashMap<String, CommPortIdentifier>();
   Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
   while (ports.hasMoreElements()) {
     CommPortIdentifier port = ports.nextElement();
     if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       result.put(port.getName(), port);
       logger.info(port.getName());
       logger.info(port.getCurrentOwner());
     }
   }
   return result;
 }
Ejemplo n.º 17
0
  @Override
  public HashMap<String, CommPortIdentifier> getAvailablePorts() {
    HashMap<String, CommPortIdentifier> portMap = new HashMap<>();
    Enumeration<?> ports = CommPortIdentifier.getPortIdentifiers();

    while (ports.hasMoreElements()) {
      CommPortIdentifier curPort = (CommPortIdentifier) ports.nextElement();

      if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        portMap.put(curPort.getName(), curPort);
      }
    }
    return portMap;
  }
Ejemplo n.º 18
0
 // find all available serial ports for the settings->ports menu.
 public String[] ListSerialPorts() {
   @SuppressWarnings("unchecked")
   Enumeration<CommPortIdentifier> ports =
       (Enumeration<CommPortIdentifier>) CommPortIdentifier.getPortIdentifiers();
   ArrayList<String> portList = new ArrayList<String>();
   while (ports.hasMoreElements()) {
     CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
     if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       portList.add(port.getName());
     }
   }
   portsDetected = (String[]) portList.toArray(new String[0]);
   return portsDetected;
 }
  /** 获得所有可用串口 */
  public ArrayList<String> getAllports() {
    @SuppressWarnings("rawtypes")
    Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    CommPortIdentifier portId;

    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        this.sPorts.add(portId.getName());
      }
    }
    System.out.println(this.sPorts.toString());
    return sPorts;
  }
Ejemplo n.º 20
0
 @SuppressWarnings("unchecked")
 public Vector<String> getPortNames() {
   // first, check that the comm package can be opened and ports seen
   portNameVector = new Vector<String>();
   Enumeration<CommPortIdentifier> portIDs = CommPortIdentifier.getPortIdentifiers();
   // find the names of suitable ports
   while (portIDs.hasMoreElements()) {
     CommPortIdentifier id = portIDs.nextElement();
     // filter out line printers
     if (id.getPortType() != CommPortIdentifier.PORT_PARALLEL) // accumulate the names in a vector
     {
       portNameVector.addElement(id.getName());
     }
   }
   return portNameVector;
 }
Ejemplo n.º 21
0
  public Collection<Device> scanPorts() {

    Collection<Device> devicesFound = new ArrayList<Device>();

    Enumeration portList;
    CommPortIdentifier portId;

    portList = CommPortIdentifier.getPortIdentifiers();
    Logger.getLogger(Things.class.getName()).log(Level.INFO, "Starting jHome 1.0");
    SerialPort serialPort = null;
    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      Logger.getLogger(Things.class.getName()).log(Level.INFO, "Scaning port: " + portId.getName());

      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        Logger.getLogger(Things.class.getName())
            .log(
                Level.INFO,
                "Serial Device Port found "
                    + portId.getName()
                    + ". Trying to discovery this device.");
        try {
          /*serialPort =
          (SerialPort) portId.open(portId.getName(), 115200);
          Device device = new SerialDevice(serialPort);*/
          Device device = new SerialDevice(portId, DEFAULT_BAUDRATE);
          device.open();
          device.discovery();
          if (device.connected()) {
            devicesFound.add(device);
          } else {
            Logger.getLogger(Things.class.getName())
                .log(Level.INFO, "Serial Device is not Things API Compatible" + portId.getName());
            device.close();
          }
          devicesFound.add(device);
        } catch (Exception e) {
          Logger.getLogger(Things.class.getName())
              .log(Level.SEVERE, "Couldn't connect to" + portId.getName());
          e.printStackTrace();
        }
      }
    }
    return devicesFound;
  }
Ejemplo n.º 22
0
  /** Populate the serial port drop-down list */
  private void createPortList() {
    try {
      Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          String name = portId.getName();
          // ignore /dev/tty to prevent duplicate serial port listings (/dev/tty and /dev/cu)
          // also ignore OS X Bluetooth serial ports
          if (!name.startsWith("/dev/tty.") && !name.contains("Bluetooth")) {
            serialPorts.addItem(name);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** @param data */
  @Override
  protected void internalWrite(byte[] data) {
    try {
      if (m_out == null) {
        m_PortIdPrinter =
            CommPortIdentifier.getPortIdentifier(
                m_sPortPrinter); // Tomamos el puerto
        m_CommPortPrinter = m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto

        m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura

        if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          ((SerialPort) m_CommPortPrinter)
              .setSerialPortParams(
                  9600,
                  SerialPort.DATABITS_8,
                  SerialPort.STOPBITS_1,
                  SerialPort.PARITY_NONE); // Configuramos el puerto
          ((SerialPort) m_CommPortPrinter)
              .setFlowControlMode(
                  SerialPort
                      .FLOWCONTROL_RTSCTS_IN); // this line prevents the printer tmu220 to stop
                                               // printing after +-18 lines printed
          // this line prevents the printer tmu220 to stop printing after +-18 lines printed. Bug
          // 8324
          // But if added a regression error appears. Bug 9417, Better to keep it commented.
          // ((SerialPort)m_CommPortPrinter).setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
          // Not needed to set parallel properties
          //                } else if (m_PortIdPrinter.getPortType() ==
          // CommPortIdentifier.PORT_PARALLEL) {
          //                    ((ParallelPort)m_CommPortPrinter).setMode(1);

        }
      }
      m_out.write(data);
      // JG 16 May 12 use multicatch
    } catch (NoSuchPortException
        | PortInUseException
        | UnsupportedCommOperationException
        | IOException e) {
      System.err.println(e);
    }
  }
Ejemplo n.º 24
0
 /**
  * @return A HashSet containing the CommPortIdentifier for all serial ports that are not currently
  *     being used.
  */
 @SuppressWarnings({"rawtypes"})
 private static HashSet<CommPortIdentifier> getAvailableSerialPorts() {
   HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>();
   Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
   while (thePorts.hasMoreElements()) {
     CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement();
     switch (com.getPortType()) {
       case CommPortIdentifier.PORT_SERIAL:
         try {
           CommPort thePort = com.open("CommUtil", 50);
           thePort.close();
           h.add(com);
         } catch (PortInUseException e) {
           System.out.println("Port, " + com.getName() + ", is in use.");
         } catch (Exception e) {
           System.err.println("Failed to open port " + com.getName());
           e.printStackTrace();
         }
     }
   }
   return h;
 }
Ejemplo n.º 25
0
  /** Check if the serial port list has changed */
  private void checkPortList() {
    serialPortCount = 0;

    try {
      Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          String name = portId.getName();
          if (!name.startsWith("/dev/tty.") && !name.contains("Bluetooth")) {
            serialPortCount++;
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (serialPortCount != serialPorts.getItemCount()) {
      // an I/O board was added or removed so update the list
      updatePortList();
    }
  }
Ejemplo n.º 26
0
  public static void main(String[] args) {

    boolean boolArgs = false;
    if ((args.length == 0) || (args.length == 1)) {
      log.error(
          MARKER_RunPcOpRs1Sender,
          "{} please input device name (e.g. /dev/ttyUSB0) and input file",
          Thread.currentThread().getStackTrace()[1].getMethodName());
    } else if (args.length > 2) {
      log.error(
          MARKER_RunPcOpRs1Sender,
          "{} too many args",
          Thread.currentThread().getStackTrace()[1].getMethodName());
    } else {
      boolArgs = true;
    }

    if (boolArgs) {

      String deviceName = args[0];
      // String deviceName = "/dev/ttyUSB0";
      log.debug(
          MARKER_RunPcOpRs1Sender,
          "{} [deviceName] {}",
          Thread.currentThread().getStackTrace()[1].getMethodName(),
          deviceName);

      String signalPath = args[1];
      log.debug(
          MARKER_RunPcOpRs1Sender,
          "{} [signalPath] {}",
          Thread.currentThread().getStackTrace()[1].getMethodName(),
          signalPath);

      CommPortIdentifier portID;
      // SerialPort port;

      @SuppressWarnings("unchecked")
      Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();

      while (portList.hasMoreElements()) {

        portID = (CommPortIdentifier) portList.nextElement();
        log.debug(
            MARKER_RunPcOpRs1Sender,
            "{} [portID.getName()] {}",
            Thread.currentThread().getStackTrace()[1].getMethodName(),
            portID.getName());

        if (portID.getPortType() == CommPortIdentifier.PORT_SERIAL) {

          log.debug(
              MARKER_RunPcOpRs1Sender,
              "{} {} is a serial device",
              Thread.currentThread().getStackTrace()[1].getMethodName(),
              deviceName);

          if (portID.getName().equals(deviceName)) {

            if (portID.isCurrentlyOwned()) {
              log.debug(
                  MARKER_RunPcOpRs1Sender,
                  "{} {} is currently owned",
                  Thread.currentThread().getStackTrace()[1].getMethodName(),
                  deviceName);
              break;
            } else {
              log.debug(
                  MARKER_RunPcOpRs1Sender,
                  "{} {} can be used",
                  Thread.currentThread().getStackTrace()[1].getMethodName(),
                  deviceName);

              PcOpRs1Sender rxtx = new PcOpRs1Sender(deviceName, signalPath);

              if (rxtx.openSerialPort()) {
                if (rxtx.setSerialPort()) {
                  rxtx.send0x74();
                } else {
                  break;
                }
              } else {
                break;
              }
            }

          } else {
            log.debug(
                MARKER_RunPcOpRs1Sender,
                "{} {} is not match {}",
                Thread.currentThread().getStackTrace()[1].getMethodName(),
                portID.getName(),
                deviceName);
          }

        } else if (portID.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
          log.debug(
              MARKER_RunPcOpRs1Sender,
              "{} {} is a parallel device",
              Thread.currentThread().getStackTrace()[1].getMethodName(),
              deviceName);
          break;
        } else {
          log.debug(
              MARKER_RunPcOpRs1Sender,
              "{} {} is an unknown device",
              Thread.currentThread().getStackTrace()[1].getMethodName(),
              deviceName);
          break;
        }
      } // while()
    } // if bool
  } // main()
Ejemplo n.º 27
0
  /**
   * python example def transmit_to_widget(label, data, data_size): ser.write(chr(SOM_VALUE))
   * ser.write(chr(label)) ser.write(chr(data_size & 0xFF)) // lsb ser.write(chr((data_size >> 8) &
   * 0xFF)) // msb for j in range(data_size): ser.write(data[j]) ser.write(chr(EOM_VALUE))
   */
  private void write() {

    char som = 0x7E;
    char eom = 0xE7;
    char label = 6; // 10 serial , 6 send

    Integer[] chan = getChannelData();

    int data_size = chan.length;

    char clsb = (char) (data_size & 0xFF);
    char cmsb = (char) ((data_size >> 8) & 0xFF);

    byte lsb = (byte) clsb;
    byte msb = (byte) cmsb;

    ArrayList<Byte> ab = new ArrayList<Byte>();
    ab.add((byte) som); // start delimter
    ab.add((byte) label); // label - whats happening
    ab.add(lsb); // start byte
    ab.add(msb); // mast
    for (int i = 0; i < data_size; i++) {
      ab.add(chan[i].byteValue());
    }
    ab.add((byte) eom);

    // Byte[] messageString = new Byte[ab.size()];
    // messageString = ab.toArray(messageString);
    byte[] messageString = new byte[ab.size()];
    for (int i = 0; i < ab.size(); i++) {
      messageString[i] = ab.get(i);
    }

    // debug in hex
    debugBytes(messageString);

    boolean portFound = false;
    String defaultPort = "/dev/ttyUSB0";

    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();

      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

        if (portId.getName().equals(defaultPort)) {
          System.out.println("Found port " + defaultPort);

          portFound = true;

          try {
            serialPort = (SerialPort) portId.open("SimpleWrite", 2000);
          } catch (PortInUseException e) {
            System.out.println("Port in use.");
            e.printStackTrace();
            continue;
          }

          try {
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {
            e.printStackTrace();
          }

          try {
            serialPort.setSerialPortParams(
                57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {
            e.printStackTrace();
          }

          try {
            serialPort.notifyOnOutputEmpty(true);
          } catch (Exception e) {
            System.out.println("Error setting event notification");
            System.out.println(e.toString());
            e.printStackTrace();
            System.exit(-1);
          }

          System.out.println("Writing \"" + messageString + "\" to " + serialPort.getName());

          try {
            outputStream.write(messageString);
          } catch (IOException e) {
            e.printStackTrace();
          }

          try {
            Thread.sleep(2000); // Be sure data is xferred before closing
          } catch (Exception e) {
            e.printStackTrace();
          }
          serialPort.close();
          System.exit(1);
        }
      }
    }

    if (!portFound) {
      System.out.println("port " + defaultPort + " not found.");
    }
  }
Ejemplo n.º 28
0
  public Serial(String iname, int irate,
                 char iparity, int idatabits, float istopbits)
  throws SerialException {
    //if (port != null) port.close();
    //this.parent = parent;
    //parent.attach(this);

    this.rate = irate;
    
    parity = SerialPort.PARITY_NONE;
    if (iparity == 'E') parity = SerialPort.PARITY_EVEN;
    if (iparity == 'O') parity = SerialPort.PARITY_ODD;

    this.databits = idatabits;

    stopbits = SerialPort.STOPBITS_1;
    if (istopbits == 1.5f) stopbits = SerialPort.STOPBITS_1_5;
    if (istopbits == 2) stopbits = SerialPort.STOPBITS_2;

    try {
      port = null;
      Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId =
          (CommPortIdentifier) portList.nextElement();

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          //System.out.println("found " + portId.getName());
          if (portId.getName().equals(iname)) {
            //System.out.println("looking for "+iname);
            port = (SerialPort)portId.open("serial madness", 2000);
           
            input = port.getInputStream();
            output = port.getOutputStream();
            port.setSerialPortParams(rate, databits, stopbits, parity);
            port.addEventListener(this);
            port.notifyOnDataAvailable(true);
            //port.setFlowControlMode(SerialPort.FLOWCONTROL_XONXOFF_IN | SerialPort.FLOWCONTROL_XONXOFF_OUT);
            //port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
            port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
            
           // System.out.println("[Serial]opening, ready to roll");
          }
        }
      }
    } catch (PortInUseException e) {
      throw new SerialException(
        I18n.format(
          _("Serial port ''{0}'' already in use. Try quiting any programs that may be using it."),
          iname
        )
      );
    } catch (Exception e) {
      throw new SerialException(
        I18n.format(
          _("Error opening serial port ''{0}''."),
          iname
        ),
        e
      );
//      //errorMessage("<init>", e);
//      //exception = e;
//      //e.printStackTrace();
    }
    
    if (port == null) {
    	System.out.println("Port is missing");
    }
  }
Ejemplo n.º 29
0
  /**
   * Initialize this device and open the serial port
   *
   * @throws InitializationException if port can not be opened
   */
  @SuppressWarnings("rawtypes")
  public void initialize() throws InitializationException {
    // parse ports and if the default port is found, initialized the reader
    Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
      CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
      if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        if (id.getName().equals(port)) {
          logger.debug("Serial port '{}' has been found.", port);
          portId = id;
        }
      }
    }
    if (portId != null) {
      // initialize serial port
      try {
        serialPort = portId.open("openHAB", 2000);
      } catch (PortInUseException e) {
        throw new InitializationException(e);
      }

      try {
        inputStream = serialPort.getInputStream();
      } catch (IOException e) {
        throw new InitializationException(e);
      }

      try {
        serialPort.addEventListener(this);
      } catch (TooManyListenersException e) {
        throw new InitializationException(e);
      }

      // activate the DATA_AVAILABLE notifier
      serialPort.notifyOnDataAvailable(true);

      try {
        // set port parameters
        serialPort.setSerialPortParams(
            baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      } catch (UnsupportedCommOperationException e) {
        throw new InitializationException(e);
      }

      try {
        // get the output stream
        outputStream = serialPort.getOutputStream();
      } catch (IOException e) {
        throw new InitializationException(e);
      }
    } else {
      StringBuilder sb = new StringBuilder();
      portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
        if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          sb.append(id.getName() + "\n");
        }
      }
      throw new InitializationException(
          "Serial port '" + port + "' could not be found. Available ports are:\n" + sb.toString());
    }
  }