| New file |
| | |
| | | # Reading Data From Serial Port With Python |
| | | |
| | | Bu projede STM32-F103C6TX2 mikrodenetleyicisinin USART portundan gelen mesaj verisinin Python aracılığı ile okunmasını sağlayan kod yazılmıştır. Bu mantığı kullanarak STM32 'nin USART portundan gelen veriyi okuyabilir ve bu gelen veriyi işleyebilirsiniz. Kodu çalıştırdığınızda açık olan Port 'ları görüntüleyebilir, Portu seçebilir ve Haberleşme Hızını(Boud Rate) girebilirsiniz. İlgili değerler girildikten sonra kod gelen veriyi okumaya başlayacaktır. |
| | | |
| | |  |
| | | |
| | | Gerekli Kütüphaneler: |
| | | pip install -i https://mirrors.aliyun.com/pypi/simple/ numpy==1.18.2 |
| | | |
| | | |
| | | -> import serial -- Komut satırına **pip install pyserial** yazarak bu kütüphaneyi kolayca kurabilirsiniz. |
| | | |
| | | -> import serial.tools.list_ports |
| | | |
| | | -> import time |
| | | |
| | | # STM32-F103C6TX Mikrodenetleyicisi İle Gönderilen Verinin Seri Monitörden Okunan Mesajı: |
| | |  |
| | | |
| | | # STM32-F103C6TX Mikrodenetleyicisi İle Gönderilen Verinin Python Kodundan Okunan Mesajı: |
| | |  |
| | | |
| | | Not: Gecikmeden kaynaklı TEST mesajı ardı ardına yazılıyor. STM32 geliştirme kartının yolladığı veri kodunda gecikme var ve aynı şekilde Python kodunda da bir gecikme var. Ufak bi düzenleme ile bu sorunun üstesinden gelinebilir. |
| | | |
| | | # STM32 Mikrodenetleyici İle Gönderilen Mesajın Kodu: (STM32CubeIDE yazılımı kullanılarak yazılmıştır.) |
| | |  |
| | | |
| | | # STM32-F103C6TX Mikrodenetleyicisinin USART Ayarı: (STM32CubeIDE yazılımı kullanılarak yazılmıştır.) |
| | |  |
| | | |
| | | # Faydalı olması dileğimle... İyi çalışmalar. |
| | | **İSMAİL SELÇUK ÇINAR / Electrical and Electronics & Aeronautical Engineering Student - 3rd Year** |
| | | |
| | | 📧 If you have any problems you can send me an email at cinarismailselcuk@gmail.com I will try to answer as soon as possible. |
| | | ### 🤝🏻 Contact Me & Social Media |
| | | |
| | | <p align="center"> |
| | | <a href="mailto:cinarismailselcuk@gmail.com"><img src="https://img.shields.io/badge/-Mail-D14836?style=flat&logo=Gmail&logoColor=white"/></a> |
| | | <a href="https://www.linkedin.com/in/ismailselcukcinar/"><img src="https://img.shields.io/badge/-LinkedIn-0077B5?style=flat&logo=Linkedin&logoColor=white%22"/</a> |
| | | <a href="https://instagram.com/ismail_selcuks"><img src="https://img.shields.io/badge/-Instagram_-E4405F?style=flat&logo=Instagram&logoColor=white"/></a> |
| | | <a href="https://twitter.com/ismail_selcuks"><img src="https://img.shields.io/badge/-Twitter_-1976c2?style=flat&logo=Twitter&logoColor=white"/></a> |
| | | <a href="https://www.youtube.com/channel/UCSt6rE5y6iklyFBpm-0xOYA"><img src="https://img.shields.io/badge/-YouTube_-c4302b?style=flat&logo=YouTube&logoColor=white"/></a> |
| | | <a href="https://discordapp.com/users/652243845790302239/"><img src="https://img.shields.io/badge/-Discord_-6A5ACD?style=flat&logo=Discord&logoColor=white"/></a> |
| | | </p> |
| New file |
| | |
| | | int sensorPin = A0; |
| | | int ledPin = 13; |
| | | int sensorValue = 0; |
| | | |
| | | void setup() { |
| | | Serial.begin(115200); |
| | | } |
| | | |
| | | int i = 0; |
| | | void loop() { |
| | | |
| | | sensorValue = analogRead(sensorPin); |
| | | Serial.print(i); |
| | | Serial.print(","); |
| | | Serial.print(sensorValue); |
| | | Serial.println(";"); |
| | | i = i + 1; |
| | | |
| | | delay(10); |
| | | } |
| New file |
| | |
| | | #!/usr/bin/python
|
| | | # -*-coding: utf-8 -*-
|
| | |
|
| | | import serial
|
| | | import threading
|
| | | import binascii
|
| | | from datetime import datetime
|
| | | import struct
|
| | | import csv
|
| | |
|
| | | class SerialPort:
|
| | | def __init__(self, port, buand):
|
| | | self.port = serial.Serial(port, buand)
|
| | | self.port.close()
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_open(self):
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_close(self):
|
| | | self.port.close()
|
| | |
|
| | | def send_data(self):
|
| | | self.port.write('')
|
| | |
|
| | | def read_data(self):
|
| | | global is_exit
|
| | | global data_bytes
|
| | | while not is_exit:
|
| | | count = self.port.inWaiting()
|
| | | if count > 0:
|
| | | rec_str = self.port.read(count)
|
| | | data_bytes=data_bytes+rec_str
|
| | | #print('当前数据接收总字节数:'+str(len(data_bytes))+' 本次接收字节数:'+str(len(rec_str)))
|
| | | #print(str(datetime.now()),':',binascii.b2a_hex(rec_str))
|
| | |
|
| | |
|
| | | serialPort = 'COM4' # 串口
|
| | | baudRate = 115200 # 波特率
|
| | | is_exit=False
|
| | | data_bytes=bytearray()
|
| | |
|
| | | if __name__ == '__main__':
|
| | | #打开串口
|
| | | mSerial = SerialPort(serialPort, baudRate)
|
| | |
|
| | | #文件写入操作
|
| | | filename=input('请输入文件名:比如test.csv:')
|
| | | dt=datetime.now()
|
| | | nowtime_str=dt.strftime('%y-%m-%d %I-%M-%S') #时间
|
| | | filename=nowtime_str+'_'+filename
|
| | | out=open(filename,'a+')
|
| | | csv_writer=csv.writer(out)
|
| | |
|
| | | #开始数据读取线程
|
| | | t1 = threading.Thread(target=mSerial.read_data)
|
| | | t1.setDaemon(True)
|
| | | t1.start()
|
| | | |
| | | while not is_exit:
|
| | | #主线程:对读取的串口数据进行处理
|
| | | data_len=len(data_bytes)
|
| | | i=0
|
| | | while(i<data_len-1):
|
| | | if(data_bytes[i]==0xFF and data_bytes[i+1]==0x5A):
|
| | | frame_code=data_bytes[i+2]
|
| | | frame_len=struct.unpack('<H',data_bytes[i+4:i+6])[0]
|
| | | frame_time=struct.unpack('<I',data_bytes[i+6:i+10])[0]
|
| | | print('帧类型:',frame_code,'帧长度:',frame_len,'时间戳:',frame_time)
|
| | | #print(frame_code,frame_len,frame_time)
|
| | | if frame_code==0x03: #判断帧类型
|
| | | #struct 解析数据帧
|
| | | accelerated_x,accelerated_y,accelerated_z,angular_x,angular_y,angular_z,tem,speed_x,speed_y,speed_z,\
|
| | | angular_v_x,angular_v_y,angular_v_z=struct.unpack('<fffffffffffff',data_bytes[i+12:i+12+frame_len-6])
|
| | | dt=datetime.now()
|
| | | nowtime_str=dt.strftime('%y-%m-%d %I:%M:%S') #时间
|
| | | loc_str=[nowtime_str,frame_time,accelerated_x,accelerated_y,accelerated_z,angular_x,angular_y,angular_z,tem,speed_x,speed_y,speed_z,\
|
| | | angular_v_x,angular_v_y,angular_v_z]
|
| | |
|
| | | #写入csv文件
|
| | | try:
|
| | | csv_writer.writerow(loc_str)
|
| | | except Exception as e:
|
| | | raise e |
| | | i=i+6+frame_len+3
|
| | | else:
|
| | | i=i+1
|
| | | data_bytes[0:i]=b'' |
| New file |
| | |
| | | import os
|
| | | import socket
|
| | |
|
| | | remote_IP='127.0.0.1'
|
| | | remote_port=5555
|
| | |
|
| | | remote_addr=(remote_IP,remote_port)
|
| | | socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
| | | socket.connect(remote_addr)
|
| | |
|
| | | while True:
|
| | | print('结束对话: (Q)')
|
| | | str=input('请输入对话内容: ')
|
| | | if str=='Q' or str=='q':
|
| | | str = str.encode('utf-8')
|
| | | socket.send(str)
|
| | | print('客户端结束对话')
|
| | | break
|
| | | else:
|
| | | str=str.encode('utf-8')
|
| | | socket.send(str)
|
| | |
|
| | | socket.close()
|
| | |
|
| New file |
| | |
| | | import os
|
| | | import socket
|
| | |
|
| | | remote_IP='127.0.0.1'
|
| | | remote_port=5555
|
| | |
|
| | | remote_addr=(remote_IP,remote_port)
|
| | | socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
| | |
|
| | | #绑定IP地址和端口号
|
| | | socket.bind(remote_addr)
|
| | | #监听来自客户端的信息
|
| | | socket.listen()
|
| | | print('正在监听来自客户端的信息......')
|
| | |
|
| | | #new_socket用于与客户机的对话
|
| | | new_socket,addr=socket.accept()
|
| | | while True:
|
| | | print('结束对话: (Q or q)')
|
| | | str=new_socket.recv(1024).decode('utf-8')
|
| | | if str=='Q' or str=='q':
|
| | | print('服务器结束对话')
|
| | | new_socket.close()
|
| | | break
|
| | | else:
|
| | | print(str)
|
| | |
|
| | |
|
| New file |
| | |
| | | import socketio
|
| | |
|
| | | def create_client():
|
| | | print('-----------start socketio.clent------------')
|
| | | sio = socketio.Client()
|
| | | |
| | | @sio.event
|
| | | def connect():
|
| | | print('connection established')
|
| | | sio.emit('client', {'msg': 'connect success'})
|
| | |
|
| | | @sio.on('serve')
|
| | | def on_message(data):
|
| | | print('client received a message!',data)
|
| | | # @sio.event
|
| | | # def message(data):
|
| | | # print('message received with ', data)
|
| | | # sio.emit('client', {'response': 'my response'})
|
| | |
|
| | | @sio.event
|
| | | def connect_error():
|
| | | print("The connection failed!")
|
| | | sio.disconnect()
|
| | |
|
| | | @sio.event
|
| | | def disconnect():
|
| | | print('disconnected from server')
|
| | | sio.disconnect()
|
| | | |
| | | sio.connect('http://localhost:5000')
|
| | | # sio.wait()
|
| | |
|
| | | #create_client() |
| New file |
| | |
| | | import this
|
| | | import socketio
|
| | |
|
| | |
|
| | | def sio(url,tparams):
|
| | | if not tparams:
|
| | | sio = socketio.Client()
|
| | | sio.connect(url)
|
| | | sio.on('connect', on_connect)
|
| | | sio.on('chat_message', revc_message)
|
| | | sio.on('disconnect', on_disconnect)
|
| | | sio.on('reconnect', on_reconnect)
|
| | | print(tparams)
|
| | | return sio
|
| | |
|
| | |
|
| | | def get_sessionid(userid, roomid):
|
| | | pass
|
| | |
|
| | | def on_connect(*args):
|
| | | # print(*args)
|
| | | print('connect')
|
| | |
|
| | | def on_disconnect():
|
| | | print('## disconnect ##')
|
| | |
|
| | | def on_reconnect():
|
| | | print('reconnect')
|
| | |
|
| | | def revc_message(*args): # 这个函数很重要 是socketio监听信息获取的函数, 这里面socketio会自行调用这个函数
|
| | | response_data_format = {}
|
| | | response_data = eval(args[0])
|
| | | print(response_data)
|
| | |
|
| | | def revc_message_mutil(*args): # 这个函数很重要 是socketio监听信息获取的函数, 这里面socketio会自行调用这个函数
|
| | | response_data_format = {}
|
| | | response_data = eval(args[0])
|
| | | print(response_data)
|
| | |
|
| | | def create_params(userid, roomid): # 这个方法类似requests库的封装方法 看底层貌似与requests的urllib3方法一样
|
| | | vsessionid, tsessionid = get_sessionid(userid, roomid)
|
| | | vparams = {
|
| | | 'sessionid': vsessionid,
|
| | | }
|
| | | tparams = {
|
| | | 'sessionid': tsessionid,
|
| | | }
|
| | | return vparams, tparams
|
| | |
|
| | | def sio(url=' xxx.net', vparams='', tparams=''):
|
| | | if not tparams:
|
| | | sio = socketio.Client()
|
| | | this.sio.connect('http://localhost:5000')
|
| | | print('socketio connect success!!!')
|
| | | sio.on('connect', on_connect)
|
| | | sio.on('chat_message', revc_message)
|
| | | sio.on('disconnect', on_disconnect)
|
| | | sio.on('reconnect', on_reconnect)
|
| | | return teacher, vsocketIO, tsocketIO
|
| | |
|
| | | def send_msg(domain_host, featurestype, sendmessage, userid, roomid, timer=1):
|
| | | teacher, vsocketIO, tsocketIO = sio(userid, roomid, host=domain_host)
|
| | | for i in range(timer):
|
| | | teacher.emit('chat_message', f'{sendmessage}', revc_message)
|
| | | vsocketIO.wait(seconds=1)
|
| | | tsocketIO.wait(seconds=1)
|
| | | return VIEWER_DATA, TEACHER_DATA
|
| | |
|
| | | def send_msg_mutil(domain_host, featurestype, sendmessage, userid, roomid, timer=1, vparams='', tparams=''):
|
| | | teacher, vsocketIO, tsocketIO = sio(userid, roomid, host=domain_host, vparams=vparams, tparams=tparams)
|
| | | for i in range(timer):
|
| | | teacher.emit('chat_message', f'{sendmessage}', revc_message_mutil)
|
| | | vsocketIO.wait(seconds=1)
|
| | | tsocketIO.wait(seconds=1)
|
| | | return VIEWER_DATA, TEACHER_DATA
|
| | |
|
| | | def clear_data():
|
| | | VIEWER_DATA.clear()
|
| | | TEACHER_DATA.clear()
|
| | |
|
| | | class Socketio_client():
|
| | |
|
| | | sio = socketio.Client()
|
| | |
|
| | | def create_client():
|
| | | print('-----------start socketio.clent------------')
|
| | | # sio = socketio.Client()
|
| | | this.sio.connect('http://localhost:5000')
|
| | | print('socketio connect success!!!')
|
| | |
|
| | | @this.sio.event
|
| | | def connect():
|
| | | print('connection established')
|
| | | this.sio.emit('client', {'msg': 'connect success'})
|
| | |
|
| | | @this.sio.on('serve')
|
| | | def on_message(data):
|
| | | print('client received a message!',data)
|
| | | # @sio.event
|
| | | # def message(data):
|
| | | # print('message received with ', data)
|
| | | # sio.emit('client', {'response': 'my response'})
|
| | |
|
| | | @this.sio.event
|
| | | def connect_error():
|
| | | print("The connection failed!")
|
| | | this.sio.disconnect()
|
| | |
|
| | | @this.sio.event
|
| | | def disconnect():
|
| | | print('disconnected from server')
|
| | | this.sio.disconnect()
|
| | | |
| | | # sio.wait()
|
| | |
|
| | | def sendmsg(msg): |
| | | this.sio.emit('client', {'msg': msg})
|
| | |
|
| | | def connect(): |
| | | this.sio.connect('http://localhost:5000')
|
| | | print('socketio connect success!!!')
|
| | |
|
| | |
|
| | | create_client() |
| New file |
| | |
| | | from socketIO_client import SocketIO, BaseNamespace
|
| | | import time
|
| | | import requests
|
| | | import logging
|
| | | # 这里引入四个变量 放在flask里面起一个单独文件防止有坑!
|
| | | from app.test_report.constant import VIEWER_DATA, TEACHER_DATA, VIEWER_DATA_MUTIL, TEACHER_DATA_MUTIL
|
| | | logging.getLogger('socketIO-client').setLevel(logging.DEBUG)
|
| | | logging.basicConfig() # 调试时候可以自定义日志
|
| | |
|
| | | class TeacherNamespace(BaseNamespace):
|
| | | def on_teacher_response(self, *args):
|
| | | print('qqq', args, type(args))
|
| | |
|
| | | class ViewerNamespace(BaseNamespace):
|
| | | def on_viewer_response(self, *args):
|
| | | print(args, type(args))
|
| | |
|
| | | def get_sessionid(userid, roomid):
|
| | | pass
|
| | |
|
| | | def on_connect(*args):
|
| | | # print(*args)
|
| | | print('connect')
|
| | |
|
| | | def on_disconnect():
|
| | | print('## disconnect ##')
|
| | |
|
| | | def on_reconnect():
|
| | | print('reconnect')
|
| | |
|
| | | def revc_message(*args): # 这个函数很重要 是socketio监听信息获取的函数, 这里面socketio会自行调用这个函数
|
| | | response_data_format = {}
|
| | | response_data = eval(args[0])
|
| | | print(response_data)
|
| | |
|
| | | def revc_message_mutil(*args): # 这个函数很重要 是socketio监听信息获取的函数, 这里面socketio会自行调用这个函数
|
| | | response_data_format = {}
|
| | | response_data = eval(args[0])
|
| | | print(response_data)
|
| | |
|
| | | def create_params(userid, roomid): # 这个方法类似requests库的封装方法 看底层貌似与requests的urllib3方法一样
|
| | | vsessionid, tsessionid = get_sessionid(userid, roomid)
|
| | | vparams = {
|
| | | 'sessionid': vsessionid,
|
| | | }
|
| | | tparams = {
|
| | | 'sessionid': tsessionid,
|
| | | }
|
| | | return vparams, tparams
|
| | |
|
| | | def sio(userid, roomid, host=' xxx.net', vparams='', tparams=''):
|
| | | if not vparams and not tparams:
|
| | | vparams, tparams = create_params(userid, roomid)
|
| | | vsocketIO = SocketIO(host, params=vparams)
|
| | | tsocketIO = SocketIO(host, params=tparams)
|
| | | viewer = vsocketIO.define(ViewerNamespace, path=f'/asjbfasbfk') # 这个path类似于信道的路径 很重要
|
| | | teacher = tsocketIO.define(TeacherNamespace, path=f'/asjbfasbfk') # 这个path类似于信道的路径 很重要
|
| | | viewer.on('connect', on_connect)
|
| | | viewer.on('chat_message', revc_message)
|
| | | viewer.on('disconnect', on_disconnect)
|
| | | viewer.on('reconnect', on_reconnect)
|
| | | teacher.on('connect', on_connect)
|
| | | teacher.on('chat_message', revc_message)
|
| | | teacher.on('disconnect', on_disconnect)
|
| | | teacher.on('reconnect', on_reconnect)
|
| | | return teacher, vsocketIO, tsocketIO
|
| | |
|
| | | def send_msg(domain_host, featurestype, sendmessage, userid, roomid, timer=1):
|
| | | teacher, vsocketIO, tsocketIO = sio(userid, roomid, host=domain_host)
|
| | | for i in range(timer):
|
| | | teacher.emit('chat_message', f'{sendmessage}', revc_message)
|
| | | vsocketIO.wait(seconds=1)
|
| | | tsocketIO.wait(seconds=1)
|
| | | return VIEWER_DATA, TEACHER_DATA
|
| | |
|
| | | def send_msg_mutil(domain_host, featurestype, sendmessage, userid, roomid, timer=1, vparams='', tparams=''):
|
| | | teacher, vsocketIO, tsocketIO = sio(userid, roomid, host=domain_host, vparams=vparams, tparams=tparams)
|
| | | for i in range(timer):
|
| | | teacher.emit('chat_message', f'{sendmessage}', revc_message_mutil)
|
| | | vsocketIO.wait(seconds=1)
|
| | | tsocketIO.wait(seconds=1)
|
| | | return VIEWER_DATA, TEACHER_DATA
|
| | |
|
| | | def clear_data():
|
| | | VIEWER_DATA.clear()
|
| | | TEACHER_DATA.clear()
|
| | | if __name__ == '__main__':
|
| | | s = time.time()
|
| | | print(send_msg('xxxx.net', 1, '发送信息1', '7848DB3F76g7ts7057F', 'E301DFFFCDDAG7S79GY9A01307461'))
|
| | | print(time.time()-s)
|
| | | clear_data()
|
| New file |
| | |
| | | #coded by 伊玛目的门徒
|
| | | #coding=utf-8
|
| | | from wordpress_xmlrpc import Client, WordPressPost
|
| | | from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
|
| | | from wordpress_xmlrpc.methods.users import GetUserInfo
|
| | | import time
|
| | | import requests
|
| | | from bs4 import BeautifulSoup
|
| | | import re
|
| | | |
| | | |
| | | from concurrent.futures import ThreadPoolExecutor
|
| | | |
| | | |
| | | start = time.clock() # 计时-开始
|
| | | urllist=[]
|
| | | titlelist=[]
|
| | | |
| | | header={'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.XXXX.XXX Safari/537.36'}
|
| | | |
| | | |
| | | |
| | | def do(i):
|
| | | try:
|
| | | |
| | | cd=[]
|
| | | html=requests.get('http://futures.hexun.com/domestic/index-'+str(i)+'.html',headers=header)
|
| | | |
| | | html.encoding='gbk'
|
| | | |
| | | Soup = BeautifulSoup(html.text, "lxml")
|
| | | #ab=Soup.select('li a[target="_blank"]')
|
| | | ab=Soup.select('div.temp01 ul li a[target="_blank"]')
|
| | | |
| | | for x in range(len(ab)):
|
| | | if (x % 2) == 1:
|
| | | cd.append (ab[x])
|
| | | |
| | | #print ('--------------')
|
| | | |
| | | pattern = re.compile(r'<a href="(.*?)" target="_blank">',re.S) # 查找数字
|
| | | result1 = pattern.findall(str(cd))
|
| | | pattern2 = re.compile(r'target="_blank">(.*?)</a>',re.S)
|
| | | result2 = pattern2.findall(str(cd))
|
| | | #print (result1)
|
| | | urllist.extend(result1)
|
| | | #print (result2)
|
| | | titlelist.extend(result2)
|
| | | |
| | | |
| | | list1.remove(i)
|
| | | |
| | | |
| | | |
| | | except:
|
| | | pass
|
| | | |
| | | |
| | | |
| | | # 多线程
|
| | | def multithreading():
|
| | | sum=0
|
| | | |
| | | while len(list1)>0:
|
| | | with ThreadPoolExecutor(max_workers=10) as executor:
|
| | | for result in executor.map(do, list1):
|
| | | sum+=1
|
| | | |
| | | return sum
|
| | | |
| | | |
| | | |
| | | |
| | | #list1=list(range(1,393,1))
|
| | | list1=list(range(392,393,1))
|
| | | |
| | | sum=multithreading()
|
| | | print ('还剩下{}页'.format(list1))
|
| | | |
| | | |
| | | |
| | | end = time.clock() # 计时-结束
|
| | | print (("爬取完成 用时:"))
|
| | | print ((end - start))
|
| | | |
| | | |
| | | print ('总爬取 %d 页 '%(sum))
|
| | | |
| | | while None in titlelist:
|
| | | titlelist.remove(None)
|
| | | |
| | | while None in urllist:
|
| | | urllist.remove(None)
|
| | | |
| | | #print (titlelist)
|
| | | |
| | | #print (urllist)
|
| | | |
| | | |
| | | '''
|
| | | #可作为TXT输出
|
| | | with open("test.txt","w") as f:
|
| | | for thing in urllist:
|
| | | f.write(thing)
|
| | | f.write('\r\n')
|
| | | '''
|
| | | |
| | | |
| | | |
| | | |
| | | |
| | | def getcontent(url,j):
|
| | | try:
|
| | | print (listj)
|
| | | |
| | | html=requests.get(url,headers=header)
|
| | | |
| | | html.encoding='gbk'
|
| | | |
| | | Soup = BeautifulSoup(html.text, "lxml")
|
| | | |
| | | con=Soup.select('div.art_contextBox ')
|
| | | |
| | | cont=''
|
| | | for y in con:
|
| | | #print (type(str(y)))
|
| | | cont=cont+str(y)
|
| | | |
| | | #print (cont)
|
| | | #print (j)
|
| | | listj.remove(j)
|
| | | #print ('****')
|
| | | #print (listj)
|
| | | return (cont)
|
| | | |
| | | |
| | | |
| | | |
| | | |
| | | except:
|
| | | pass
|
| | | |
| | | |
| | | def wpsend(title,content):
|
| | | |
| | | wp = Client('http://www.6324.xyz/xmlrpc.php', '你的用户名', '你的密码')
|
| | | |
| | | #print (content)
|
| | | post = WordPressPost()
|
| | | post.title = title
|
| | | #post.content = " ''' "+ content +" ''' "
|
| | | post.content = " "+ str(content) +" "
|
| | | post.post_status = 'publish'
|
| | | post.terms_names = {
|
| | | 'post_tag': ['操盘策略'],
|
| | | 'category': [ '期货']
|
| | | }
|
| | | wp.call(NewPost(post))
|
| | | localtime = time.localtime(time.time())
|
| | | print ('文档已上传,执行时间 {}'.format(time.strftime("%Y-%m-%d %H:%M:%S",localtime)))
|
| | | |
| | | |
| | | def work(j):
|
| | | |
| | | url=urllist[j]
|
| | | title=titlelist[j]
|
| | | |
| | | cont=getcontent(url,j)
|
| | | wpsend(title,cont)
|
| | | |
| | | print ('成功完成任务采集任务第 {}号任务'.format(j))
|
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | # 多线程
|
| | | def multithreading_con():
|
| | | sum=0
|
| | | global listj
|
| | | listj=list(range(len(urllist)))
|
| | | #print (type(listj))
|
| | | #print (listj)
|
| | | |
| | | while len(listj)>0:
|
| | | with ThreadPoolExecutor(max_workers=5) as executor:
|
| | | for result in executor.map(work,listj ):
|
| | | sum+=1
|
| | | |
| | | return sum
|
| | | |
| | | |
| | | |
| | | multithreading_con()
|
| | | |
| | | end = time.clock() # 计时-结束
|
| | | print ("全部上传完成 用时:")
|
| | | |
| | | print ((end - start)) |
| New file |
| | |
| | | from http.client import SWITCHING_PROTOCOLS
|
| | | from flask import Flask, request, redirect, url_for, render_template
|
| | |
|
| | |
|
| | | class switch_case(object):
|
| | | def case_to_function(self, case):
|
| | | fun_name = "case_fun_" + str(case)
|
| | | method = getattr(self, fun_name, self.case_fun_other)
|
| | | return method
|
| | | def case_fun_start(self, msg):
|
| | | print(msg)
|
| | | def case_fun_stop(self, msg):
|
| | | print(msg)
|
| | | def case_fun_other(self, msg):
|
| | | print(msg)
|
| | |
|
| | | # 创建Flask服务
|
| | | app = Flask(__name__)
|
| | |
|
| | | # 访问URL:http://127.0.0.1:8080/home/hello
|
| | | # 返回结果:{"data":"welcome to use flask.","msg":"hello"}
|
| | | @app.route('/home/<name>')
|
| | | def home(name):
|
| | | cls.case_to_function(name)("case_fun_"+name+" is called")
|
| | | return {
|
| | | "msg": name,
|
| | | "data": "welcome to use flask."
|
| | | }
|
| | |
|
| | | if __name__ == "__main__":
|
| | | cls = switch_case()
|
| | | # 启动Flask服务,指定主机IP和端口
|
| | | app.run(host='127.0.0.1', port=8080) |
| New file |
| | |
| | | from serialToExcel import SerialToExcel |
| | | |
| | | serialToExcel = SerialToExcel("COM4",115200) |
| | | |
| | | columnas = ["Nro Lectura","Valor"] |
| | | |
| | | serialToExcel.setColumns(["Nro Lectura","Valor"]) |
| | | serialToExcel.setRecordsNumber(10) |
| | | serialToExcel.readPort() |
| | | |
| | | serialToExcel.writeFile("archivo1.xls") |
| New file |
| | |
| | | @echo off
|
| | | set local enabledelayedexpansion
|
| | | python serial_reader_1.py |
| New file |
| | |
| | | @echo off
|
| | | set local enabledelayedexpansion
|
| | | python serial_reader_2.py |
| New file |
| | |
| | | import serial |
| | | import xlwt |
| | | from datetime import datetime |
| | | |
| | | class SerialToExcel: |
| | | |
| | | def __init__(self,port,speed): |
| | | |
| | | self.port = port |
| | | self.speed = speed |
| | | |
| | | self.wb = xlwt.Workbook() |
| | | self.ws = self.wb.add_sheet("Data from Serial",cell_overwrite_ok=True) |
| | | self.ws.write(0, 0, "Data from Serial") |
| | | self.columns = ["Date Time"] |
| | | self.number = 100 |
| | | |
| | | |
| | | def setColumns(self,col): |
| | | self.columns.extend(col) |
| | | |
| | | def setRecordsNumber(self,number): |
| | | self.number = number |
| | | |
| | | def readPort(self): |
| | | ser = serial.Serial(self.port, self.speed, timeout=1) |
| | | c = 0 |
| | | for col in self.columns: |
| | | self.ws.write(1, c, col) |
| | | c = c + 1 |
| | | self.fila = 2 |
| | | |
| | | i = 0 |
| | | while(i<self.number): |
| | | line = str(ser.readline()) |
| | | if(len(line) > 0): |
| | | now = datetime.now() |
| | | date_time = now.strftime("%m/%d/%Y, %H:%M:%S") |
| | | print(date_time,line) |
| | | if(line.find(",")): |
| | | c = 1 |
| | | self.ws.write(self.fila, 0, date_time) |
| | | columnas = line.split(",") |
| | | for col in columnas: |
| | | self.ws.write(self.fila, c, col) |
| | | c = c + 1 |
| | | |
| | | i = i + 1 |
| | | self.fila = self.fila + 1 |
| | | |
| | | def writeFile(self,archivo): |
| | | self.wb.save(archivo) |
| | | |
| | | |
| New file |
| | |
| | | #!/usr/bin/python
|
| | | # -*-coding: utf-8 -*-
|
| | |
|
| | | from asyncio import sleep
|
| | | from collections import deque
|
| | | from pickle import FALSE
|
| | | import serial
|
| | | import threading
|
| | | from datetime import datetime
|
| | | import socketio
|
| | | import time
|
| | | import csv
|
| | |
|
| | |
|
| | | class SerialPort:
|
| | | def __init__(self, port, buand):
|
| | | self.port = serial.Serial(port, buand)
|
| | | self.port.close()
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_open(self):
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_close(self):
|
| | | self.port.close()
|
| | |
|
| | | def send_data(self):
|
| | | self.port.write('')
|
| | |
|
| | | def read_data(self):
|
| | | global is_exit
|
| | | global data_bytes,data_list
|
| | | while True: |
| | | while not is_exit:
|
| | | count = self.port.inWaiting()
|
| | | if count > 0:
|
| | | rec_str = self.port.read(count)
|
| | | data_list.append(rec_str)
|
| | | # data_bytes = data_bytes+rec_str
|
| | | # print(str(datetime.now()),':','当前数据接收总字节数:'+str(len(data_bytes))+' 本次接收字节数:'+str(len(rec_str)))
|
| | |
|
| | | def write_data(self): |
| | | global data_L,L,index_,is_exit,data_list,send_list
|
| | | newData = False
|
| | | while True:
|
| | | while not is_exit:
|
| | | # i,is_60_index,is_65_index,is_68_index = 0
|
| | | # is_first = False
|
| | | if len(data_list)<1: |
| | | continue
|
| | | # 写入csv文件
|
| | | text_ = data_list.popleft()
|
| | | for each in text_:
|
| | | send_list.append(int(each))
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%Y-%m-%d %H:%M:%S.%f') # 时间
|
| | | while len(send_list)>0:
|
| | | x = send_list.popleft()
|
| | | if(x == 60):
|
| | | if len(send_list)<3:
|
| | | send_list.appendleft(x)
|
| | | break
|
| | | else:
|
| | | y = send_list.popleft()
|
| | | z = send_list.popleft()
|
| | | m = send_list.popleft()
|
| | | if (x == 60 and y == 170 and z == 85):
|
| | | if(m == 65):
|
| | | index_ = 0
|
| | | data_L=[[],[],[],[]]
|
| | | if(m == 66):
|
| | | index_ = 1
|
| | | data_L[index_] = []
|
| | | if(m == 67):
|
| | | index_ = 2
|
| | | data_L[index_] = []
|
| | | if(m == 68):
|
| | | index_ = 3
|
| | | data_L[index_] = []
|
| | | data_L[index_].append(x) |
| | | data_L[index_].append(y)
|
| | | data_L[index_].append(z)
|
| | | data_L[index_].append(m)
|
| | | else:
|
| | | data_L[index_].append(x)
|
| | | send_list.appendleft(m)
|
| | | send_list.appendleft(z)
|
| | | send_list.appendleft(y)
|
| | | else:
|
| | | data_L[index_].append(x)
|
| | | # 发送socket消息
|
| | | if(len(data_L[3])>0 and len(data_L[3])==len(data_L[2])):
|
| | | if sio.connected:
|
| | | sio.emit("msg",{"time": nowtime_str,"serialport":serialPort,"data":data_L})
|
| | | data_L=[[],[],[],[]] |
| | | |
| | | # socket_.send("msg",{"data":text_})
|
| | | # try:
|
| | | # # writedata ='{}'.format(data_list.popleft())
|
| | | # # Note.write(writedata.encode('hex'))
|
| | | # csv_writer.writerow(text_)
|
| | | # except Exception as e:
|
| | | # raise e
|
| | |
|
| | | def test(self):
|
| | | global is_exit
|
| | | while True: |
| | | sleep(10)
|
| | | is_exit = False
|
| | | sleep(10)
|
| | | is_exit = True
|
| | |
|
| | | serialPort = '/dev/tty.usbserial-14130' # 串口
|
| | | baudRate = 115200 # 波特率
|
| | | socketurl_ = "http://192.168.0.30:3001"
|
| | | is_exit = False
|
| | | data_bytes = bytearray()
|
| | | data_list = deque()
|
| | | send_list = deque()
|
| | | L = []
|
| | | data_L = [[],[],[],[]]
|
| | | index_ = 0 #第 A/B/C/D 组数据
|
| | | # sio = socketio.Client(logger=True, engineio_logger=True)
|
| | | sio = socketio.Client()
|
| | | start_timer = None
|
| | | csv_writer = None
|
| | | is_data_header = False
|
| | |
|
| | | @sio.event
|
| | | def connect():
|
| | | print('connected to server')
|
| | |
|
| | |
|
| | | @sio.event
|
| | | def pong_from_server():
|
| | | global start_timer
|
| | | latency = time.time() - start_timer
|
| | | print('latency is {0:.2f} ms'.format(latency * 1000))
|
| | | sio.sleep(1)
|
| | | if sio.connected:
|
| | | print(' reconnected')
|
| | |
|
| | |
|
| | | @sio.on('command_msg')
|
| | | def command_msg(data):
|
| | | global is_exit
|
| | | if data['command'] == 'stop':
|
| | | is_exit = True
|
| | | if data['command'] == 'start':
|
| | | is_exit = False
|
| | |
|
| | | if __name__ == '__main__':
|
| | | # serialPort = input("请输入串口字符串")
|
| | | # 打开串口
|
| | | mSerial = SerialPort(serialPort, baudRate)
|
| | |
|
| | | # 文件写入操作
|
| | | # filename = input('请输入文件名:比如test.csv:')
|
| | | filename = 'test.csv'
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%y-%m-%d %I-%M-%S') # 时间
|
| | | # filename = nowtime_str+'_'+filename
|
| | | # out = open(filename, 'w')
|
| | | # csv_writer = csv.writer(out)
|
| | | # txt写入
|
| | | # Note=open(nowtime_str+'_test.txt',mode='w')
|
| | |
|
| | | # 开始数据读取线程
|
| | | t1 = threading.Thread(target=mSerial.read_data)
|
| | | t1.setDaemon(True)
|
| | | t1.start()
|
| | |
|
| | | # 连接socketio
|
| | | sio.connect(socketurl_)
|
| | | print('-----------------------------000000000000000---------------------------------')
|
| | | # 开始写数据
|
| | | t3 = threading.Thread(target=mSerial.write_data())
|
| | | t3.setDaemon(True)
|
| | | t3.start()
|
| | | print('-----------------------------11111111111111---------------------------------')
|
| | | |
| | | # sio.wait() #sio事件处理
|
| | | t4 = threading.Thread(target=sio.wait())
|
| | | t4.setDaemon(True)
|
| | | t4.start()
|
| | |
|
| | | # 连接socket
|
| | | # remote_IP='192.168.0.225'
|
| | | # remote_port=5000
|
| | | # remote_addr=(remote_IP,remote_port)
|
| | | # socket_=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
| | | # socket_.connect(remote_addr) |
| New file |
| | |
| | | #!/usr/bin/python
|
| | | # -*-coding: utf-8 -*-
|
| | |
|
| | | from asyncio import sleep
|
| | | from collections import deque
|
| | | from pickle import FALSE
|
| | | import serial
|
| | | import threading
|
| | | from datetime import datetime
|
| | | import socketio
|
| | | import time
|
| | | import csv
|
| | |
|
| | |
|
| | | class SerialPort:
|
| | | def __init__(self, port, buand):
|
| | | self.port = serial.Serial(port, buand)
|
| | | self.port.close()
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_open(self):
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_close(self):
|
| | | self.port.close()
|
| | |
|
| | | def send_data(self):
|
| | | self.port.write('')
|
| | |
|
| | | def read_data(self):
|
| | | global is_exit
|
| | | global data_bytes,data_list
|
| | | while True: |
| | | while not is_exit:
|
| | | count = self.port.inWaiting()
|
| | | if count > 0:
|
| | | rec_str = self.port.read(count)
|
| | | data_list.append(rec_str)
|
| | | # data_bytes = data_bytes+rec_str
|
| | | # print(str(datetime.now()),':','当前数据接收总字节数:'+str(len(data_bytes))+' 本次接收字节数:'+str(len(rec_str)))
|
| | |
|
| | | def write_data(self): |
| | | global data_L,L,index_,is_exit,data_list,send_list
|
| | | newData = False
|
| | | while True:
|
| | | while not is_exit:
|
| | | # i,is_60_index,is_65_index,is_68_index = 0
|
| | | # is_first = False
|
| | | if len(data_list)<1: |
| | | continue
|
| | | # 写入csv文件
|
| | | text_ = data_list.popleft()
|
| | | for each in text_:
|
| | | send_list.append(int(each))
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%Y-%m-%d %H:%M:%S.%f') # 时间
|
| | | while len(send_list)>0:
|
| | | x = send_list.popleft()
|
| | | if(x == 60):
|
| | | if len(send_list)<3:
|
| | | send_list.appendleft(x)
|
| | | break
|
| | | else:
|
| | | y = send_list.popleft()
|
| | | z = send_list.popleft()
|
| | | m = send_list.popleft()
|
| | | if (x == 60 and y == 170 and z == 85):
|
| | | if(m == 65):
|
| | | index_ = 0
|
| | | data_L=[[],[],[],[]]
|
| | | if(m == 66):
|
| | | index_ = 1
|
| | | data_L[index_] = []
|
| | | if(m == 67):
|
| | | index_ = 2
|
| | | data_L[index_] = []
|
| | | if(m == 68):
|
| | | index_ = 3
|
| | | data_L[index_] = []
|
| | | data_L[index_].append(x) |
| | | data_L[index_].append(y)
|
| | | data_L[index_].append(z)
|
| | | data_L[index_].append(m)
|
| | | else:
|
| | | data_L[index_].append(x)
|
| | | send_list.appendleft(m)
|
| | | send_list.appendleft(z)
|
| | | send_list.appendleft(y)
|
| | | else:
|
| | | data_L[index_].append(x)
|
| | | # 发送socket消息
|
| | | if(len(data_L[3])>0 and len(data_L[3])==len(data_L[2])):
|
| | | if sio.connected:
|
| | | sio.emit("msg",{"time": nowtime_str,"serialport":serialPort,"data":data_L})
|
| | | data_L=[[],[],[],[]] |
| | | |
| | | # socket_.send("msg",{"data":text_})
|
| | | # try:
|
| | | # # writedata ='{}'.format(data_list.popleft())
|
| | | # # Note.write(writedata.encode('hex'))
|
| | | # csv_writer.writerow(text_)
|
| | | # except Exception as e:
|
| | | # raise e
|
| | |
|
| | | def test(self):
|
| | | global is_exit
|
| | | while True: |
| | | sleep(10)
|
| | | is_exit = False
|
| | | sleep(10)
|
| | | is_exit = True
|
| | |
|
| | | serialPort = '/dev/tty.usbserial-14110' # 串口
|
| | | baudRate = 115200 # 波特率
|
| | | socketurl_ = "http://192.168.0.30:3001"
|
| | | is_exit = False
|
| | | data_bytes = bytearray()
|
| | | data_list = deque()
|
| | | send_list = deque()
|
| | | L = []
|
| | | data_L = [[],[],[],[]]
|
| | | index_ = 0 #第 A/B/C/D 组数据
|
| | | # sio = socketio.Client(logger=True, engineio_logger=True)
|
| | | sio = socketio.Client()
|
| | | start_timer = None
|
| | | csv_writer = None
|
| | | is_data_header = False
|
| | |
|
| | | @sio.event
|
| | | def connect():
|
| | | print('connected to server')
|
| | |
|
| | |
|
| | | @sio.event
|
| | | def pong_from_server():
|
| | | global start_timer
|
| | | latency = time.time() - start_timer
|
| | | print('latency is {0:.2f} ms'.format(latency * 1000))
|
| | | sio.sleep(1)
|
| | | if sio.connected:
|
| | | print(' reconnected')
|
| | |
|
| | |
|
| | | @sio.on('command_msg')
|
| | | def command_msg(data):
|
| | | global is_exit
|
| | | if data['command'] == 'stop':
|
| | | is_exit = True
|
| | | if data['command'] == 'start':
|
| | | is_exit = False
|
| | |
|
| | | if __name__ == '__main__':
|
| | | # serialPort = input("请输入串口字符串")
|
| | | # 打开串口
|
| | | mSerial = SerialPort(serialPort, baudRate)
|
| | |
|
| | | # 文件写入操作
|
| | | # filename = input('请输入文件名:比如test.csv:')
|
| | | filename = 'test.csv'
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%y-%m-%d %I-%M-%S') # 时间
|
| | | # filename = nowtime_str+'_'+filename
|
| | | # out = open(filename, 'w')
|
| | | # csv_writer = csv.writer(out)
|
| | | # txt写入
|
| | | # Note=open(nowtime_str+'_test.txt',mode='w')
|
| | |
|
| | | # 开始数据读取线程
|
| | | t1 = threading.Thread(target=mSerial.read_data)
|
| | | t1.setDaemon(True)
|
| | | t1.start()
|
| | |
|
| | | # 连接socketio
|
| | | sio.connect(socketurl_)
|
| | | print('-----------------------------000000000000000---------------------------------')
|
| | | # 开始写数据
|
| | | t3 = threading.Thread(target=mSerial.write_data())
|
| | | t3.setDaemon(True)
|
| | | t3.start()
|
| | | print('-----------------------------11111111111111---------------------------------')
|
| | | |
| | | # sio.wait() #sio事件处理
|
| | | t4 = threading.Thread(target=sio.wait())
|
| | | t4.setDaemon(True)
|
| | | t4.start()
|
| | |
|
| | | # 连接socket
|
| | | # remote_IP='192.168.0.225'
|
| | | # remote_port=5000
|
| | | # remote_addr=(remote_IP,remote_port)
|
| | | # socket_=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
| | | # socket_.connect(remote_addr) |
| New file |
| | |
| | | #!/usr/bin/python
|
| | | # -*-coding: utf-8 -*-
|
| | |
|
| | | from asyncio import sleep
|
| | | from collections import deque
|
| | | from pickle import FALSE
|
| | | from socketio_client import connect_, sio, send_msg
|
| | | import sys
|
| | | import serial
|
| | | import threading
|
| | | import binascii
|
| | | from datetime import datetime
|
| | | import socketio
|
| | | import time
|
| | | import csv
|
| | | import socket
|
| | | # import numpy
|
| | |
|
| | |
|
| | | class SerialPort:
|
| | | def __init__(self, port, buand):
|
| | | self.port = serial.Serial(port, buand)
|
| | | self.port.close()
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_open(self):
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_close(self):
|
| | | self.port.close()
|
| | |
|
| | | def send_data(self):
|
| | | self.port.write('')
|
| | |
|
| | | def read_data(self):
|
| | | global is_exit
|
| | | global data_bytes,data_list
|
| | | while True: |
| | | while not is_exit:
|
| | | count = self.port.inWaiting()
|
| | | if count > 0:
|
| | | rec_str = self.port.read(count)
|
| | | data_list.append(rec_str)
|
| | | # data_bytes = data_bytes+rec_str
|
| | | # print(str(datetime.now()),':','当前数据接收总字节数:'+str(len(data_bytes))+' 本次接收字节数:'+str(len(rec_str)))
|
| | |
|
| | | def write_data(self): |
| | | global is_exit,data_bytes,data_list,csv_writer,L,sio,start_timer,is_data_header,send_list
|
| | | newData = False
|
| | | while True:
|
| | | while not is_exit:
|
| | | i,is_60_index,is_65_index,is_68_index = 0
|
| | | is_first = False
|
| | | # 主线程:对读取的串口数据进行处理
|
| | | if len(data_list)<1: |
| | | continue
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%y-%m-%d %I:%M:%S') # 时间
|
| | | # 写入csv文件
|
| | | text_ = data_list.popleft()
|
| | | print(type(text_))
|
| | | # if len(send_list) < 1:
|
| | | # continue
|
| | | for each in text_:
|
| | | L.append(int(each))
|
| | | for i in range(len(L)):
|
| | | if(L[i] == 60 and L[i+1]==170 and L[i+2] ==85 and not is_first):
|
| | | is_first = True
|
| | | is_60_first = i |
| | | match (L[i+3]):
|
| | | case 65:
|
| | | is_65_index = i
|
| | | case 66:
|
| | | is_68_index = 0
|
| | | case 67:
|
| | | is_68_index = 0
|
| | | case 68:
|
| | | is_68_index = i
|
| | | |
| | | # print('---------------------------start---------------------------------')
|
| | | # print(L)
|
| | | try:
|
| | | # writedata ='{}'.format(data_list.popleft())
|
| | | # Note.write(writedata.encode('hex'))
|
| | | csv_writer.writerow(text_)
|
| | | except Exception as e:
|
| | | raise e
|
| | | # 发送socket消息
|
| | | # sio.emit('msg', {'response': 'my response'})
|
| | | if sio.connected:
|
| | | sio.emit("msg",{"time": nowtime_str,"data":L})
|
| | | # socket_.send("msg",{"data":text_})
|
| | | L.clear()
|
| | | # print('-----------------------------end---------------------------------')
|
| | |
|
| | | def test(self):
|
| | | global is_exit
|
| | | while True: |
| | | sleep(10)
|
| | | is_exit = False
|
| | | sleep(10)
|
| | | is_exit = True
|
| | |
|
| | | serialPort = 'COM4' # 串口
|
| | | baudRate = 115200 # 波特率
|
| | | socketurl_ = "http://192.168.0.225:5000"
|
| | | is_exit = False
|
| | | data_bytes = bytearray()
|
| | | data_list = deque()
|
| | | send_list = deque()
|
| | | L = []
|
| | | data_L = [[],[],[],[]]
|
| | | sio = socketio.Client(logger=True, engineio_logger=True)
|
| | | # sio = socketio.Client()
|
| | | start_timer = None
|
| | | csv_writer = None
|
| | | is_data_header = False
|
| | |
|
| | | @sio.event
|
| | | def connect():
|
| | | print('connected to server')
|
| | |
|
| | |
|
| | | @sio.event
|
| | | def pong_from_server():
|
| | | global start_timer
|
| | | latency = time.time() - start_timer
|
| | | print('latency is {0:.2f} ms'.format(latency * 1000))
|
| | | sio.sleep(1)
|
| | | if sio.connected:
|
| | | print(' reconnected')
|
| | |
|
| | |
|
| | | @sio.on('command_msg')
|
| | | def command_msg(data):
|
| | | global is_exit
|
| | | if data['command'] == 'stop':
|
| | | is_exit = True
|
| | | if data['command'] == 'start':
|
| | | is_exit = False
|
| | |
|
| | | if __name__ == '__main__':
|
| | | # 打开串口
|
| | | mSerial = SerialPort(serialPort, baudRate)
|
| | |
|
| | | # 文件写入操作
|
| | | # filename = input('请输入文件名:比如test.csv:')
|
| | | filename = 'test.csv'
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%y-%m-%d %I-%M-%S') # 时间
|
| | | filename = nowtime_str+'_'+filename
|
| | | out = open(filename, 'w')
|
| | | csv_writer = csv.writer(out)
|
| | | # txt写入
|
| | | # Note=open(nowtime_str+'_test.txt',mode='w')
|
| | |
|
| | | # 开始数据读取线程
|
| | | t1 = threading.Thread(target=mSerial.read_data)
|
| | | t1.setDaemon(True)
|
| | | t1.start()
|
| | |
|
| | | # 连接socketio
|
| | | sio.connect(socketurl_)
|
| | |
|
| | | # 开始写数据
|
| | | t3 = threading.Thread(target=mSerial.write_data())
|
| | | t3.setDaemon(True)
|
| | | t3.start()
|
| | |
|
| | | # sio.wait() #sio事件处理
|
| | | t2 = threading.Thread(target=sio.wait())
|
| | | t2.setDaemon(True)
|
| | | t2.start()
|
| | |
|
| | | # 连接socket
|
| | | # remote_IP='192.168.0.225'
|
| | | # remote_port=5000
|
| | | # remote_addr=(remote_IP,remote_port)
|
| | | # socket_=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
| | | # socket_.connect(remote_addr) |
| New file |
| | |
| | | #!/usr/bin/python
|
| | | # -*-coding: utf-8 -*-
|
| | |
|
| | | from asyncio import sleep
|
| | | from collections import deque
|
| | | from distutils.log import debug
|
| | | from multiprocessing.connection import wait
|
| | | from pickle import FALSE
|
| | | from tracemalloc import start
|
| | | import serial
|
| | | import threading
|
| | | from datetime import datetime
|
| | | import socketio
|
| | | import time
|
| | | import csv
|
| | | # import pysnooper
|
| | |
|
| | |
|
| | | class SerialPort:
|
| | | def __init__(self, port, buand):
|
| | | self.port = serial.Serial(port, buand)
|
| | | self.port.close()
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_open(self):
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_close(self):
|
| | | self.port.close()
|
| | |
|
| | | def send_data(self):
|
| | | self.port.write('')
|
| | |
|
| | | # @pysnooper.snoop()
|
| | | def read_data(self):
|
| | | global is_exit
|
| | | global data_bytes,data_list,csv_writer,int_list
|
| | | while True: |
| | | while not is_exit:
|
| | | count = self.port.inWaiting()
|
| | | if count > 0:
|
| | | rec_str = self.port.read(count)
|
| | | # data_list.append(rec_str)
|
| | | for byte in rec_str:
|
| | | # print('----------------------------',type(byte),byte)
|
| | | int_list.append(byte)
|
| | | # data_bytes = data_bytes+rec_str
|
| | | # print(str(datetime.now()),':','当前数据接收总字节数:'+str(len(data_bytes))+' 本次接收字节数:'+str(len(rec_str)))
|
| | | # wait(10000)
|
| | | # try:
|
| | | # # writedata ='{}'.format(data_list.popleft())
|
| | | # # Note.write(writedata.encode('hex'))
|
| | | # csv_writer.writerow(rec_str)
|
| | | # except Exception as e:
|
| | | # raise e
|
| | | # @pysnooper.snoop()
|
| | | def write_data(self): |
| | | global data_L,index_,is_exit,send_list,int_list,sio,serialPort
|
| | | start_array = False
|
| | | while True:
|
| | | while not is_exit:
|
| | | if len(int_list)<1: |
| | | continue |
| | | x = int_list.popleft()
|
| | | if(not start_array and x==60):
|
| | | if len(int_list)<3:
|
| | | int_list.appendleft(x)
|
| | | break
|
| | | else:
|
| | | y = int_list.popleft()
|
| | | z = int_list.popleft()
|
| | | m = int_list.popleft()
|
| | | if (y == 170 and z == 85 and m==65):
|
| | | data_L=[[],[],[],[]]
|
| | | index_ =(abs(69-m)%4) |
| | | data_L[index_].append(x)
|
| | | data_L[index_].append(y)
|
| | | data_L[index_].append(z)
|
| | | data_L[index_].append(m)
|
| | | start_array = True
|
| | | else:
|
| | | data_L[index_].append(x)
|
| | | int_list.appendleft(m)
|
| | | int_list.appendleft(z)
|
| | | int_list.appendleft(y)
|
| | | else:
|
| | | if(len(data_L[index_]) == 61):
|
| | | index_ = (index_+1)%4
|
| | | data_L[index_].append(x)
|
| | | else:
|
| | | data_L[index_].append(x)
|
| | | if(len(data_L[3]) == 61):
|
| | | # send_list.append(data_L)
|
| | | if(data_L[0][3] != 65):
|
| | | start_array = False
|
| | | break
|
| | | try:
|
| | | for r in data_L:
|
| | | csv_writer.writerow(r)
|
| | | except Exception as e:
|
| | | raise e
|
| | | ret = [[],[],[],[]]
|
| | | i = 0
|
| | | while(i<4):
|
| | | if(len(data_L[i]) != 61):
|
| | | continue
|
| | | j = 5
|
| | | while(j<61):
|
| | | ret[i].append(data_L[i][j+1]*256 + data_L[i][j])
|
| | | j = j+2
|
| | | i = i+1 |
| | | # print(parse_data(send_list.popleft()))
|
| | | if sio.connected:
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%Y-%m-%d %H:%M:%S.%f') # 时间
|
| | | sio.emit("msg",{"time": nowtime_str,"serialport":serialPort,"data":ret})
|
| | | data_L = [[],[],[],[]]
|
| | | index_ = 0
|
| | |
|
| | | def send_data(self): |
| | | global send_list,sio
|
| | | while True:
|
| | | while not is_exit:
|
| | | if sio.connected:
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%Y-%m-%d %H:%M:%S.%f') # 时间
|
| | | sio.emit("msg",{"time": nowtime_str,"data":send_list.popleft()})
|
| | | # try:
|
| | | # for r in data_L:
|
| | | # csv_writer.writerow(r)
|
| | | # except Exception as e:
|
| | | # raise e
|
| | |
|
| | | def test(self):
|
| | | global is_exit
|
| | | while True: |
| | | sleep(10)
|
| | | is_exit = False
|
| | | sleep(10)
|
| | | is_exit = True
|
| | |
|
| | | serialPort = '/dev/tty.usbserial-14130' # 串口
|
| | | baudRate = 115200 # 波特率
|
| | | socketurl_ = "http://127.0.0.1:3001"
|
| | | is_exit = False
|
| | | data_bytes = bytearray()
|
| | | data_list = deque()
|
| | | send_list = deque()
|
| | | int_list= deque()
|
| | | L = []
|
| | | base_length = 61
|
| | | data_L = [[],[],[],[]]
|
| | | index_ = 0 #第 A/B/C/D 组数据
|
| | | sio = socketio.Client(logger=True, engineio_logger=True)
|
| | | # sio = socketio.Client()
|
| | | start_timer = None
|
| | | csv_writer = None
|
| | | is_data_header = False
|
| | |
|
| | | @sio.event
|
| | | def connect():
|
| | | print('connected to server')
|
| | |
|
| | |
|
| | | @sio.event
|
| | | def pong_from_server():
|
| | | global start_timer
|
| | | latency = time.time() - start_timer
|
| | | print('latency is {0:.2f} ms'.format(latency * 1000))
|
| | | sio.sleep(1)
|
| | | if sio.connected:
|
| | | print(' reconnected')
|
| | |
|
| | |
|
| | | @sio.on('command_msg')
|
| | | def command_msg(data):
|
| | | global is_exit
|
| | | if data['command'] == 'stop':
|
| | | is_exit = True
|
| | | if data['command'] == 'start':
|
| | | is_exit = False
|
| | |
|
| | | def parse_data(data):
|
| | | ret = [[],[],[],[]]
|
| | | i = 0
|
| | | while(i<4):
|
| | | j = 5
|
| | | arr = data[i]
|
| | | print(arr)
|
| | | while(j<61):
|
| | | print('------------------',i,j,arr[j],'----------------------')
|
| | | # ret[i].append(data[i][j+1]*256 + data[i][j])
|
| | | j = j+2
|
| | | i = i+1
|
| | | return ret
|
| | |
|
| | |
|
| | | if __name__ == '__main__':
|
| | | # serialPort = input("请输入串口字符串")
|
| | | # 打开串口
|
| | | mSerial = SerialPort(serialPort, baudRate)
|
| | |
|
| | | # 文件写入操作
|
| | | # filename = input('请输入文件名:比如test.csv:')
|
| | | filename = 'test.csv'
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%y-%m-%d %I-%M-%S') # 时间
|
| | | filename = nowtime_str+'_'+filename
|
| | | out = open(filename, 'w')
|
| | | csv_writer = csv.writer(out)
|
| | | # txt写入
|
| | | # Note=open(nowtime_str+'_test.txt',mode='w')
|
| | |
|
| | | # 开始数据读取线程
|
| | | t1 = threading.Thread(target=mSerial.read_data)
|
| | | t1.setDaemon(True)
|
| | | t1.start()
|
| | |
|
| | | # 连接socketio
|
| | | sio.connect(socketurl_)
|
| | | # 开始写数据
|
| | | t2 = threading.Thread(target=mSerial.write_data())
|
| | | t2.setDaemon(True)
|
| | | t2.start()
|
| | | |
| | | # sio.wait() #sio事件处理
|
| | | t4 = threading.Thread(target=sio.wait())
|
| | | print('------------------------------------------------------------------------')
|
| | | t4.setDaemon(True)
|
| | | t4.start()
|
| | |
|
| | | # 连接socket
|
| | | # remote_IP='192.168.0.225'
|
| | | # remote_port=5000
|
| | | # remote_addr=(remote_IP,remote_port)
|
| | | # socket_=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
| | | # socket_.connect(remote_addr) |
| New file |
| | |
| | | #!/usr/bin/python
|
| | | # -*-coding: utf-8 -*-
|
| | |
|
| | | from asyncio import sleep
|
| | | from collections import deque
|
| | | from distutils.log import debug
|
| | | from multiprocessing.connection import wait
|
| | | from pickle import FALSE
|
| | | from tracemalloc import start
|
| | | import serial
|
| | | import threading
|
| | | from datetime import datetime
|
| | | import socketio
|
| | | import time
|
| | | import csv
|
| | | # import pysnooper
|
| | |
|
| | |
|
| | | class SerialPort:
|
| | | def __init__(self, port, buand):
|
| | | self.port = serial.Serial(port, buand)
|
| | | self.port.close()
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_open(self):
|
| | | if not self.port.isOpen():
|
| | | self.port.open()
|
| | |
|
| | | def port_close(self):
|
| | | self.port.close()
|
| | |
|
| | | def send_data(self):
|
| | | self.port.write('')
|
| | |
|
| | | # @pysnooper.snoop()
|
| | | def read_data(self):
|
| | | global is_exit
|
| | | global data_bytes,data_list,csv_writer,int_list
|
| | | while True: |
| | | while not is_exit:
|
| | | count = self.port.inWaiting()
|
| | | if count > 0:
|
| | | rec_str = self.port.read(count)
|
| | | # data_list.append(rec_str)
|
| | | for byte in rec_str:
|
| | | # print('----------------------------',type(byte),byte)
|
| | | int_list.append(byte)
|
| | | # data_bytes = data_bytes+rec_str
|
| | | # print(str(datetime.now()),':','当前数据接收总字节数:'+str(len(data_bytes))+' 本次接收字节数:'+str(len(rec_str)))
|
| | | # wait(10000)
|
| | | # try:
|
| | | # # writedata ='{}'.format(data_list.popleft())
|
| | | # # Note.write(writedata.encode('hex'))
|
| | | # csv_writer.writerow(rec_str)
|
| | | # except Exception as e:
|
| | | # raise e
|
| | | # @pysnooper.snoop()
|
| | | def write_data(self): |
| | | global data_L,index_,is_exit,send_list,int_list,sio,serialPort
|
| | | start_array = False
|
| | | while True:
|
| | | while not is_exit:
|
| | | if len(int_list)<1: |
| | | continue |
| | | x = int_list.popleft()
|
| | | if(not start_array and x==60):
|
| | | if len(int_list)<3:
|
| | | int_list.appendleft(x)
|
| | | break
|
| | | else:
|
| | | y = int_list.popleft()
|
| | | z = int_list.popleft()
|
| | | m = int_list.popleft()
|
| | | if (y == 170 and z == 85 and m==65):
|
| | | data_L=[[],[],[],[]]
|
| | | index_ =(abs(69-m)%4) |
| | | data_L[index_].append(x)
|
| | | data_L[index_].append(y)
|
| | | data_L[index_].append(z)
|
| | | data_L[index_].append(m)
|
| | | start_array = True
|
| | | else:
|
| | | data_L[index_].append(x)
|
| | | int_list.appendleft(m)
|
| | | int_list.appendleft(z)
|
| | | int_list.appendleft(y)
|
| | | else:
|
| | | if(len(data_L[index_]) == 61):
|
| | | index_ = (index_+1)%4
|
| | | data_L[index_].append(x)
|
| | | else:
|
| | | data_L[index_].append(x)
|
| | | if(len(data_L[3]) == 61):
|
| | | # send_list.append(data_L)
|
| | | if(data_L[0][3] != 65):
|
| | | start_array = False
|
| | | break
|
| | | try:
|
| | | for r in data_L:
|
| | | csv_writer.writerow(r)
|
| | | except Exception as e:
|
| | | raise e
|
| | | ret = [[],[],[],[]]
|
| | | i = 0
|
| | | while(i<4):
|
| | | if(len(data_L[i]) != 61):
|
| | | continue
|
| | | j = 5
|
| | | while(j<61):
|
| | | ret[i].append(data_L[i][j+1]*256 + data_L[i][j])
|
| | | j = j+2
|
| | | i = i+1 |
| | | # print(parse_data(send_list.popleft()))
|
| | | if sio.connected:
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%Y-%m-%d %H:%M:%S.%f') # 时间
|
| | | sio.emit("msg",{"time": nowtime_str,"serialport":serialPort,"data":ret})
|
| | | data_L = [[],[],[],[]]
|
| | | index_ = 0
|
| | |
|
| | | def send_data(self): |
| | | global send_list,sio
|
| | | while True:
|
| | | while not is_exit:
|
| | | if sio.connected:
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%Y-%m-%d %H:%M:%S.%f') # 时间
|
| | | sio.emit("msg",{"time": nowtime_str,"data":send_list.popleft()})
|
| | | # try:
|
| | | # for r in data_L:
|
| | | # csv_writer.writerow(r)
|
| | | # except Exception as e:
|
| | | # raise e
|
| | |
|
| | | def test(self):
|
| | | global is_exit
|
| | | while True: |
| | | sleep(10)
|
| | | is_exit = False
|
| | | sleep(10)
|
| | | is_exit = True
|
| | |
|
| | | serialPort = '/dev/tty.usbserial-14110' # 串口
|
| | | baudRate = 115200 # 波特率
|
| | | socketurl_ = "http://127.0.0.1:3001"
|
| | | is_exit = False
|
| | | data_bytes = bytearray()
|
| | | data_list = deque()
|
| | | send_list = deque()
|
| | | int_list= deque()
|
| | | L = []
|
| | | base_length = 61
|
| | | data_L = [[],[],[],[]]
|
| | | index_ = 0 #第 A/B/C/D 组数据
|
| | | sio = socketio.Client(logger=True, engineio_logger=True)
|
| | | # sio = socketio.Client()
|
| | | start_timer = None
|
| | | csv_writer = None
|
| | | is_data_header = False
|
| | |
|
| | | @sio.event
|
| | | def connect():
|
| | | print('connected to server')
|
| | |
|
| | |
|
| | | @sio.event
|
| | | def pong_from_server():
|
| | | global start_timer
|
| | | latency = time.time() - start_timer
|
| | | print('latency is {0:.2f} ms'.format(latency * 1000))
|
| | | sio.sleep(1)
|
| | | if sio.connected:
|
| | | print(' reconnected')
|
| | |
|
| | |
|
| | | @sio.on('command_msg')
|
| | | def command_msg(data):
|
| | | global is_exit
|
| | | if data['command'] == 'stop':
|
| | | is_exit = True
|
| | | if data['command'] == 'start':
|
| | | is_exit = False
|
| | |
|
| | | def parse_data(data):
|
| | | ret = [[],[],[],[]]
|
| | | i = 0
|
| | | while(i<4):
|
| | | j = 5
|
| | | arr = data[i]
|
| | | print(arr)
|
| | | while(j<61):
|
| | | print('------------------',i,j,arr[j],'----------------------')
|
| | | # ret[i].append(data[i][j+1]*256 + data[i][j])
|
| | | j = j+2
|
| | | i = i+1
|
| | | return ret
|
| | |
|
| | |
|
| | | if __name__ == '__main__':
|
| | | # serialPort = input("请输入串口字符串")
|
| | | # 打开串口
|
| | | mSerial = SerialPort(serialPort, baudRate)
|
| | |
|
| | | # 文件写入操作
|
| | | # filename = input('请输入文件名:比如test.csv:')
|
| | | filename = 'test.csv'
|
| | | dt = datetime.now()
|
| | | nowtime_str = dt.strftime('%y-%m-%d %I-%M-%S') # 时间
|
| | | filename = nowtime_str+'_'+filename
|
| | | out = open(filename, 'w')
|
| | | csv_writer = csv.writer(out)
|
| | | # txt写入
|
| | | # Note=open(nowtime_str+'_test.txt',mode='w')
|
| | |
|
| | | # 开始数据读取线程
|
| | | t1 = threading.Thread(target=mSerial.read_data)
|
| | | t1.setDaemon(True)
|
| | | t1.start()
|
| | |
|
| | | # 连接socketio
|
| | | sio.connect(socketurl_)
|
| | | # 开始写数据
|
| | | t2 = threading.Thread(target=mSerial.write_data())
|
| | | t2.setDaemon(True)
|
| | | t2.start()
|
| | | |
| | | # sio.wait() #sio事件处理
|
| | | t4 = threading.Thread(target=sio.wait())
|
| | | print('------------------------------------------------------------------------')
|
| | | t4.setDaemon(True)
|
| | | t4.start()
|
| | |
|
| | | # 连接socket
|
| | | # remote_IP='192.168.0.225'
|
| | | # remote_port=5000
|
| | | # remote_addr=(remote_IP,remote_port)
|
| | | # socket_=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
| | | # socket_.connect(remote_addr) |
| New file |
| | |
| | | import socketio
|
| | |
|
| | | def create_sio():
|
| | | sio = socketio.Client()
|
| | | return sio
|
| | |
|
| | | def connect_(url,sio):
|
| | | if not url:
|
| | | sio.connect(url)
|
| | | sio.on('connect', on_connect)
|
| | | sio.on('chat_message', revc_message)
|
| | | sio.on('disconnect', on_disconnect)
|
| | | sio.on('reconnect', on_reconnect)
|
| | | print('create sio')
|
| | | return sio
|
| | |
|
| | | def sio(url,tparams):
|
| | | if not tparams:
|
| | | sio = socketio.Client()
|
| | | sio.connect(url)
|
| | | sio.on('connect', on_connect)
|
| | | sio.on('chat_message', revc_message)
|
| | | sio.on('disconnect', on_disconnect)
|
| | | sio.on('reconnect', on_reconnect)
|
| | | return sio
|
| | |
|
| | |
|
| | | def get_sessionid(userid, roomid):
|
| | | pass
|
| | |
|
| | | def on_connect(*args):
|
| | | # print(*args)
|
| | | print('connect')
|
| | |
|
| | | def on_disconnect():
|
| | | print('## disconnect ##')
|
| | |
|
| | | def on_reconnect():
|
| | | print('reconnect')
|
| | |
|
| | | def send_msg(sendmessage, sio):
|
| | | sio.emit('msg', b'{sendmessage}')
|
| | | return |
| | |
|
| | | def revc_message(*args): # 这个函数很重要 是socketio监听信息获取的函数, 这里面socketio会自行调用这个函数
|
| | | response_data_format = {}
|
| | | response_data = eval(args[0])
|
| | | print(response_data)
|
| | |
|
| | | def revc_message_mutil(*args): # 这个函数很重要 是socketio监听信息获取的函数, 这里面socketio会自行调用这个函数
|
| | | response_data_format = {}
|
| | | response_data = eval(args[0])
|
| | | print(response_data)
|
| | |
|
| | | def create_params(userid, roomid): # 这个方法类似requests库的封装方法 看底层貌似与requests的urllib3方法一样
|
| | | vsessionid, tsessionid = get_sessionid(userid, roomid)
|
| | | vparams = {
|
| | | 'sessionid': vsessionid,
|
| | | }
|
| | | tparams = {
|
| | | 'sessionid': tsessionid,
|
| | | }
|
| | | return vparams, tparams
|
| | |
|
| | | def clear_data():
|
| | | print('sessionid') |
| New file |
| | |
| | | L = []
|
| | | a = b'\x00\xef\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdthe first line\n\r\a\b\t\\\f\'\"\v\b\n\000'
|
| | | print(a)
|
| | | for each in a:
|
| | | L.append(int(each))
|
| | | with open('data.txt','w') as p:
|
| | | p.write(str(L))
|
| | | print(L)
|
| | |
|
| | | |
| | | with open('data.txt','r') as p:
|
| | | line = p.readline()
|
| | | print(b''.join([bytes([int(i)]) for i in line[1:-1].split(',')]))
|
| | |
|
| | |
|
| | | def readbytetxt2(filename):
|
| | | dic = {
|
| | | '0': 0, '1': 1, '2': 2,
|
| | | '3': 3, '4': 4, '5': 5,
|
| | | '6': 6, '7': 7, '8': 8,
|
| | | '9': 9, 'a': 10, 'b': 11,
|
| | | 'c': 12, 'd': 13, 'e': 14,
|
| | | 'f': 15,
|
| | | }
|
| | | dic2 = {
|
| | | 'a': '\a', 'b': '\b', |
| | | 'f': '\f', 'n': '\n', |
| | | 'r': '\r', 'v': '\v', |
| | | '\'': '\'', '\"': '', |
| | | '\\': '\\', |
| | | }
|
| | | with open(filename,'r') as p:
|
| | | line = p.readline()
|
| | | while line:
|
| | | if line[-1] == '\n':
|
| | | line = line[:-1]
|
| | | i = 2
|
| | | L = b''
|
| | | while i+1 < len(line):
|
| | | if line[i:i+2] == '\\x' and (line[i+2] in dic.keys()) and (line[i+3] in dic.keys()):
|
| | | L += bytes([dic[line[i+2]]*16+dic[line[i+3]]])
|
| | | i += 4
|
| | | elif line[i] == '\\' and line[i+1] in dic2.keys():
|
| | | L += bytes(dic2[line[i+1]],'utf8')
|
| | | i += 2
|
| | | elif line[i:i+4] == '\\000':
|
| | | L += bytes('\000','utf8')
|
| | | i += 2
|
| | | else:
|
| | | L += bytes(line[i],'utf8')
|
| | | i += 1
|
| | | yield L
|
| | | line = p.readline()
|
| | | |
| | | a = b'\x00\xef\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdthe first line\n\r\a\b\t\\\f\'\"\v\b\n\000'
|
| | | b = b'\xa0\xdf\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdthe second line\nn'
|
| | | c = b'\xe0\xaf\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdthe third line\\'
|
| | | with open('data.txt','w') as p:
|
| | | p.write(str(a)+'\n')
|
| | | p.write(str(b)+'\n')
|
| | | p.write(str(c))
|
| | | |
| | | line = readbytetxt2('data.txt')
|
| | | |
| | | print([a for a in line]) |
| New file |
| | |
| | | <!DOCTYPE html>
|
| | | <html>
|
| | | <head>
|
| | | <title>WebSocket</title>
|
| | |
|
| | | <style>
|
| | | html, body {
|
| | | font: normal 1em arial, helvetica;
|
| | | }
|
| | |
|
| | | #log {
|
| | | width: 400px;
|
| | | height: 200px;
|
| | | border: 1px solid #000000;
|
| | | overflow: auto;
|
| | | }
|
| | |
|
| | | #msg {
|
| | | width: 330px;
|
| | | }
|
| | | </style>
|
| | |
|
| | | <script>
|
| | | var socket;
|
| | |
|
| | | function init() {
|
| | | var host = "ws://127.0.0.1:5000/";
|
| | | try {
|
| | | socket = new WebSocket(host);
|
| | | socket.onopen = function (msg) {
|
| | | log("Begin Connection!");
|
| | | };
|
| | | socket.onmessage = function (msg) {
|
| | | log(msg.data);
|
| | | };
|
| | | socket.onclose = function (msg) {
|
| | | log("Lose Connection!");
|
| | | };
|
| | | }
|
| | | catch (ex) {
|
| | | log(ex);
|
| | | }
|
| | | $("msg").focus();
|
| | | }
|
| | |
|
| | | function send() {
|
| | | var txt, msg;
|
| | | txt = $("msg");
|
| | | msg = txt.value;
|
| | | if (!msg) {
|
| | | alert("Message can not be empty");
|
| | | return;
|
| | | }
|
| | | txt.value = "";
|
| | | txt.focus();
|
| | | try {
|
| | | socket.send(msg);
|
| | | } catch (ex) {
|
| | | log(ex);
|
| | | }
|
| | | }
|
| | |
|
| | | window.onbeforeunload = function () {
|
| | | try {
|
| | | socket.send('quit');
|
| | | socket.close();
|
| | | socket = null;
|
| | | }
|
| | | catch (ex) {
|
| | | log(ex);
|
| | | }
|
| | | };
|
| | |
|
| | |
|
| | | function $(id) {
|
| | | return document.getElementById(id);
|
| | | }
|
| | | function log(msg) {
|
| | | $("log").innerHTML += "<br>" + msg;
|
| | | }
|
| | | function onkey(event) {
|
| | | if (event.keyCode == 13) {
|
| | | send();
|
| | | }
|
| | | }
|
| | | </script>
|
| | |
|
| | | </head>
|
| | | <body onload="init()">
|
| | | <h3>WebSocket</h3>
|
| | | <br>
|
| | | <div id="log"></div>
|
| | | <input id="msg" type="textbox" onkeypress="onkey(event)"/>
|
| | | <button onclick="send()">发送</button>
|
| | | </body>
|
| | | </html>
|
| New file |
| | |
| | | import threading
|
| | | from time import sleep
|
| | | import eventlet
|
| | | import socketio
|
| | |
|
| | |
|
| | | def create_serve():
|
| | | sio = socketio.Server()
|
| | | app = socketio.WSGIApp(sio, static_files={
|
| | | '/': {'content_type': 'text/html', 'filename': 'index.html'}
|
| | | })
|
| | |
|
| | | @sio.event
|
| | | def connect(sid, environ):
|
| | | print('connect ', sid)
|
| | | sio.emit('serve', {'response': 'connert success'})
|
| | | # delay_cmd = Delay_cmd(sio)
|
| | | # t3 = threading.Thread(target=delay_cmd.send(delay_cmd))
|
| | | # t3.setDaemon(True)
|
| | | # t3.start()
|
| | |
|
| | | @sio.on('msg')
|
| | | def on_message(sid, data):
|
| | | print('serve received a message! on_message',data)
|
| | | # sio.emit('command_msg', {'command': 'stop', "params":"nothing"})
|
| | |
|
| | | @sio.on('client')
|
| | | def another_event(sid, data):
|
| | | print('serve received a message!', data)
|
| | |
|
| | | # @sio.event
|
| | | # def my_event(sid, data):
|
| | | # print('message ', data)
|
| | | # sio.emit('serve', {'response': 'connert success'})
|
| | |
|
| | | @sio.event
|
| | | def disconnect(sid):
|
| | | print('disconnect ', sid)
|
| | |
|
| | | if __name__ == '__main__':
|
| | | eventlet.wsgi.server(eventlet.listen(('', 5000)), app)
|
| | |
|
| | |
|
| | | class Delay_cmd():
|
| | | def __init__(self, sio,):
|
| | | self.sio = sio
|
| | | |
| | | def send(self):
|
| | | while True:
|
| | | sleep(10)
|
| | | self.sio.emit('command_msg', {'command': 'stop', "params":"nothing"})
|
| | | sleep(10)
|
| | | self.sio.emit('command_msg', {'command': 'start', "params":"nothing"})
|
| | |
|
| | | create_serve() |