package com.port;

import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
import com.fazecast.jSerialComm.SerialPort;

public class Main {

    static int inputPort=0;
    static SerialPort chosenPort;

    public static void main(String[] args) {
		
	// Aktive COM Ports ausgeben
	SerialPort[] portNames = SerialPort.getCommPorts();                     
	int i;
        for(i = 1; i <= portNames.length; i++)
            System.out.println(i+" :"+portNames[i-1].getSystemPortName());
        
        // Benutzer wählt COM Port
        Scanner scan = new Scanner(System.in);
        do{
            try{
                int input = Integer.parseInt(scan.nextLine());
                if((input>0) && (input<i))
                inputPort = input;
                else
                System.out.println("Bitte richtige Zahl eingeben!");
            }catch(Exception e){
                System.out.println("Bitte eine Zahl eingeben!");
            }
        }while(inputPort==0);

        System.out.println("Gewählter Port: "+inputPort);
        
        

        chosenPort = SerialPort.getCommPorts()[inputPort-1];
        chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
 
        System.out.println(chosenPort.getDescriptivePortName());
        
        if(chosenPort.openPort()) {
            
            // Seriell Lesen
            Thread threadIn = new Thread(){
                @Override public void run() {
                    Scanner input = new Scanner(chosenPort.getInputStream());
                    while(input.hasNextLine()) {
                        try {
                            String line = input.nextLine();
                            System.out.println(line);
                        } catch(Exception e) {}
                    }
                }
            };
            
            // Seriell Schreiben
            Thread threadOut = new Thread(){
		@Override public void run() {
                    try {Thread.sleep(100); } catch(Exception e) {}
                    PrintWriter output = new PrintWriter(chosenPort.getOutputStream());
                    output.println("G0 X100");
                    output.flush();
                }
            };
            
            threadIn.start();
            threadOut.start();
        }
        else {
            System.out.println("COM Port konnte nicht geöffnet werden");
        }
    } 
}
