java 串口通信读取电子秤

1、在网上下载RXTXcomm.jar、rxtxParallel.dll、rxtxSerial.dll,有32位和64位的版本

2、把rxtxParallel.dll、rxtxSerial.dll拷贝到:C:\WINDOWS\system32下。

3、把RXTXcomm.jar、rxtxParallel.dll、rxtxSerial.dll拷贝到 jdk1.8.0_131\jre\lib\ext下;
     如:C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext

4、替换采样程序目录下的libs文件夹下的 RXTXcomm.jar

//打开串口 根据串口名、波特率
private static void openSerialPort()
{
    //读取可用端口
    commList = findPort();
    // 检查是否有可用串口,有则加入选项中
    if (commList == null || commList.size() < 1) {
        System.out.println("没有搜索到有效串口!");
        WriteLog("没有搜索到有效串口", "", "");
    } else {
        String CanUserCom = "";
        for (String s : commList) {
            CanUserCom += "  " + s;
        }
        WriteLog("搜索到有效串口:" + CanUserCom, "", "");
        WriteLog("连接电子秤时请确认波特率、数据位、停止位、奇偶校验等信息是否匹配!", "", "");
    }

    // 检查串口名称是否获取正确
    if (Common.CommName == null || Common.CommName.equals(""))
    {
        WriteLog("串口设置为空,请检查配置","","");
        System.out.println("串口设置为空,请检查配置!");
    }
    else
    {
        WriteLog(Common.CommName + "打开串口中、波特率:"+Common.BaudRate+"、数据位:"+Common.DataBits+"、停止为:"+Common.StopBits+"、奇偶校验:"+Common.CheckChar, "", "");
        String commName = Common.CommName;//串口
        int baudrate = Integer.valueOf(Common.BaudRate); //波特率
        int DataBits = Integer.valueOf(Common.DataBits); //数据位、
        int StopBits = Integer.valueOf(Common.StopBits); //停止为

        //奇偶校验位数据转换
        //无:0、奇数:1、偶数:2
        int ParityBits = 0; //奇偶校验
        switch (Common.ParityBits)
        {
            case "无":
                ParityBits = 0;
                break;
            case "奇":
                ParityBits = 1;
                break;
            case "偶":
                ParityBits = 2;
                break;
        }

        try
        {
            serialport = openPort(commName, baudrate,DataBits,StopBits,ParityBits);
            if (serialport != null)
            {
                WriteLog(commName + "串口已打开", "", "");
                System.out.println("串口已打开" + "\r\n");
               WriteFromPort(serialport);
            }
        } catch (SerialPortParameterFailure e) {
            e.printStackTrace();
        } catch (NotASerialPort e) {
            e.printStackTrace();
        } catch (NoSuchPort e) {
            e.printStackTrace();
        }
        catch (PortInUse e)
        {
            e.printStackTrace();
            System.out.println("串口已被占用!");
            WriteLog(commName+"串口已被占用","","");
            JOptionPane.showMessageDialog(null, "打开失败!串口已被占用或者软件已打开。", "提示", JOptionPane.ERROR_MESSAGE);
            logger.error("串口已被占用:" + e.getMessage(), e);
        }
    }

    try {
        addListener(serialport, new SerialListener());
    } catch (TooManyListeners e) {
        e.printStackTrace();
    }
}

//从串口读取数据
/**
 * 从串口读取数据
 *
 * @param serialPort
 *            当前已建立连接的SerialPort对象
 * @return 读取到的数据
 * @throws ReadDataFromSerialPortFailure
 *             从串口读取数据时出错
 * @throws SerialPortInputStreamCloseFailure
 *             关闭串口对象输入流出错
 */
public static byte[] readFromPort(SerialPort serialPort) throws ReadDataFromSerialPortFailure,SerialPortInputStreamCloseFailure {
    InputStream in = null;
    byte[] bytes = null;
    byte[] bytesAll = new byte[100];
    int bytesLenght = 0;
    try {
        in = serialPort.getInputStream();
        try {
            // 获取buffer里的数据长度
            int bufflenth = in.available();
            while (bufflenth != 0) {
                // 初始化byte数组为buffer中数据的长度
                bytes = new byte[bufflenth];
                in.read(bytes);
                bufflenth = in.available();
            }
            //System.err.println("in.available="+in.available());
        }catch(Exception ex)
        {}
    } catch (IOException e) {
        logger.error("从串口读取数据:" + e.getMessage(), e);
        throw new ReadDataFromSerialPortFailure();
    } finally {
        try {
            if (in != null) {
                in.close();
                in = null;
            }
        } catch (IOException e) {
            throw new SerialPortInputStreamCloseFailure();
        }
    }
    return bytes;
}


//向串口写数
public static void WriteFromPort(SerialPort serialPort) {
    try {
        //获取串口的输出流对象
        OutputStream outputStream = serialPort.getOutputStream();
        //通过串口的输出流向串口写数据
        outputStream.write(new byte[]{'1'});
        outputStream.flush();
        //关闭输出流
        outputStream.close();
        System.out.println("发送数据1");
    } catch (Exception e) {
        logger.error("从串口写数据:" + e.getMessage(), e);
    }
}


//处理监控到的串口事件
private static class SerialListener implements SerialPortEventListener {
    //处理监控到的串口事件
    public void serialEvent(SerialPortEvent serialPortEvent) {
        switch (serialPortEvent.getEventType()) {
            case SerialPortEvent.BI: // 10 通讯中断
                System.err.println("与串口设备通讯中断");
                WriteLog("与串口设备通讯中断","","");
                break;
            case SerialPortEvent.OE: // 7 溢位(溢出)错误
            case SerialPortEvent.FE: // 9 帧错误
            case SerialPortEvent.PE: // 8 奇偶校验错误
            case SerialPortEvent.CD: // 6 载波检测
            case SerialPortEvent.CTS: // 3 清除待发送数据
            case SerialPortEvent.DSR: // 4 待发送数据准备好了
            case SerialPortEvent.RI: // 5 振铃指示
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2 输出缓冲区已清空
                break;
            case SerialPortEvent.DATA_AVAILABLE: // 1 串口存在可用数据
                byte[] data = null;
                try {
                    if (serialport == null)
                    {
                        //System.err.println("串口对象为空!监听失败!");
                        WriteLog("串口对象为空!监听失败!", "", "");
                        System.err.println("串口对象为空!监听失败");
                    } else {
                        // 读取串口数据
                        data = readFromPort(serialport);
                        if(Portdata==null || Portdata.equals(""))
                            Portdata = new String(data);
                        else
                            Portdata += new String (data);

                        Portdata = Portdata.replaceAll("\r\n","");
                        ShowPortdata = Portdata;
                        System.err.println("data="+Portdata);
                        switch (Common.EquipType)
                        {
                            case "沈阳龙腾JD4000":
                                //波特率:1200 数据位8 校验位:无 停止位:1 起始为1 输出码 ASCII码  空格开始 S结束 返回数据: +200.34 GS  或者 -0.05 GS
                                int SIndex = Portdata.lastIndexOf("S");
                                int FIndex = Portdata.lastIndexOf(" ");
                                int FIndexZ = Portdata.lastIndexOf("+");
                                if(FIndex>=0 && SIndex>1)
                                {
                                    String WeightTemp = Portdata;
                                    String FirstChar = "+";
                                    if(FIndexZ>0)
                                        FirstChar = WeightTemp.substring(FIndexZ,FIndexZ+1);       //符号

                                    int GIndex = WeightTemp.indexOf("G");
                                    String Number = WeightTemp.substring(FIndexZ+1,GIndex);
                                    if(FirstChar.equals("+"))
                                        Weight = Number;             //将样重信息赋值给全局变量

                                    if(Weight.lastIndexOf("-")==0)
                                        Weight = "0.0";

                                    Portdata = "";  //取数成功后清空数据
                                }
                                break;
                            case "上海耀华XK3190":
                                //wn都存在
                                //wn00000.60kg
                                //存在此种情况只有w没有n:wn00000.60kgwn00000.60kgwn00000.60kgw00000.60kg0000.60kgw00000.60kgw00000.60kgw00000.60kgw00000.60kg
                                //此时去掉n后面的无效数据,重新获取n 和 k 的位置
                                if(Portdata!="")
                                {
                                    int LastFirstGIndex = Portdata.lastIndexOf("g");
                                    if(LastFirstGIndex>0)
                                    {
                                        Portdata = Portdata.substring(0, LastFirstGIndex);   //将末尾的不符合的数据截取掉
                                        int LastFirstKIndex = Portdata.lastIndexOf("k");
                                        if (LastFirstKIndex > 0) {
                                            String WeightTemp = Portdata.substring(LastFirstKIndex - 8, LastFirstKIndex);
                                            //WriteLog("WeightTemp="+WeightTemp, "", "");
                                            PortList.add(WeightTemp);
                                            Weight = GetStableWeight();
                                            Portdata = "";  //取数成功后清空数据
                                        }
                                    }
                                }
                                break;
                            case "博图BT419W":
                                //ST NT 000313.6 gST NT 000313.6 gST NT 000313.6 gST NT 000313.7 gST NT 000313.7 gST NT 000313.7 gST NT 000313.7 g
                                if(Portdata!="")
                                {
                                    int LastFirstGIndex = Portdata.lastIndexOf("g");
                                    if(LastFirstGIndex>0)
                                    {
                                        Portdata = Portdata.substring(0, LastFirstGIndex);   //将末尾的不符合的数据截取掉
                                        int LastFirstKIndex = Portdata.lastIndexOf(" ");
                                        if (LastFirstKIndex > 0) {
                                            String WeightTemp = Portdata.substring(LastFirstKIndex - 8, LastFirstKIndex);
                                            PortList.add(WeightTemp);
                                            Weight = GetStableWeight();
                                            Portdata = "";  //取数成功后清空数据
                                        }
                                    }
                                }
                                break;
                            case "自定义配置":
                                if(Portdata!="")
                                {
                                    int LastFirstGIndex = Portdata.lastIndexOf(Common.EndChar);
                                    if(LastFirstGIndex>0)
                                    {
                                        Portdata = Portdata.substring(0, LastFirstGIndex);   //将末尾的不符合的数据截取掉
                                        int LastFirstKIndex = Portdata.lastIndexOf(Common.NumberAfterChar);
                                        if (LastFirstKIndex > 0)
                                        {
                                            String WeightTemp = "";
                                            if(Common.symbol.equals(""))
                                            {
                                                WeightTemp = Portdata.substring(LastFirstKIndex - Integer.valueOf(Common.NumberLength), LastFirstKIndex);
                                            }
                                            else
                                            {
                                                //+200.34 GS  -200.34 GS
                                                int LastSymbol = Portdata.lastIndexOf(Common.symbol);
                                                WeightTemp = Portdata.substring(LastSymbol, LastFirstKIndex);
                                            }
                                            PortList.add(WeightTemp);
                                            Weight = GetStableWeight();
                                            Portdata = "";  //取数成功后清空数据
                                        }
                                    }
                                }
                                break;
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.toString());
                    logger.error("处理监控到的串口事件:" + e.getMessage(), e);
                    // 发生读取错误时显示错误信息后退出系统
                }
                break;
        }
    }
}

//获取稳定重量
private static String GetStableWeight()
{
    String RunWeight = "";
    //连续输出0时清空 PortList,防止内存溢出
    int PortLength = PortList.size();
    if(PortList.size()>10)
    {
        float OneNum = GetFloatNumber(PortList.get(PortLength - 11).toString());
        float TenNum = GetFloatNumber(PortList.get(PortLength-1).toString());
        //最后一个数减去倒数第十个数 变化小于1,表示数据稳定,然后取平均值 ,并清空PortList
        if(Math.abs(TenNum - OneNum)<1)
        {
            float AllWeight = 0;
            for(int i=0;i<10;i++)
            {
                AllWeight +=GetFloatNumber(PortList.get(PortLength - i-1).toString());
            }
            float WeightAvg = AllWeight/10.00f;
            RunWeight = String.valueOf(GetFloatNumber(String.valueOf(WeightAvg)));
            if(PortList.size()>100)
            {
                for(int i=0;i<50;i++)
                {
                    PortList.remove(i);
                }
            }
        }
    }
    return RunWeight;
}

//将字符串转为float
private static float GetFloatNumber(String fnum)
{
    float ft = Float.valueOf(fnum);
    int scale  = 2;//设置位数
    int roundingMode  =  4;//表示四舍五入,可以选择其他舍值方式,例如去尾,等等.
    BigDecimal bd = new  BigDecimal((double)ft);
    bd = bd.setScale(scale,roundingMode);
    ft = bd.floatValue();
    return ft;
}



//将ASCII转化为字符串
public static String asciiToString(String value)
{
    StringBuffer sbu = new StringBuffer();
    String[] chars = value.split(",");
    for (int i = 0; i < chars.length; i++) {
        sbu.append((char) Integer.parseInt(chars[i]));
    }
    return sbu.toString();
}

你可能感兴趣的:(java,串口,java)