启动一个服务,使用FastAPI框架,增加跨域允许
1 # -*- coding: UTF-8 -*- 2 """ 3 @author: cc 4 @file: service.py 5 @time: 2021/05/24 6 """ 7 8 import sqlite3 9 from fastapi import FastAPI 10 import uvicorn 11 import os 12 from fastapi.middleware.cors import CORSMiddleware 13 14 service_path = os.path.normpath(os.path.dirname(os.path.abspath(__file__))) 15 db = os.path.join(service_path, 'perfume.db') 16 17 conn = sqlite3.connect(db) 18 curs = conn.cursor() 19 20 app = FastAPI() 21 22 origins = [ 23 "*", 24 ] 25 26 app.add_middleware( 27 CORSMiddleware, 28 allow_origins=origins, 29 allow_credentials=True, 30 allow_methods=["*"], 31 allow_headers=["*"], 32 ) 33 34 @app.get('/') 35 async def perfume(scent: str): 36 data = [] 37 scents = scent.split(",") 38 if scent: 39 if len(scents) == 1: 40 sql = "select * from perfume_scent where scent='{}'".format(scent) 41 res = curs.execute(sql) 42 res_list = list(res) 43 lens = len(res_list) 44 if lens == 0: 45 sql = "select * from perfume_scent where scents like '% {} %'".format(scent) 46 res = curs.execute(sql) 47 res_list = list(res) 48 else: 49 sign_str = '' 50 for scent in scents: 51 sign_str += "(case when instr(scents, ' {} ') > 0 then 1 else 0 end) + ".format(scent) 52 sign_str = sign_str[:-3] 53 sql = "select *, {} as num from perfume_list order by num desc limit 5".format(sign_str) 54 55 res = curs.execute(sql) 56 res_list = list(res) 57 58 for item in res_list: 59 li = { 60 'name': item[1].replace("{} ".format(item[3]), ""), 61 'en_name': item[2], 62 'brand': item[3], 63 'image': item[6], 64 'scents': item[7], 65 } 66 data.append(li) 67 68 return {'scent': data} 69 70 if __name__ == '__main__': 71 uvicorn.run(app=app, host='0.0.0.0', port=8000)
1 # -*- coding: UTF-8 -*- 2 """ 3 @author: cc 4 @file: service.py 5 @time: 2021/05/24 6 """ 7 8 import sqlite3 9 from fastapi import FastAPI 10 import uvicorn 11 import os 12 from fastapi.middleware.cors import CORSMiddleware 13 14 service_path = os.path.normpath(os.path.dirname(os.path.abspath(__file__))) 15 db = os.path.join(service_path, 'perfume.db') 16 17 conn = sqlite3.connect(db) 18 curs = conn.cursor() 19 20 app = FastAPI() 21 22 origins = [ 23 "*", 24 ] 25 26 app.add_middleware( 27 CORSMiddleware, 28 allow_origins=origins, 29 allow_credentials=True, 30 allow_methods=["*"], 31 allow_headers=["*"], 32 ) 33 34 @app.get('/') 35 async def perfume(scent: str): 36 data = [] 37 scents = scent.split(",") 38 if scent: 39 if len(scents) == 1: 40 sql = "select * from perfume_scent where scent='{}'".format(scent) 41 res = curs.execute(sql) 42 res_list = list(res) 43 lens = len(res_list) 44 if lens == 0: 45 sql = "select * from perfume_scent where scents like '% {} %'".format(scent) 46 res = curs.execute(sql) 47 res_list = list(res) 48 else: 49 sign_str = '' 50 for scent in scents: 51 sign_str += "(case when instr(scents, ' {} ') > 0 then 1 else 0 end) + ".format(scent) 52 sign_str = sign_str[:-3] 53 sql = "select *, {} as num from perfume_list order by num desc limit 5".format(sign_str) 54 55 res = curs.execute(sql) 56 res_list = list(res) 57 58 for item in res_list: 59 li = { 60 'name': item[1].replace("{} ".format(item[3]), ""), 61 'en_name': item[2], 62 'brand': item[3], 63 'image': item[6], 64 'scents': item[7], 65 } 66 data.append(li) 67 68 return {'scent': data} 69 70 if __name__ == '__main__': 71 uvicorn.run(app=app, host='0.0.0.0', port=8000)
1 # -*- coding: UTF-8 -*- 2 """ 3 @author: cc 4 @file: smellPlayer.py 5 @time: 2021/01/12 6 """ 7 import serial 8 import os 9 from binascii import unhexlify 10 from crcmod import crcmod 11 12 os.path.join('..') 13 from util import logging 14 logger = logging.getLogger(__name__) 15 16 FRAME_HEAD = 'F5' 17 FRAME_TAIL = '55' 18 19 def crc16Add(str_data): 20 crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000) 21 data = str_data.replace(" ", "") 22 readcrcout = hex(crc16(unhexlify(data))).upper() 23 str_list = list(readcrcout) 24 if len(str_list) < 6: 25 str_list.insert(2, '0'*(6-len(str_list))) # 位数不足补0 26 crc_data = "".join(str_list) 27 return crc_data[2:4]+' '+crc_data[4:] 28 29 30 def ten2sixteen(num, length): 31 """ 32 十进制转十六进制 33 :param num: 十进制数字 34 :param length: 字节长度 35 :return: 36 """ 37 data = str(hex(eval(str(num))))[2:] 38 data_len = len(data) 39 if data_len % 2 == 1: 40 data = '0' + data 41 data_len += 1 42 43 sixteen_str = "00 " * (length - data_len//2) + data[0:2] + ' ' + data[2:] 44 return sixteen_str.strip() 45 46 47 class SmellPlayer(object): 48 49 isOpen = False # 串口是否开启,默认关闭 50 ser = None # 串口连接信息 51 52 def __init__(self): 53 self.init_device() 54 55 def search_usb(self): 56 logger.info("开始查找气味模块串口信息") 57 import serial.tools.list_ports 58 self.device = None 59 port_list = list(serial.tools.list_ports.comports()) 60 if len(port_list) == 0: 61 logger.warning("没有找到USB串口信息,请连接气味模块") 62 else: 63 for i in range(0, len(port_list)): 64 if 'USB Serial' in str(port_list[i]): 65 self.device = str(port_list[i]).split('-')[0].strip() 66 logger.info('气味模块串口信息:{}'.format(str(port_list[i]))) 67 break 68 69 if not self.device: 70 logger.warning("没有找到气味模块设备,请连接气味模块") 71 72 def connect(self): 73 """ 74 连接串口 75 76 """ 77 if self.device: 78 try: 79 ser = serial.Serial(self.device, 19200, timeout=2) 80 if ser.isOpen(): 81 self.isOpen = True 82 self.ser = ser 83 logger.info("设备连接成功,{}".format(str(self.ser))) 84 else: 85 self.isOpen = False 86 logger.warning("设备打开失败") 87 except Exception as e: 88 logger.warning("设备连接失败:{}".format(e)) 89 90 def init_device(self): 91 self.search_usb() 92 self.connect() 93 94 def play(self, channel, seconds): 95 """ 96 开始播放气味 97 98 :param channel: 信道(路数) 99 :return: 100 """ 101 102 if self.isOpen: 103 logger.info("开始播放气味,channel值为:{}, 播放时间 {} 秒".format(channel, seconds)) 104 self.channel = int(channel) 105 self.exec(self.channel, seconds) 106 107 def stop(self): 108 """ 109 停止播放气味 110 111 :return: 112 """ 113 if self.isOpen: 114 logger.info("停止播放气味") 115 stop_cmd = '12 00 00 01 00 01 00' 116 verify = crc16Add(stop_cmd) 117 cmd = FRAME_HEAD + ' ' + stop_cmd + ' ' + verify + ' ' + FRAME_TAIL 118 self.ser.write(bytes.fromhex(cmd)) 119 120 def exec(self, channel, seconds): 121 """ 122 发送协议 123 :param channel: 信道(路数) 124 :param seconds: 播放时长 125 :return: 126 """ 127 play_cmd = '12 01 00 00 02 05' 128 scent_channel = ten2sixteen(channel, 1) 129 play_time = ten2sixteen(seconds, 4) 130 str_data = play_cmd + ' ' + scent_channel + ' ' + play_time 131 verify = crc16Add(str_data) 132 cmd = FRAME_HEAD + ' ' + str_data + ' ' + verify + ' ' + FRAME_TAIL 133 if self.isOpen: 134 logger.info("通信协议内容:{}".format(str(cmd))) 135 try: 136 self.ser.write(bytes.fromhex(cmd)) 137 logger.info("协议发送成功") 138 except Exception as e: 139 logger.warning('执行报错:{}'.format(e)) 140 141 def close(self): 142 """ 143 关闭串口连接 144 :return: 145 """ 146 147 if self.isOpen: 148 logger.info("关闭设备连接") 149 self.ser.close()