java串口获取单片机传来的图片

导读:本篇文章讲解 java串口获取单片机传来的图片,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

java串口获取单片机传来的图片

package com.hunau.Port2;

import gnu.io.*;

import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import java.util.TooManyListenersException;

import javax.imageio.stream.FileImageOutputStream;

import com.hunau.images.ImageUtil;
import com.hunau.images.mysqlimages;
/**
 * @program: AGPS
 * @description: java串口获取单片机传来的图片
 * @author: Mr.Liu
 * @create: 2019-02-23 16:51
 **/
public class read implements SerialPortEventListener {
   
    protected static CommPortIdentifier portid = null;  //通讯端口标识符
    protected static SerialPort comPort = null;         //串行端口
    protected static int BAUD = 115200;  //波特率
    protected static int DATABITS = SerialPort.DATABITS_8;
      //数据位
    protected static int STOPBITS = SerialPort.STOPBITS_1;  //停止位
    protected static int PARITY = SerialPort.PARITY_NONE;  //奇偶检验
    public static OutputStream oStream;    //输出流
    public static InputStream iStream;     //输入流

    /**
     * 读取所有串口名字
     */
    private void listPortChoices() {
        CommPortIdentifier portId;
        Enumeration en = CommPortIdentifier.getPortIdentifiers();
        // iterate through the ports.
        while (en.hasMoreElements()) {
            portId = (CommPortIdentifier) en.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println(portId.getName());
            }
        }
    }

    /**
     * 设置串口号
     * 获取数据
     * @param
     * @return
     */
    public void setSerialPortNumber() {

        String osName = null;
        String osname = System.getProperty("os.name", "").toLowerCase();
        if (osname.startsWith("windows")) {
            // windows
            osName = "COM5";
        } else if (osname.startsWith("linux")) {
            // linux
            osName = "/dev/ttyS1";
        }
        System.out.println(osName);
        try {
            portid = CommPortIdentifier.getPortIdentifier(osName);
            // portid = CommPortIdentifier.getPortIdentifier(Port);
            if (portid.isCurrentlyOwned()) {
                System.out.println("端口在使用");
            } else {
                comPort = (SerialPort) portid.open(this.getClass().getName(), 1000);//this.getClass().getName()
            }
        } catch (PortInUseException e) {
            System.out.println("端口被占用");
            e.printStackTrace();

        } catch (NoSuchPortException e) {
            System.out.println("端口不存在");
            e.printStackTrace();
        }

        

        try {
            //设置串口参数依次为(波特率,数据位,停止位,奇偶检验)
            comPort.setSerialPortParams(BAUD, DATABITS, STOPBITS, PARITY);
        } catch (UnsupportedCommOperationException e) {
            System.out.println("端口操作命令不支持");
            e.printStackTrace();
        }
        try {
            comPort.addEventListener(this);       //给当前串口增加一个监听器
            comPort.notifyOnDataAvailable(true);  //当有数据时通知
            //System.out.print("有数据");
        } catch (TooManyListenersException e) {
            e.printStackTrace();
        }
      //记录已经到达串口COM4且未被读取的数据的字节(Byte)数。
        int availableBytes = 0;
      //定义用于缓存读入数据的数组
        byte[] cache = new byte[10240];
        try {
            iStream = comPort.getInputStream(); //从COM5获取数据
            
            System.out.println("获取的数据对象:"+iStream);
            StringBuffer sb = new StringBuffer(); 
            //StringBuffer data = new StringBuffer(); 
            String path = "C:\\Users\\liuyanbin\\Desktop\\images\\a.jpg";
            while (true) {
            		availableBytes = iStream.available();
            		
	               	while (availableBytes>0) {
	               		byte[] imgdata = new byte[10240];
	               		//从串口的输入流对象中读入数据并将数据存放到缓存数组中
	               		iStream.read(cache);
	               		/*for (int i = 0;i < cache.length && i < availableBytes; i++) {
	               			System.out.print((cache[i]& 0xff) +"*");
	   					}*/
	               		
	               		//System.arraycopy(cache, srcPos, dest, destPos, length);
	               		int end = 0;
	               		/**
	               		 * 下面的32 33是通过数据推算出来的图片数据起始位置
	               		 * 要是用不同的格式照片,这个要改
	               		 * (cache[i-1] == -1 && cache[i]==-39)是图片数据结束位置
	               		 * **/
	               	    for(int i =32,j=0; i < cache.length&& i < availableBytes; i++) {  
	               	        
	               	        if(cache[32]==-1 && cache[33] ==-40)
	               	        	{
	               	        		imgdata[j++]=cache[i];
	               	        		//System.out.print(cache[i]);
	               	        	}
	               	        if((cache[32]!=-1 && cache[33] !=-40)||(cache[i-1] == -1 && cache[i]==-39))
	               	        {
	               	        	end = i;//返回一个结束点
	               	        	//System.out.print(end);
	               	        	break;
	               	        }
	               	    } 

		               	   
		              if(end>100){//一个简单的过滤条件
		            	  byte2image(cache,end,path);
		            	  
		              }
	               	 System.out.print("\n");
	               	    
                   	availableBytes = iStream.available();
	                   	/**
	                   	 * 设置暂停的时间 5 秒,以便每一次能够接收到全部图片数据
	                   	 * 可根据不同的单片机数据发送上来的时间决定
	                   	 * **/
	                   	Thread.sleep(5*1000); 
	       			}


			}
           // oStream = comPort.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    /**
     * byte数组到图片
     * 
     * **/
    public void byte2image(byte[] data,int end,String path){
      	
		String path2 = path;
      try{
	      FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path2));
	      /*for (int i = 32; i < end+1; i++) {
			System.out.print(data[i]);
		}//检查数据是否正确*/
	      imageOutput.write(data, 32, end+1);
	      imageOutput.close();
	      System.out.println("Make Picture success,Please find image in " + path2);
	      Thread.sleep(100); //设置暂停的时间 100 毫秒
	      readImage2DB(path);
      } catch(Exception ex) {
	        System.out.println("Exception错误: " + ex);
	        ex.printStackTrace();
      }
    }
    /**
     * 将图片插入数据库
     * 
     * **/ 
    public static void readImage2DB(String path) {
    	Date now = new Date(); 
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
		String hehe = dateFormat.format( now ); 
		System.out.println(hehe); 

        Connection conn = null;
        PreparedStatement ps = null;
        FileInputStream in = null;
        try {
            in = ImageUtil.readImage(path);

            conn = mysqlimages.getConn();
            String sql = "insert into tb_images2 (id,image,tip,zhushi,date,enable,name)values(NULL,?,?,?,?,1,?)";
            ps = conn.prepareStatement(sql);
            ps.setBinaryStream(1, in, in.available());
            ps.setString(2, "test");
            ps.setString(3, "I likes to play");
            ps.setString(4, hehe);
            ps.setString(5, "hunau");
            int count = ps.executeUpdate();
            if (count > 0) {
                System.out.println("插入成功!");
            } else {
                System.out.println("插入失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mysqlimages.closeConn(conn);
            if (null != ps) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    @Override
    public void serialEvent(SerialPortEvent event) {
        switch (event.getEventType()) {
            case SerialPortEvent.BI:
            case SerialPortEvent.OE:
            case SerialPortEvent.FE:
            case SerialPortEvent.PE:
            case SerialPortEvent.CD:
            case SerialPortEvent.CTS:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;
            case SerialPortEvent.DATA_AVAILABLE:// 当有可用数据时读取数据,并且给串口返回数据
                //进来后 就不是第一次了
                //TODO
                break;
        }
    }
    public static void main(String[] args) {
    	read se = new read();
    	se.setSerialPortNumber();
    	
	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/64721.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!