<commit_before>/**
 * Copyright (c) 2010-2016 by the respective copyright holders.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.openhab.binding.epsonprojector.connector;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.io.IOUtils;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

/**
 * Connector for serial port communication.
 *
 * @author <NAME>
 * @since 1.3.0
 */
public class EpsonProjectorSerialConnector implements EpsonProjectorConnector, SerialPortEventListener {

    private static final Logger logger = LoggerFactory.getLogger(EpsonProjectorSerialConnector.class);

    String serialPortName = null;
    InputStream in = null;
    OutputStream out = null;
    SerialPort serialPort = null;

    public EpsonProjectorSerialConnector(String serialPort) {
        serialPortName = serialPort;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void connect() throws EpsonProjectorException {

        try {
            logger.debug("Open connection to serial port '{}'", serialPortName);
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);

            CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

            serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            serialPort.enableReceiveThreshold(1);
            serialPort.disableReceiveTimeout();

            in = serialPort.getInputStream();
            out = serialPort.getOutputStream();

            out.flush();
            if (in.markSupported()) {
                in.reset();
            }

            // RXTX serial port library causes high CPU load
            // Start event listener, which will just sleep and slow down event loop
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            throw new EpsonProjectorException(e);
        }

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void disconnect() throws EpsonProjectorException {
        if (out != null) {
            logger.debug("Close serial out stream");
            IOUtils.closeQuietly(out);
        }
        if (in != null) {
            logger.debug("Close serial in stream");
            IOUtils.closeQuietly(in);
        }
        if (serialPort != null) {
            logger.debug("Close serial port");
            serialPort.close();
        }

        serialPort.removeEventListener();

        serialPort = null;
        out = null;
        in = null;

        logger.debug("Closed");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String sendMessage(String data, int timeout) throws EpsonProjectorException {
        if (in == null || out == null) {
            connect();
        }

        try {
            // flush input stream<commit_msg>[epson] NPE fix (#5616)<commit_after>/**
 * Copyright (c) 2010-2016 by the respective copyright holders.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.openhab.binding.epsonprojector.connector;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.io.IOUtils;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

/**
 * Connector for serial port communication.
 *
 * @author <NAME>
 * @since 1.3.0
 */
public class EpsonProjectorSerialConnector implements EpsonProjectorConnector, SerialPortEventListener {

    private static final Logger logger = LoggerFactory.getLogger(EpsonProjectorSerialConnector.class);

    String serialPortName = null;
    InputStream in = null;
    OutputStream out = null;
    SerialPort serialPort = null;

    public EpsonProjectorSerialConnector(String serialPort) {
        serialPortName = serialPort;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void connect() throws EpsonProjectorException {

        try {
            logger.debug("Open connection to serial port '{}'", serialPortName);
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);

            CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

            serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            serialPort.enableReceiveThreshold(1);
            serialPort.disableReceiveTimeout();

            in = serialPort.getInputStream();
            out = serialPort.getOutputStream();

            out.flush();
            if (in.markSupported()) {
                in.reset();
            }

            // RXTX serial port library causes high CPU load
            // Start event listener, which will just sleep and slow down event loop
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            throw new EpsonProjectorException(e);
        }

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void disconnect() throws EpsonProjectorException {
        if (out != null) {
            logger.debug("Close serial out stream");
            IOUtils.closeQuietly(out);
            out = null;
        }
        if (in != null) {
            logger.debug("Close serial in stream");
            IOUtils.closeQuietly(in);
            in = null;
        }
        if (serialPort != null) {
            logger.debug("Close serial port");
            serialPort.close();
            serialPort.removeEventListener();
            serialPort = null;
        }

        logger.debug("Closed");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String sendMessage(String data, int timeout) throws EpsonProjectorException {
        if (in == null || out == null) {
            connect();
        }

        try {
            // flush input stream
{'fraction_non_alphanumeric': 0.09693585337915235, 'fraction_numerical': 0.00859106529209622, 'mean_word_length': 2.5100502512562812, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '837298', 'n_tokens_mistral': 1900, 'n_tokens_neox': 1834, 'n_words': 460}