def send_mail() -> None: """Отправляет сообщение с расписанием занятий""" try: server = smtplib.SMTP_SSL('smtp.mail.ru', 465) # Формируем тело письма subject = input("Введи текст темы сообщения: ") main_body_text = input("Введи текст сообщения для отправки: ") # Отправка текста: (как альтернатива способу ниже) # msg_img = MIMEMultipart() # msg = MIMEText(body, 'plain', 'utf-8') # msg['Subject'] = Header(subject, 'utf-8') img_data = open('schedule/schedule.png', 'rb').read() msg = MIMEMultipart() image = MIMEImage(img_data, name=os.path.basename('schedule/schedule.png')) msg['Subject'] = Header(subject, 'utf-8') text = MIMEText(main_body_text) msg.attach(text) msg.attach(image) # Отправляем письмо server.login(username, password) server.sendmail(username, mail_receiver, msg.as_string()) server.quit() except FileNotFoundError: logger.warning("NOT schedule.png")
def commit_session(sess): try: sess.commit() except Exception as e: logger.error(e) sess.rollback() logger.warning('commit failed') sess.close()
def pars_img(): """Берет картинку с сайта""" try: image = soup.find( class_="page_raspis_block_img").find("img").get("src") urlretrieve(image, filename="schedule/schedule.png") logger.info("Начинаю скачивание файла") except NotSchedule: logger.warning("NOT schedule")
def update_net_param(net_param: NetParams): sess = DBSession() try: query = sess.query(NetParams) rst = query.filter_by(net_param_id=1).first() rst.remote_uart_addr = 1234 logger.info(rst) sess.commit() except Exception as e: logger.error(e) sess.rollback() logger.warning('update router_device failed %s' % net_param) sess.close() pass
def addr_info_handler(msg): data = msg.data idx = 1 count = data[idx:idx + 1] logger.info('addr count %d' % bytes_to_int(count)) idx += 1 addrs = [] for i in range(bytes_to_int(count)): addr = data[idx:idx + 2] idx += 2 _addr = bytes_to_int(addr) addrs.append('0X%04X' % _addr) pass logger.warning('addr info %s' % addrs) pass
def mt_sys_handler(msg: Msg): logger.debug('sys handler') if len(msg.data): if msg.data[0] == SUCCESS: logger.info('success') handler_info = get_handler_func(msg.cmd_state1, msg.cmd_state2) if handler_info: handler_name = handler_info['name'] handler_func = handler_info['func'] logger.info('handler func %s' % handler_name) handler_func(msg) pass else: logger.warning('handler func not found') pass
def update_router_device(router_device: RouterDevice, params): sess = DBSession() try: query = sess.query(RouterDevice) _filter = query.filter_by(ext_addr=router_device.ext_addr) if 'router_device_id' in params: _filter = _filter.filter( RouterDevice.router_device_id == params['router_id']) if 'ext_addr' in params: _filter = _filter.filter( RouterDevice.ext_addr == params['ext_addr']) if 'net_addr' in params: _filter = _filter.filter( RouterDevice.net_addr == params['net_addr']) if 'name' in params: _filter = _filter.filter(RouterDevice.name == params['name']) if 'status' in params: _filter = _filter.filter(RouterDevice.status == params['status']) rst = _filter.all() for device in rst: if router_device.ext_addr: device.ext_addr = router_device.ext_addr if router_device.net_addr: device.net_addr = router_device.net_addr if router_device.status: device.status = router_device.status if router_device.name: device.name = router_device.name if router_device.voltage: device.voltage = router_device.voltage if router_device.start_time: device.start_time = router_device.start_time if router_device.update_time: device.update_time = router_device.update_time if router_device.rssi: device.rssi = router_device.rssi if router_device.lqi: device.lqi = router_device.lqi if router_device.parent: device.parent = router_device.parent sess.commit() except Exception as e: logger.error(e) sess.rollback() logger.warning('update router_device failed %s' % router_device) sess.close() pass
def run(self): while True: try: send_data = serial_out_msg_queue.get() data = send_data['data'] self.client.send_data(data) try: rep = serial_rep_msg_queue.get(timeout=2) if rep == SUCCESS: logger.info('rep success,data = %s' % data) pass if rep == FAILED: logger.warning('rep failed,data = %s' % data) pass except Empty as e: logger.warning('rep timeout,data = %s' % data) pass except Exception as e: time.sleep(5) logger.error(traceback.format_exc()) pass
def serial_process(): MsgProcessThread().start() with serial.Serial(config.serial_port, config.serial_rate) as ser: Thread(target=msg_handler, args=()).start() send_data = SerialSendData(ser) MsgSendDataThread(send_data).start() init_coor_device() while True: try: serial_in_msg_queue.put(ser.read()) except Exception as e: logger.warning('ser closed. \t %s', e) ser.close() flag = 1 while True: try: ser.open() init_coor_device() logger.warning('ser re open success') break except Exception as e: if flag: flag = 0 logger.warning('%s', e) pass pass pass
def tcp_process(): msg_process_thread = MsgProcessThread() msg_process_thread.setDaemon(True) msg_process_thread.start() host = config.tcp_addr port = config.tcp_port addr = (host, port) tcp_client = socket(AF_INET, SOCK_STREAM) tcp_client.connect(addr) tcp_client.settimeout(5 * 60) # 五分钟没有接收到数据说明直接重新连接 init_coor_device() Thread(target=msg_handler, args=()).start() tcp_send_data = TcpSendData(tcp_client) msg_send_thread = MsgSendDataThread(tcp_send_data) msg_send_thread.setDaemon(True) msg_send_thread.start() sync_clock_thread = SyncCoorClockThread(1800) # 30min同步一次时间 sync_clock_thread.setDaemon(True) sync_clock_thread.start() while True: try: serial_in_msg_queue.put(tcp_client.recv(1)) except Exception as e: logger.warning('tcp connect closed \t %s' % traceback.format_exc()) tcp_client.close() while True: try: logger.warning('prepare re connect') tcp_client = socket(AF_INET, SOCK_STREAM) tcp_client.settimeout(5 * 60) # 五分钟没有接收到数据说明直接重新连接 tcp_client.connect(addr) tcp_send_data.client = tcp_client init_coor_device() logger.warning('re connect success') break except Exception as e: tcp_client.close() logger.warning('%s' % e)
def update_end_device(end_device: EndDevice, params): sess = DBSession() try: query = sess.query(EndDevice) _filter = query.filter_by(ext_addr=end_device.ext_addr) if 'end_device_id' in params: _filter = _filter.filter( EndDevice.end_device_id == params['end_device_id']) if 'ext_addr' in params: _filter = _filter.filter(EndDevice.ext_addr == params['ext_addr']) if 'net_addr' in params: _filter = _filter.filter(EndDevice.net_addr == params['net_addr']) if 'name' in params: _filter = _filter.filter(EndDevice.name == params['name']) if 'status' in params: _filter = _filter.filter(EndDevice.status == params['status']) if 'hum_freq' in params: _filter = _filter.filter(EndDevice.hum_freq == params['hum_freq']) if 'temp_freq' in params: _filter = _filter.filter( EndDevice.temp_freq == params['temp_freq']) rst = _filter.all() for device in rst: if end_device.ext_addr: device.ext_addr = end_device.ext_addr if end_device.net_addr: device.net_addr = end_device.net_addr if end_device.status: device.status = end_device.status if end_device.name: device.name = end_device.name if end_device.voltage: device.voltage = end_device.voltage if end_device.start_time: device.start_time = end_device.start_time if end_device.hum_freq: device.hum_freq = end_device.hum_freq if end_device.temp_freq: device.temp_freq = end_device.temp_freq if end_device.hum: device.hum = end_device.hum if end_device.temp: device.temp = end_device.temp if end_device.update_time: device.update_time = end_device.update_time if end_device.rssi: device.rssi = end_device.rssi if end_device.lqi: device.lqi = end_device.lqi if end_device.pv: device.pv = end_device.pv if end_device.time_window: device.time_window = end_device.time_window if end_device.parent: device.parent = end_device.parent if end_device.type: device.type = end_device.type sess.commit() except Exception as e: logger.error(e) sess.rollback() logger.warning('update end_device failed %s' % end_device) sess.close() pass
def run(self): self.timer = self.init_timer() while True: try: for _ in range(self.msg_len): self.msg.append(serial_in_msg_queue.get()) if self.state == SOP_STATE: char = self.get_one_msg(self.idx) if char == MT_UART_SOF: self.state = LEN_STATE self.msg_len = 1 # if not self.timer._is_stopped: # self.timer = self.init_timer() # self.timer.start() elif self.state == LEN_STATE: char = self.get_one_msg(self.idx) self.data['len'] = char self.state = CMD_STATE1 self.msg_len = 1 elif self.state == CMD_STATE1: char = self.get_one_msg(self.idx) self.data['cmd_state1'] = char self.state = CMD_STATE2 self.msg_len = 1 elif self.state == CMD_STATE2: char = self.get_one_msg(self.idx) self.data['cmd_state2'] = char if self.data['len'] == 0: self.state = FCS_STATE self.msg_len = 1 else: self.state = DATA_STATE self.msg_len = self.data['len'] elif self.state == DATA_STATE: chs = self.msg[self.idx - self.data['len'] + 1:self.idx + 1] for b in chs: self.data['data'] += b self.state = FCS_STATE self.msg_len = 1 pass elif self.state == FCS_STATE: char = self.get_one_msg(self.idx) fcs = self.cal_fcs() if fcs == char: mt_msg = Msg(self.data) msg_queue.put(mt_msg) logger.info('add msg : %s' % mt_msg) else: logger.warning('fcs failed') # self.msg = self.msg[1:] self.msg = self.msg[self.idx + 1:] self.timer.cancel() # self.timer = self.init_timer() self.state = SOP_STATE self.init_msg() self.idx = -1 self.msg_len = 1 self.idx += self.msg_len except Exception as e: time.sleep(5) logger.error(e) pass pass
def time_out_process(self): logger.warning('time out, state = %s' % self.state) if self.state != SOP_STATE: self.state = SOP_STATE self.init_msg() pass
def mt_app_handler(msg): logger.debug('app handler') if len(msg.data): if msg.data[0] == TEMP_HUM_DATA: logger.debug('temp hum data') temp_hum_handler(msg) return if msg.data[0] == COOR_START: logger.warning('coor start') coor_start_handler() return if msg.data[0] == END_REPORT_STATUS_CMD: logger.warning('end report status') end_report_status_handler(msg) return if msg.data[0] == ROUTER_STATUS_CMD: logger.warning('router report status') router_report_status_handler(msg) return if msg.data[0] == MASTER_GET_ADDR_COUNT_CMD: logger.warning("addr info") addr_info_handler(msg) return if msg.data[0] == COOR_REPORT_NV_PARAMS_CMD: logger.warning("coor report nv params") coor_report_nv_params_handler(msg) return if msg.data[0] == SUCCESS: logger.info('cmd success') return pass logger.warning('unknown cmd id ') else: logger.warning('app msg data empty')
# 进阶版:组装一个日志功能(二次开发实现的) # import logging # logger = logging.getLogger() #创建一个空架子,与logging独立 # fh = logging.FileHandler("test1.log","a",encoding="utf-8") #创建一个文件句柄用来记录日志(文件流) # ch = logging.StreamHandler() #创建一个屏幕流(打印记录的内容) # formater = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(filename)s %(lineno)s %(message)s") #定义一个记录文件的格式 # # # # fh.setFormatter(formater) #给文件句柄设置记录内容的格式 # ch.setFormatter(formater) #给中控台设置打印内容的格式 # # logger.addHandler(fh) #将文件句柄添加到logger对象中 # logger.addHandler(ch) #将中控台添加到logger对象中 # # logger.level = 10 #设置警告级别 # # logger.debug("调试") # logger.info("信息") # logger.warning("警告") # logger.error("错误") # logger.critical("危险") from my_logger import logger logger.debug("调试2") logger.info("信息2") logger.warning("警告2") logger.error("错误2") logger.critical("危险2")