Bläddra i källkod

add: 远程升级

wulianwei 2 år sedan
förälder
incheckning
5bc478824b

BIN
file/1.2.bin


+ 2 - 1
src/main/java/com/tuoren/remote/AES.java

@@ -68,8 +68,9 @@ public class AES {
          */ 
         // 需要加密的字串 
     	String cKey = "tuorenzhinenghua"; 
-        String cSrc = "43186642383902B4&a1xJ4qC587v&89860471162180041210"; 
+        String cSrc = "{\"method\":\"getRemoteConf\",\"params\":{\"device\":\"51258111303002A9\"}}"; 
         System.out.println(cSrc); 
+
         // 加密 
         byte[] enString = AES.encrypt(cSrc, cKey); 
         for(byte a:enString)

+ 46 - 9
src/main/java/com/tuoren/remote/MyServer.java

@@ -1,5 +1,6 @@
 package com.tuoren.remote;
 
+import java.io.File;
 import java.sql.Connection;
 import java.sql.ResultSet;
 import java.util.Date;
@@ -11,6 +12,7 @@ import org.slf4j.LoggerFactory;
 
 import com.alibaba.fastjson.JSONObject;
 
+import cn.hutool.core.util.HexUtil;
 import cn.hutool.db.sql.SqlExecutor;
 import io.netty.bootstrap.ServerBootstrap;
 import io.netty.buffer.ByteBuf;
@@ -78,14 +80,25 @@ class MyServerHandler extends ChannelInboundHandlerAdapter{
         JSONObject jsonRequest = JSONObject.parseObject(msgStr);
         
         String jsonString = "{\"code\":\"1\"}";
+        byte[] resultOut = null;
         String ip = ctx.channel().remoteAddress().toString();
         logger.info("regist ip :"+ip);
         String method = jsonRequest.getString("method");
-        
+        JSONObject params = jsonRequest.getJSONObject("params");
         try {
         	if("getRemoteConf".equals(method)){
-        		JSONObject params = jsonRequest.getJSONObject("params");
-        		jsonString = handleRegist(params);
+        		jsonString = handleRemote(params);
+        		System.out.println("jsonResult:"+jsonString);
+        		 resultOut = AES.encrypt(jsonString,key);
+            }else if("checkUpdate".equals(method)) {
+            	jsonString = handleCheck(params);
+            	 resultOut = AES.encrypt(jsonString,key);
+            }else if("getUpdateFile".equals(method)) {
+            	resultOut = handleUpdateFile(params);
+            	for(byte a:resultOut)
+       		 {
+       			 System.out.printf("%02x",a);
+       		 }
             }
         	
         }catch (Exception e) {
@@ -93,22 +106,24 @@ class MyServerHandler extends ChannelInboundHandlerAdapter{
         	logger.error("regist error:"+e);
 		}
         
-        byte[] resultRegist = AES.encrypt(jsonString,key);
-        ByteBuf encoded = ctx.alloc().buffer(2 * resultRegist.length);  
        
-        encoded.writeBytes(resultRegist);
+        ByteBuf encoded = ctx.alloc().buffer(2 * resultOut.length);  
+       
+        encoded.writeBytes(resultOut);
         ctx.channel().writeAndFlush(encoded);
         ctx.flush();
 	}
 	
-	private String handleRegist(JSONObject jsonData) throws Exception{
+	private String handleRemote(JSONObject jsonData) throws Exception{
 		JSONObject json = new JSONObject();
         json.put("code", 1);   
        
-        String deviceName = jsonData.getString("devive");
+        String deviceName = jsonData.getString("device");
   
         Connection conn = ds.getConnection();
-        ResultSet resultSet =  SqlExecutor.callQuery(conn, "select type,total_dose,first_dose,max_dose,append_dose,continue_dose,self_control_lock_time,patient_code from bus_device_configuration where device_id = ? limit 1", deviceName);
+        ResultSet resultSet =  SqlExecutor.callQuery(conn, "select c.type,c.total_dose,c.first_dose,c.max_dose,c.append_dose,c.continue_dose"
+        		+ ",c.self_control_lock_time,c.patient_code from bus_device_configuration c "
+        		+ "inner join bus_device d on d.remote_config_id = c.id and d.device_id = ? limit 1", deviceName);
         if(resultSet.next()){
         	json.put("code", 0);
         	json.put("hosnum", resultSet.getString("patient_code"));
@@ -130,6 +145,28 @@ class MyServerHandler extends ChannelInboundHandlerAdapter{
         return json.toString();
 	}
 	
+	private String handleCheck(JSONObject jsonData) throws Exception{
+		JSONObject json = new JSONObject();
+        json.put("update_flag", 1); //是否可以升级
+        json.put("update_file", "1.2.bin");    
+        return json.toString();
+	}
+	
+	private byte[] handleUpdateFile(JSONObject jsonData) throws Exception{
+		byte[] bs = null;
+		String file = jsonData.getString("file");
+		String workdir =  System.getProperty("user.dir");
+		System.out.println(workdir);
+		File fileF = new File(workdir+"/file/"+file);
+		byte blockNum = jsonData.getByte("blockNum");
+        if(0==blockNum) {
+        	bs = YModem.fileInfo(fileF, file);
+        }else {
+        	bs = YModem.fileData(fileF, blockNum);
+        }
+        return bs;
+	}
+	
 }
 	
 	

+ 289 - 0
src/main/java/com/tuoren/remote/TModem.java

@@ -0,0 +1,289 @@
+package com.tuoren.remote;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+
+class TModem {
+
+    protected final byte CPMEOF = 26;       /* control/z */
+    protected final int MAXERRORS = 10;     /* max times to retry one block */
+    protected final int SECSIZE = 128;      /* cpm sector, transmission block */
+    protected final int SENTIMOUT = 30;     /* timeout time in send */
+    protected final int SLEEP   = 30;       /* timeout time in recv */
+
+    /* Protocol characters used */
+
+    protected final byte    SOH = 1;    /* Start Of Header */
+    protected final byte    EOT = 4;    /* End Of Transmission */
+    protected final byte    ACK = 6;    /* ACKnowlege */
+    protected final byte    NAK = 0x15; /* Negative AcKnowlege */
+
+    protected InputStream inStream;
+    protected OutputStream outStream;
+    protected PrintWriter errStream;
+
+    /** Construct a TModem */
+    public TModem(InputStream is, OutputStream os, PrintWriter errs) {
+        inStream = is;
+        outStream = os;
+        errStream = errs;
+    }
+
+    /** Construct a TModem with default files (stdin and stdout). */
+    public TModem() {
+        inStream = System.in;
+        outStream = System.out;
+        errStream = new PrintWriter(System.err);
+    }
+
+    /** A main program, for direct invocation. */
+    public static void main(String[] argv) throws 
+        IOException, InterruptedException {
+
+        /* argc must == 2, i.e., `java TModem -s filename' */
+        if (argv.length != 2) 
+            usage();
+
+        if (argv[0].charAt(0) != '-')
+            usage();
+
+        TModem tm = new TModem();
+        tm.setStandalone(true);
+
+        boolean OK = false;
+        switch (argv[0].charAt(1)){
+        case 'r': 
+            OK = tm.receive(argv[1]); 
+            break;
+        case 's': 
+            OK = tm.send(argv[1]); 
+            break;
+        default: 
+            usage();
+        }
+        System.out.print(OK?"Done OK":"Failed");
+        System.exit(0);
+    }
+
+    /* give user minimal usage message */
+    protected static void usage()
+    {
+        System.err.println("usage: TModem -r/-s file");
+        // not errStream, not die(), since this is static.
+        System.exit(1);
+    }
+
+    /** If we're in a standalone app it is OK to System.exit() */
+    protected boolean standalone = false;
+    public void setStandalone(boolean is) {
+        standalone = is;
+    }
+    public boolean isStandalone() {
+        return standalone;
+    }
+
+    /** A flag used to communicate with inner class IOTimer */
+    protected boolean gotChar;
+
+    /** An inner class to provide a read timeout for alarms. */
+    class IOTimer extends Thread {
+        String message;
+        long milliseconds;
+
+        /** Construct an IO Timer */
+        IOTimer(long sec, String mesg) {
+            milliseconds = 1000 * sec;
+            message = mesg;
+        }
+
+        public void run() {
+          try {
+            Thread.sleep(milliseconds);
+          } catch (InterruptedException e) {
+            // can't happen
+          }
+          /** Implement the timer */
+          if (!gotChar)
+            errStream.println("Timed out waiting for " + message);
+            die(1);
+        }
+    }
+
+    /*
+     * send a file to the remote
+     */
+    public boolean send(String tfile) throws IOException, InterruptedException
+    {
+        char checksum, index, blocknumber, errorcount;
+        byte character;
+        byte[] sector = new byte[SECSIZE];
+        int nbytes;
+        DataInputStream foo;
+
+        foo = new DataInputStream(new FileInputStream(tfile));
+        errStream.println( "file open, ready to send");
+        errorcount = 0;
+        blocknumber = 1;
+
+        // The C version uses "alarm()", a UNIX-only system call,
+        // to detect if the read times out. Here we do detect it
+        // by using a Thread, the IOTimer class defined above.
+        gotChar = false;
+        new IOTimer(SENTIMOUT, "NAK to start send").start();
+
+        do {
+            character = getchar();
+            gotChar = true;
+            if (character != NAK && errorcount < MAXERRORS)
+                ++errorcount;
+        } while (character != NAK && errorcount < MAXERRORS);
+
+        errStream.println( "transmission beginning");
+        if (errorcount == MAXERRORS) {
+            xerror();
+        }
+
+        while ((nbytes=inStream.read(sector))!=0) {
+            if (nbytes<SECSIZE)
+                sector[nbytes]=CPMEOF;
+            errorcount = 0;
+            while (errorcount < MAXERRORS) {
+                errStream.println( "{" + blocknumber + "} ");
+                putchar(SOH);   /* here is our header */
+                putchar(blocknumber);   /* the block number */
+                putchar(~blocknumber);  /* & its complement */
+                checksum = 0;
+                for (index = 0; index < SECSIZE; index++) {
+                    putchar(sector[index]);
+                    checksum += sector[index];
+                }
+                putchar(checksum);  /* tell our checksum */
+                if (getchar() != ACK)
+                    ++errorcount;
+                else
+                    break;
+            }
+            if (errorcount == MAXERRORS)
+                xerror();
+            ++blocknumber;
+        }
+        boolean isAck = false;
+        while (!isAck) {
+            putchar(EOT);
+            isAck = getchar() == ACK;
+        }
+        errStream.println( "Transmission complete.");
+        return true;
+    }
+
+    /*
+     * receive a file from the remote
+     */
+    public boolean receive(String tfile) throws IOException, InterruptedException
+    {
+        char checksum, index, blocknumber, errorcount;
+        byte character;
+        byte[] sector = new byte[SECSIZE];
+        DataOutputStream foo;
+
+        foo = new DataOutputStream(new FileOutputStream(tfile));
+
+        System.out.println("you have " + SLEEP + " seconds...");
+
+        /* wait for the user or remote to get his act together */
+        gotChar = false;
+        new IOTimer(SLEEP, "receive from remote").start(); 
+
+        errStream.println("Starting receive...");
+        putchar(NAK);
+        errorcount = 0;
+        blocknumber = 1;
+        rxLoop:
+        do { 
+            character = getchar();
+            gotChar = true;
+            if (character != EOT) {
+                try {
+                    byte not_ch;
+                    if (character != SOH) {
+                        errStream.println( "Not SOH");
+                        if (++errorcount < MAXERRORS)
+                            continue rxLoop;
+                        else
+                            xerror();
+                    }
+                    character = getchar();
+                    not_ch = (byte)(~getchar());
+                    errStream.println( "[" +  character + "] ");
+                    if (character != not_ch) {
+                        errStream.println( "Blockcounts not ~");
+                        ++errorcount;
+                        continue rxLoop;
+                    }
+                    if (character != blocknumber) {
+                        errStream.println( "Wrong blocknumber");
+                        ++errorcount;
+                        continue rxLoop;
+                    }
+                    checksum = 0;
+                    for (index = 0; index < SECSIZE; index++) {
+                        sector[index] = getchar();
+                        checksum += sector[index];
+                    }
+                    if (checksum != getchar()) {
+                        errStream.println( "Bad checksum");
+                        errorcount++;
+                        continue rxLoop;
+                    }
+                    putchar(ACK);
+                    blocknumber++;
+                    try {
+                        foo.write(sector);
+                    } catch (IOException e) {
+                        errStream.println("write failed, blocknumber " + blocknumber);
+                    }
+                } finally {
+                if (errorcount != 0)
+                    putchar(NAK);
+            }
+        }
+        } while (character != EOT);
+
+        foo.close();
+
+        putchar(ACK);   /* tell the other end we accepted his EOT   */
+        putchar(ACK);
+        putchar(ACK);
+
+        errStream.println("Receive Completed.");
+        return true;
+    }
+
+    protected byte getchar() throws IOException {
+        return (byte)inStream.read();
+    }
+
+    protected void putchar(int c) throws IOException {
+        outStream.write(c);
+    }
+
+    protected void xerror()
+    {
+        errStream.println("too many errors...aborting");
+        die(1);
+    }
+
+    protected void die(int how)
+    {
+        if (standalone)
+            System.exit(how);
+        else 
+          System.out.println(("Error code " + how));
+    }
+}

+ 105 - 0
src/main/java/com/tuoren/remote/YModem.java

@@ -0,0 +1,105 @@
+package com.tuoren.remote;
+
+import java.io.DataInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.RandomAccessFile;
+import java.util.Arrays;
+
+
+import cn.hutool.core.util.ArrayUtil;
+
+public class YModem {
+
+	protected static final byte    SOH = 1;    /* Start Of Header */
+	protected static final byte    STX  = 2;    /* Start Of Header */
+    protected static final byte    EOT = 4;    /* End Of Transmission */
+    protected static final byte    ACK = 6;    /* ACKnowlege */
+    protected static final byte    NAK = 0x15; /* Negative AcKnowlege */
+    
+    protected static final int SECSIZE_SOH = 128;      /* cpm sector, transmission block */
+    protected static final int SECSIZE_STX = 1024;      /* cpm sector, transmission block */
+    
+    
+    public static byte[] fileData(File fileF, byte blockNum) throws Exception {
+    	byte[] sector1 = new byte[3];
+    	byte[] sector2 = new byte[SECSIZE_STX];
+    	byte[] sector3 = new byte[2];
+    	try(FileInputStream files = new FileInputStream(fileF);
+    	    RandomAccessFile randFile = new RandomAccessFile(fileF,"rw");){
+    		randFile.seek( (blockNum-1)*SECSIZE_STX);
+        	int readlen =randFile.read(sector2);
+        	if(readlen <= 0) {
+        		sector1[0]=EOT;
+        		sector2 = new byte[SECSIZE_SOH];
+        	}else if(readlen <= SECSIZE_SOH) {
+        		sector1[0]= SOH;
+        		byte[] sector2_temp = new byte[SECSIZE_SOH];
+        		sector2_temp = Arrays.copyOfRange(sector2, 0, readlen);
+        		sector2 = sector2_temp;
+        		if(readlen<sector2.length) {
+        			Arrays.fill(sector2, readlen, sector2.length, (byte)0x1A);
+        		}
+        	}else if(readlen<=SECSIZE_STX){
+        		sector1[0]= STX;
+        		if(readlen<sector2.length) {
+        			Arrays.fill(sector2, readlen, sector2.length, (byte)0x1A);
+        		}
+        	}
+    	}
+    	
+    	
+    	sector1[1]=blockNum;
+    	sector1[2]=(byte) ~blockNum;
+    	
+    	short crc = ymodem_crc(sector2);
+    	sector3[0] = (byte) (crc >>8);
+    	sector3[1] = (byte) (crc);
+    	byte[] sector = ArrayUtil.addAll(sector1,sector2,sector3);
+    	
+    	return sector;
+    }
+    
+    public static byte[] fileInfo(File fileF, String fileName) throws Exception {
+    	byte[] sector1 = new byte[3];
+    	byte[] sector2 = new byte[SECSIZE_SOH];
+    	byte[] sector3 = new byte[2];
+    	if(!fileF.isFile()) {
+    		return null;
+    	}
+    	
+    	String len = String.valueOf(fileF.length());
+    	sector1[0]=SOH;
+    	sector1[1]=0;
+    	sector1[2]=(byte) 0xFF;
+    	ArrayUtil.copy(fileName.getBytes(), 0, sector2, 0, fileName.length());
+    	ArrayUtil.copy(len.getBytes(), 0, sector2, fileName.length()+1, len.length());
+    	short crc = ymodem_crc(sector2);
+    	sector3[0] = (byte) (crc >>8);
+    	sector3[1] = (byte) (crc);
+    	byte[] sector = ArrayUtil.addAll(sector1,sector2,sector3);
+    	return sector;
+    }
+    
+    static short ymodem_crc(byte[] data)
+    {
+    	int t=0;
+        short crc = 0;
+        while (t < data.length)
+        {
+            crc = (short) (crc ^ ((short) data[t++] << 8));
+            for (int i = 0; i < 8; i++)
+            {
+                if ((crc & 0x8000) != 0)
+                {
+                    crc = (short) ((crc << 1) ^ 0x1021);
+                }
+                else
+                {
+                    crc = (short) (crc << 1);
+                }
+            }
+        }
+        return crc;
+    }
+}