Skip to content

Commit

Permalink
Change logging
Browse files Browse the repository at this point in the history
  • Loading branch information
nikolay committed Jul 24, 2020
1 parent 3a58709 commit cfd9392
Show file tree
Hide file tree
Showing 8 changed files with 110 additions and 68 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea
dwgconfig.py
*.pyc
16 changes: 9 additions & 7 deletions README.md
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Overview
========

This Script for VoIP GSM Module - Dinstar DWG 2000: sending and receiveing SMS/USSD from/to gateway (written on Python2).
This Script for VoIP GSM Module - Dinstar DWG 2000: sending and receiving SMS/USSD from/to gateway (written on Python2).

How to compile
==============
Expand All @@ -20,6 +20,8 @@ How to install
- On/Off debugging (debug)
- Path for pidfile, if running as daemon (pidfile)
- Path to logfile, if running as daemon (logfile)
- Format of log line (log_format)
- Format of date in log line (log_date_format)

How to use
==========
Expand All @@ -31,13 +33,13 @@ How to use
- restart: restarting script as daemon
- help: showing help message for arguments
- Sending SMS format:
- First line - phone number
- Second line - port
- Other lines - message for send
- First line - phone number
- Second line - port
- Other lines - message for send
- Received message as eml format.
- Sending USSD-command format
- First line - port
- Second line - USSD-command (ex. *100#)
- Sending USSD-command format:
- First line - port
- Second line - USSD-command (ex. *100#)
- Received message as eml format.

Depends
Expand Down
2 changes: 1 addition & 1 deletion daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import atexit
from signal import SIGTERM


class Daemon:
"""
A generic daemon class.
Expand Down Expand Up @@ -63,7 +64,6 @@ def daemonize(self):
def delpid(self):
os.remove(self.pidfile)


def start(self):
try:
pf = file(self.pidfile, 'r')
Expand Down
52 changes: 31 additions & 21 deletions dwg.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,35 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import dwgconfig
import socket
import logging
from sys import argv
from dwgc import DWGD, logger
from dwgc import DWGD
from daemon import Daemon
from logger import create_logger


def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', dwgconfig.port))
sock.listen(1)
logger('[SYSTEM] Server listening...', False)
logging.info('[SYSTEM] Server listening...')

try:
while True:
conn, addr = sock.accept()
logger('[SYSTEM] Gateway connected %s' % addr[0], False)
logging.info('[SYSTEM] Gateway connected %s' % addr[0])
DWGD(conn)
logger('[SYSTEM] Gateway disconnected', False)
logging.info('[SYSTEM] Gateway disconnected')
except KeyboardInterrupt:
logging.info('[SYSTEM] Daemon keyboard interrupted')
exit()
finally:
logging.info('[SYSTEM] Daemon socket closed')
sock.close()


def usage():
print """
Script usage parameters:
Expand All @@ -33,34 +40,37 @@ def usage():
help - Show this help
"""


class DWGDaemon(Daemon):
def run(self):
main()


"""
Check agrvs
"""
if __name__ == "__main__":
daemon = DWGDaemon(dwgconfig.pidfile)
if len(argv) == 2:
if argv[1] == 'debug':
dwgconfig.debug = True
dwgconfig.as_daemon = False
logger('[SYSTEM] Debug mode is on', True)
main()
elif argv[1] == 'start':
logger('[SYSTEM] Daemon started', True)
daemon.start()
elif argv[1] == 'stop':
logger('[SYSTEM] Daemon stopped', True)
daemon.stop()
elif argv[1] == 'restart':
logger('[SYSTEM] Daemon restarted', True)
daemon.restart()
else:
allowed_argv = ['debug', 'start', 'stop', 'restart']
if argv[1] not in allowed_argv:
usage()
exit(2)
exit(0)
else:
create_logger(argv[1] == 'debug')
if argv[1] == 'debug':
logging.debug('[SYSTEM] Debug mode is on')
main()
elif argv[1] == 'start':
logging.info('[SYSTEM] Daemon started')
daemon.start()
elif argv[1] == 'stop':
logging.info('[SYSTEM] Daemon stopped')
daemon.stop()
elif argv[1] == 'restart':
logging.info('[SYSTEM] Daemon restarted')
daemon.restart()
exit(0)
else:
usage()
exit(2)
exit(2)
59 changes: 22 additions & 37 deletions dwgc.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from time import time, strftime
import codecs
import os
import logging
from subprocess import Popen


Expand Down Expand Up @@ -40,19 +41,15 @@ def getDWG(self):
exit()
except:
break
if not self.ping_t is None:
self.ping_t.cancel()
if not self.check_t is None:
self.check_t.cancel()
self.stop_ping()
self.conn.close()


def parseDWG(self, data):
"""
Parsing DWG Messages
"""
if data:
logger('[PROCESS] <- %s' % data.encode("hex"), True)
logging.debug('[PROCESS] <- %s' % data.encode("hex"))
while data:
header = {'len': unpack('!L', data[0:4])[0],
'id': {'mac': unpack('!6s', data[4:10])[0],
Expand All @@ -74,7 +71,7 @@ def parseType(self, htype, data):
"""
sdata = {'type': 0,
'body': ''}
if htype == 0: # recieved keep alive
if htype == 0: # received keep alive
self.ping_count = 0
elif htype == 7: # Status message
sdata['type'] = 8
Expand Down Expand Up @@ -109,9 +106,9 @@ def parseType(self, htype, data):
if body['login'] == dwgconfig.login and body['password'] == dwgconfig.password:
sdata['type'] = 16
sdata['body'] = pack('!?', False)
logger('[SYSTEM] Authentication success', False)
logging.info('[SYSTEM] Authentication success')
else:
logger('[SYSTEM] Authentication failed', False)
logging.info('[SYSTEM] Authentication failed')
elif htype == 515: # Call state report
sdata['type'] = 516
sdata['body'] = pack('!?', False)
Expand All @@ -122,10 +119,7 @@ def pingDWG(self):
Ping DWG
"""
if self.ping_count > 2:
if not self.ping_t is None:
self.ping_t.cancel()
if not self.check_t is None:
self.check_t.cancel()
self.stop_ping()
self.conn.close()
else:
sdata = {'type': 0,
Expand All @@ -147,7 +141,7 @@ def sendDWG(self, header, sdata):
pkt += pack('!H', sdata['type'])
pkt += pack('!H', 0)
pkt += sdata['body']
logger('[PROCESS] -> %s' % pkt.encode("hex"), True)
logging.debug('[PROCESS] -> %s' % pkt.encode("hex"))
self.conn.send(pkt)

def create_header(self):
Expand Down Expand Up @@ -179,9 +173,9 @@ def saveSMS(self, body):
sms.write(body['content'].decode('utf-16-be'))
sms.close()
Popen(dwgconfig.run_program)
logger('[DATA] Received SMS from number %s' % body['number'], False)
logging.info('[DATA] Received SMS from number %s' % body['number'])
except:
logger('[DATA] Received unknown SMS', False)
logging.info('[DATA] Received unknown SMS')

def saveUSSD(self, body):
"""
Expand All @@ -202,23 +196,24 @@ def saveUSSD(self, body):
elif body['encoding'] == 1:
ussd.write(body['content'].decode('utf-16-be'))
ussd.close()
logger('[DATA] Received USSD from port %s' % body['port'], False)
logging.info('[DATA] Received USSD from port %s' % body['port'])
except:
logger('[DATA] Received unknown USSD', False)

logging.info('[DATA] Received unknown USSD')

def checkSMS(self):
"""
Check SMS/USSD in folders
"""
files = [f for f in os.listdir(dwgconfig.send_path) if os.path.isfile(os.path.join(dwgconfig.send_path, f))]
port = None
number = None
if len(files):
sms = codecs.open(dwgconfig.send_path + files[0], 'r', 'utf-8').readlines()
f_send = True
if len(sms) > 2:
try:
number = str(sms[0].strip())
if not number.isdigit(): f_send = False
# if not number.isdigit(): f_send = False
except:
f_send = False
try:
Expand All @@ -233,7 +228,7 @@ def checkSMS(self):
sdata = {'type': 1,
'body': pack('!BBBB24sH%ds' % len(content), port, 1, 0, 1, number, len(content), content)}
self.sendDWG(self.create_header(), sdata)
logger('[DATA] Sending SMS to number %s' % number, False)
logging.info('[DATA] Sending SMS to number %s' % number)
os.remove(dwgconfig.send_path + files[0])
else:
files = [f for f in os.listdir(dwgconfig.ussd_send_path) if os.path.isfile(os.path.join(dwgconfig.ussd_send_path, f))]
Expand All @@ -253,23 +248,13 @@ def checkSMS(self):
sdata = {'type': 9,
'body': pack('!BBH%ds' % len(number), port, 1, len(number), number)}
self.sendDWG(self.create_header(), sdata)
logger('[DATA] Sending USSD to port %s to number %s' % (port, number), False)
logging.info('[DATA] Sending USSD to port %s to number %s' % (port, number))
os.remove(dwgconfig.ussd_send_path + files[0])
self.check_t = Timer(self.check_timer, self.checkSMS)
self.check_t.start()


def logger(message, debug):
now = strftime('%d.%m.%Y %H:%M:%S')
line = '[%s] %s' % (now, message)
if dwgconfig.as_daemon:
line += '\n'
if debug and dwgconfig.debug:
open(dwgconfig.logfile, 'a').write(line)
elif not debug:
open(dwgconfig.logfile, 'a').write(line)
else:
if debug and dwgconfig.debug:
print line
elif not debug:
print line
def stop_ping(self):
if self.ping_t is not None:
self.ping_t.cancel()
if self.check_t is not None:
self.check_t.cancel()
5 changes: 3 additions & 2 deletions dwgconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@

pidfile = '/var/run/dwg_server.pid' # PID file path (for daemon)
logfile = '/var/log/dwg_server.log' # Log file path (for daemon)
as_daemon = True
log_format = '[%(asctime)s] [%(levelname)s] %(message)s' # Log file format
log_date_format = '%d.%m.%Y %H:%M:%S' # Log file date format

if __name__ == '__main__':
print 'Config file for Dinstar DWG Gateways!'
print 'Config file for Dinstar DWG Gateways!'
20 changes: 20 additions & 0 deletions dwgconfig.py.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

port = 12000 # DWG Gateway port
login = 'test' # DWG API Login (from API 2.0)
password = 'test' # DWG API Password (from API 2.0)
income_path = '/var/spool/dwgp/incoming/' # SMS income path
send_path = '/var/spool/dwgp/send/' # SMS send path
ussd_income_path = '/var/spool/dwgp/ussd_incoming/' # USSD income path
ussd_send_path = '/var/spool/dwgp/ussd_send' # USSD send path
run_program = '/etc/local_scripts/radius2.php' # External program after receiving SMS
debug = True # On/OFF Debug

pidfile = '/var/run/dwg_server.pid' # PID file path (for daemon)
logfile = '/var/log/dwg_server.log' # Log file path (for daemon)
log_format = '[%(asctime)s] [%(levelname)s] %(message)s' # Log file format
log_date_format = '%d.%m.%Y %H:%M:%S' # Log file date format

if __name__ == '__main__':
print 'Config file for Dinstar DWG Gateways!'
21 changes: 21 additions & 0 deletions logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import dwgconfig


def create_logger(debug=False):
log = logging.getLogger()
formatter = logging.Formatter(dwgconfig.log_format, datefmt=dwgconfig.log_date_format)
log_level = logging.DEBUG
if debug:
log_handler = logging.StreamHandler()
else:
if not dwgconfig.debug:
log_level = logging.INFO
log_handler = logging.FileHandler(dwgconfig.logfile)
log_handler.setLevel(log_level)
log_handler.setFormatter(formatter)
log.setLevel(log_level)
log.addHandler(log_handler)

1 comment on commit cfd9392

@zad2019
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hello
i want to do smart panel for ussd recharge DINSTAR GW
HOW MUCH IT COST

Please sign in to comment.