工作上,每次都怕让联调采集前置服务调试通信业务,上传记录,下载参数。去哪找流量卡?而且,有的机器型号是cdma,有的是gprs,有的机器通信模块还坏了。想到搞个串口通信方式吧,与电脑连接,在电脑上做个工具中专转tcp与采集通信。 提高下工作效率。且如果现场的机器,通信模块坏了,利用此工具,把车载机通过串口接到电脑上,主要电脑能联网,可以通过电脑网络把记录上传上去。且,通信日志,一目了然,便于分析
已经实现,平常工作中使用,再也不用到处找流量卡了。实现方式,改终端通信库,增加串口通信方式,做上位机小工具(nodejs),实现串口转tcp.
附:测试结果截图
另外,这个上位机工具也可以用python做个,实现起来都很快。nodejs和 python真是强大的利器!比用java和c++实现快多了!
附:nojs实现
s.js文件:
var SerialPort = require("serialport"); var fs = require('fs'); var net = require('net'); var iconv = require('iconv-lite'); var config = require('./config'); var HOST = config.ServerIP; var PORT = config.ServerPort; var COM = config.com; var client = new net.Socket(); SerialPort.list(function (err, ports) { //console.log(ports); ports.forEach(function(port) { console.log('available serial port:'+port.comName); //console.log(port.pnpId); //console.log(port.manufacturer); }); if(ports.length == 0){ console.log('Waring:there is no serial port!'); } }); console.log('TcpClient - Simple Communication Test Tool V1.00\n'); console.log('Author:yangyongzhen\n'); console.log('QQ:534117529\n'); console.log('Copyright (c) ****** 2015-2016\n'); console.log('Server ip:'+HOST+' port:'+PORT+'\n'); //nodejs中的console读入是异步的。下面的是同步读取console的代码。 // function readSyn() { // process.stdin.pause(); // var response = fs.readSync(process.stdin.fd, 1000, 0, "utf8"); // process.stdin.resume(); // return response[0].trim(); // } // console.log('Please enter serial port(1-9):'); // var cmd = readSyn(); // COM = 'COM'+cmd; var serialPort = new SerialPort(COM, { baudrate: 115200, autoOpen: false }); serialPort.open(function (error) { if ( error ) { console.log('failed to open serial: '+error); } else { console.log('open serial success,'+COM); } }); //console.log('end ,over!'); serialPort.on('data', function(data) { var hex = new Buffer(data); var str = iconv.decode(hex, 'gbk'); //debugger; if((str[0] == '-') && (str[1] == '>') && (str[2] == 'C') && (str[3] == 'o') ){ //console.log('\n->log1:\n' + str[2]+str[3]); // client.setTimeout(3000,function(){ // console.log('Connect timeout err!\n'); // } // ); client.connect(PORT, HOST, function() { console.log('->Connect:\n' + str); console.log('Connected to: ' + HOST + ':' + PORT); }); } else if((str[0] == 'T') && (str[1] == 'x')){ client.write(data.slice(3,data.length)); var hexstr = new Buffer(data); hexstr = hexstr.toString("hex",3,data.length); console.log('->Tx:\n' + hexstr); } else if((str[0] == '-') && (str[1] == '>') && (str[2] == 'D') && (str[3] == 'i') ){ console.log('->Disconnect:\n' + str); console.log('Client Connection closed'); client.destroy(); } else{ //var hexstr = new Buffer(str); //hexstr = hexstr.toString("hex",0,str.length); //console.log('\n->hexlog:\n' + hexstr); console.log('\n->log:\n' + str); } }); // 为客户端添加“data”事件处理函数 // data是服务器发回的数据 client.on('data', function(data) { var hexstr = new Buffer(data); hexstr = hexstr.toString("hex"); console.log('<-recv:\n' + hexstr); //console.log(data); //var str = iconv.decode(data, 'gbk'); serialPort.write(data, function(err, results) { // console.log('err ' + err); // console.log('results ' + results); }); }); // 为客户端添加“close”事件处理函数 client.on('close', function() { console.log('Remote Connection closed'); client.destroy(); }); //捕获异常,防止崩溃 process.on('uncaughtException', function (err) { //logger.error(err); console.log('Err:'+err); });
config.js文件:
var config = { com: "COM3", //串口号 ServerIP: "########", //服务器地址 ServerPort: ### //服务器端口 //ServerIP: "####", //服务器地址 // ServerPort: ### //服务器端口 // ServerIP: "192.168.60.36", //服务器地址 // ServerPort: 5037 //服务器端口 } module.exports = config;
附:python版的实现:
#coding=utf-8 #author:yangyongzhen #QQ:534117529 #'COMTest TcpServer - Simple Test Comm Tool 1.00' import sys,threading,time import serial import binascii,encodings import re import os from socket import * from struct import * #from myutil import * #name: myutil.py mylock = threading.RLock() Server_IP = '' Srever_Port = '' def print_hex1(s,prev='0x'): for c in s: print '%s%02x' %(prev,ord(c)), print def print_hex(s): for c in s: print '%02x' %(ord(c)), print def hexto_str(s): r ='' for c in s: r += '%02x' %(ord(c)) return r def strto_hex(s): r = s.decode('hex') return r #''代表服务器为localhost #在一个非保留端口号上进行监听 class ComThread: def __init__(self, Port=0): self.l_serial = None self.alive = False self.tcpalive = False self.waitEnd = None self.port = Port #TCP部分 #self.sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection = None #数据 self.snddata = '' self.rcvdata = '' def waiting(self): if not self.waitEnd is None: self.waitEnd.wait() def SetStopEvent(self): if not self.waitEnd is None: self.waitEnd.set() self.alive = False self.tcpalive = False self.stop() def start(self): self.l_serial = serial.Serial() self.l_serial.port = self.port self.l_serial.baudrate = 115200 self.l_serial.timeout = 2 #秒 self.l_serial.open() if self.l_serial.isOpen(): self.waitEnd = threading.Event() self.alive = True print 'open serial port %d ok!\n' %(self.port+1) print 'baudrate:115200 \n' self.thread_read = None self.thread_read = threading.Thread(target=self.FirstReader) self.thread_read.setDaemon(1) self.thread_read.start() self.thread_write = None self.thread_write = threading.Thread(target=self.FirstWriter) self.thread_write.setDaemon(1) self.thread_write.start() #TCP部分 self.tcpalive = True self.thread_TcpClient = None self.thread_TcpClient = threading.Thread(target=self.TcpClient) self.thread_TcpClient.setDaemon(1) self.thread_TcpClient.start() self.thread_TcpSend = None self.thread_TcpSend = threading.Thread(target=self.TcpSend) self.thread_TcpSend.setDaemon(1) self.thread_TcpSend.start() return True else: return False def FirstReader(self): while self.alive: # 接收间隔 time.sleep(0.1) try: data = '' n = self.l_serial.inWaiting() if n: data = data+self.l_serial.read(n) #for l in xrange(len(data)): #print '%02X' % ord(data[l]), # 发送数据 print u'->:' #print data[0],data[1] if ((data[0] == '-') and (data[1] == '>')): #print 'head:' print data #if((data[2] == 'D') and (data[3] == 'i')): #print 'close connection!' #self.tcpalive = False #self.connection.close() elif((data[0] == 'T') and (data[1] == 'x')): print_hex(data[3:]) mylock.acquire() self.snddata = data[3:] mylock.release() else: print data # 判断结束 except Exception, ex: print str(ex) self.waitEnd.set() self.alive = False def FirstWriter(self): while self.alive: # 接收间隔 time.sleep(0.1) try: #snddata = raw_input('\nenter data send:\n') if self.rcvdata!='': self.l_serial.write(self.rcvdata) print u'-<recv:' print_hex(self.rcvdata) mylock.acquire() self.rcvdata = '' mylock.release() #print_hex(snddata) except Exception, ex: print str(ex) self.waitEnd.set() self.alive = False def TcpClient(self): while self.tcpalive: # 接收间隔 time.sleep(0.1) self.connection = socket(AF_INET, SOCK_STREAM) self.connection.connect((Server_IP, int(Server_Port))) print 'Connect to Server OK!\n' print 'waiting... \n' self.snddata = '' self.rcvdata = '' #self.tcpalive = True while True: #读取客户端套接字的下一行 data = self.connection.recv(1024) #如果没有数量的话,那么跳出循环 if not data: break #发送一个回复至客户端 mylock.acquire() self.snddata = '' self.rcvdata = data mylock.release() #connection.send('Echo=>' + data) self.connection.close() self.waitEnd.set() self.tcpalive = False def TcpSend(self): while self.tcpalive: # 接收间隔 time.sleep(0.1) while True: time.sleep(0.1) try: if not self.connection is None: if self.snddata != '': self.connection.send(self.snddata) mylock.acquire() self.rcvdata = '' self.snddata = '' mylock.release() except Exception, ex: pass def stop(self): self.alive = False self.tcpalive = False self.thread_read.join() if self.l_serial.isOpen(): self.l_serial.close() #测试用部分 if __name__ == '__main__': print 'Serial to Tcp Communication Test Tool 1.01\n' print 'Author:yangyongzhen\n' print 'QQ:534117529\n' print 'Copyright (c) ##### 2016-2017.\n' Server_IP = raw_input('please enter ServerIP:') print 'Server_IP: %s' %(Server_IP) Server_Port = raw_input('please enter ServerPort:') print 'Server_Port: %s' %(Server_Port) com =raw_input('please enter com port(1-9):') rt = ComThread(int(com)-1) try: if rt.start(): rt.waiting() rt.stop() else: pass except Exception,se: print str(se) if rt.alive: rt.stop() os.system("pause") print '' print 'End OK .' del rt