panasonic-log-reader/data_reader.py

130 lines
4.8 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/python3.5
####################################################################
# Скрипт разбора лога АТС Panasonic TDA200
# вызов:
# для обработки файла созданного, к примеру, программой SMDRLog
# > python data_reader.py -file TDA20013082015_12052016.lg
# для чтения данных напрямую с com-порта АТС
# > python data_reader.py -port /dev/ttyUSB0
#
# Автор: Сергей Калинин banzaj28@gmail.com
# Лицензия: GPL
####################################################################
import pymysql
import sys, os
import re
import datetime
# параметры соединения с СУБД
db_host = 'host'
db_user = 'dbuser'
db_pass = 'dbpass'
out_dir = '/var/log/ats'
def insert(**kwargs):
"""Вставка данных в БД. В качестве параметров список полей и значений"""
qwery = 'INSERT INTO `cdr` ('
for key in kwargs.keys():
qwery = "{} `{}`, ".format(qwery,key)
qwery = qwery.rstrip(', ') + ') VALUES('
for key in kwargs.keys():
#qwery = qwery + '"' + kwargs.get(key) +'", '
qwery = "{} \"{}\",".format(qwery,kwargs.get(key))
qwery = qwery.rstrip(', ') + ');'
print(qwery)
conn = pymysql.connect(host=db_host, database='ats', user=db_user, password=db_pass, charset='utf8')
cur = conn.cursor()
cur.execute(qwery)
conn.commit()
cur.close()
conn.close()
def parce_string(line):
"""Получает на вход строку и раскидывает её в нужном виде и пишет в файл"""
if line[:3] == "---" or line == "" or line[3:7] == "Date":
print(line)
return
print(line)
# Создаём текстовые файлы на всякий случай, для дублирования информации
now = datetime.datetime.now()
out_log_name = os.path.join(out_dir, '{}_{}'.format(now.month, now.year))
out_log = open(out_log_name,"a+")
out_log.write(line + '\n')
out_log.close()
# Разбор строки
# Преобразуем дату к виду "ДД/ММ/ГГГГ"
#call_date = "{}.{}.20{}".format(line[:2],line[3:5],line[6:8])
call_date = "20{}/{}/{}".format(line[6:8],line[3:5],line[:2])
call_time = line[9:14].strip()
int_number = line[19:22].strip()
ext_co_line = line[23:25].strip()
dial_number = line[26:51].strip()
ring = line[52:56].strip()
call_duration = re.sub("'", ":", line[57:65].strip())
acc_code = line[66:77].strip()
call_code = line[77:81].strip()
# Проверяем признак входящщего звонка
if dial_number == "<I>":
call_direct = "Входящий"
dial_number = ""
elif dial_number[:3] == "EXT":
call_direct = "Внутренний"
dial_number = dial_number[3:]
else: call_direct = "Исходящий"
insert(call_date=call_date,
call_time=call_time,
int_number=int_number,
ext_co_line=ext_co_line,
dial_number=dial_number,
ring=ring,
call_duration=call_duration,
acc_code=acc_code,
call_code=call_code,
call_direct=call_direct)
def port_data_read(port_name):
global out_dir
"""Чтение данных из последовательного порта, тестовая реализация"""
import serial
ser = serial.Serial(port_name)
#ser = serial.Serial("com1")
ser.baudrate = 9600
print(ser)
while True:
line = ser.readline()
line = line.decode()
line = line.rstrip()
parce_string(line)
if __name__ == "__main__":
# В зависисмости от ключей вызова скрипта выполняем ту или иную процедуру
# соответсвенно -port - чтение из порта, -file - чтение из файла
if len(sys.argv) > 2:
if sys.argv[1] == '-port':
#action = 'read_port'
port_name = sys.argv[2]
port_data_read(port_name)
if sys.argv[1] == '-file':
#action = 'read_file'
log_file_name = sys.argv[2]
log = open(log_file_name)
for line in log:
parce_string(line)
log.close()
else:
print ("\nФормат вызова:\n- для обработки файла\
\n # python data_reader.py -file TDA20013082015_12052016.lg\
\n- для чтения данных напрямую с com-порта АТС\
\n # python data_reader.py -port /dev/ttyUSB0\n")
sys.exit(1)
c