main.py 11.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
#!/usr/bin/env python

import logging
from logging.handlers import TimedRotatingFileHandler
import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('config.ini')

PORT = config.get('globals','PORT')
BAUDRATE = config.getint('globals', 'BAUDRATE')
PIN = None # SIM card PIN (if any)
PIN_TRX = config.get('globals', 'PIN_TRX')

BASE_CHIPINFO = config.get('globals', 'BASE_CHIPINFO')
CHIPINFO = BASE_CHIPINFO

AAA_HOST = config.get('globals', 'AAA_HOST')
CITY = config.get('globals', 'CITY')
PRODUCTS = config.get('globals', 'PRODUCTS')

REDIS_HOST = config.get('globals', 'REDIS_HOST')
REDIS_PORT = config.getint('globals', 'REDIS_PORT')
REDIS_TTL = config.getint('globals', 'REDIS_TTL')
REDIS_DISABLE_PULL_TTL = config.getint('globals', 'REDIS_DISABLE_PULL_TTL')

PULL_INTERVAL = config.getint('globals', 'PULL_INTERVAL')
SLEEP_AFTER_TOPUP = config.getint('globals', 'SLEEP_AFTER_TOPUP')
SLEEP_BETWEEN_BALANCE_N_TOPUP = config.getint('globals', 'SLEEP_BETWEEN_BALANCE_N_TOPUP')
TOPUP_USSD_TIMEOUT = config.getint('globals', 'TOPUP_USSD_TIMEOUT')
SLEEP_AFTER_USSD_ERROR = 90

MIN_BALANCE = config.getint('globals', 'MIN_BALANCE')

PULL_COUNT = 0
MSISDN = ''
BALANCE = 0

DISABLE_SEM=0
DISABLE_SEM_ON_TRX=60

logger = None

from gsmmodem.modem import GsmModem
from gsmmodem.exceptions import TimeoutException

from time import sleep
from time import strftime

import redis
import requests

import sate24 
import xltunai

redis_client = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=0)

def handleSms(sms):
    global DISABLE_SEM
    
    #logger.info(u'== SMS From: {0}; Time: {1}; Message: {2}'.format(sms.number, sms.time, sms.text))
    
    if not xltunai.isValidSender(sms.number):
        logger.info('Ignoring incoming sms from invalid sender')
        return
    
    logger.info('Incoming SMS')
    logger.info(sms)
        
    if sms.text.find('Terimakasih, transaksi CASH IN ke akun') >= 0:
        logger.info('handleSms: CASH IN, aktivasi pull jika non aktif')
        enablePull()
        return
    
        
    destination = xltunai.getDestinationFromMessage(sms.text)
    if destination == '':
        logger.warning('handleSms: gagal parsing nomor tujuan')
        return
        
    nominal = xltunai.getNominalFromMessage(sms.text)
    if nominal == '':
        logger.warning('handleSms: gagal parsing nominal')
        return
    
    sn = xltunai.getSNFromMessage(sms.text)
    if sn == '':
        logger.warning('handleSms: gagal parsing SN')
    
    
    DISABLE_SEM = 0
    
    response_code = xltunai.getResponseCodeByMessage(sms.text)
    
    request_id = getRequestIdByNominalDestination(nominal, destination)
    if not request_id:
        logger.info('Unknown request id for nominal:{0} destination:{1}'.format(nominal, destination))
        return
        
    pushTopupStatus(request_id, response_code, sms.text)
    

def getRequestIdByNominalDestination(nominal, destination):
    redis_key = sate24.keyByNominalDestination(CHIPINFO, nominal, destination)
    return redis_client.spop(redis_key)
    
def pushTopupStatus(request_id, response_code, _message):
    global BALANCE
    global CHIPINFO
    
    redis_key = sate24.keyByRequestId(CHIPINFO, request_id) + '.response_code'
    if response_code == '00':
        redis_client.set(redis_key, response_code)
    else:
        redis_response_code = redis_client.get(redis_key)
        if redis_response_code == '00':
            logger.info('Ignoring message from success trx ')
            return
        
    message = "{0} -- Prev balance: {1}".format(_message, BALANCE)
    
    timestamp = strftime('%Y%m%d%H%M%S')
    
    if response_code == '00':
        sn = xltunai.getSNFromMessage(message)
        message = 'SN={0};{1}'.format(sn, message)
        
    push_message = CHIPINFO + '$' + message
    
    payload = {
        'trans_id': request_id,
        'trans_date': timestamp,
        'resp_code': response_code,
        'ussd_msg': push_message
    }
    
    url = AAA_HOST + '/topup'
    
    try:
        logger.info('Sending topup status to AAA')
        logger.info(payload)
        r = requests.get(url, params=payload)
    except:
        return
        
def getIsDisableRedisKey():
    return CHIPINFO + '.pulldisable'
    
def isPullEnable():
    redis_key = getIsDisableRedisKey()
    result = 'FALSE'
    
    try:
        result = redis_client.get(redis_key)
        redis_client.expire(redis_key, REDIS_DISABLE_PULL_TTL)
    except:
        return False
        
    if not result:
        return True
    
    return result == 'FALSE'

def enablePull():
    logger.info('Enabling Pull on products {0}'.format(PRODUCTS))
    redis_key = getIsDisableRedisKey()
    try:
        redis_client.set(redis_key, 'FALSE')
        redis_client.expire(redis_key, REDIS_DISABLE_PULL_TTL)
    except:
        return

def disablePull():
    global DISABLE_SEM
    global DISABLE_SEM_ON_TRX
    
    logger.info('Disabling Pull')
    redis_key = getIsDisableRedisKey()
    try:
        redis_client.set(redis_key, 'TRUE')
        redis_client.expire(redis_key, REDIS_DISABLE_PULL_TTL)
    except:
        return
            
def topupTask(task, modem):
    if not task:
        return
    
    if task['status'] != 'OK':
        return
    
    checkSignal(modem)
    
    redis_key = sate24.keyByRequestId(CHIPINFO, task['requestId'])
    redis_client.set(redis_key, task)
    redis_client.expire(redis_key, REDIS_TTL)
    
    nominal = xltunai.getNominalFromProduct(task['product'])
    intl_destination = xltunai.toInternationalNumber(task['destination'])
    
    redis_key = sate24.keyByNominalDestination(CHIPINFO, nominal, intl_destination)
    redis_client.sadd(redis_key, task['requestId'])
    redis_client.expire(redis_key, REDIS_TTL)
    
    pushTopupStatus(task['requestId'], '68', 'Siap mengirimkan trx ke operator')

    message = 'Executing USSD'
    response_code = '68'
    
    ussd_command = xltunai.getTopupUSSDCommand(task['destination'], task['product'], PIN_TRX)
    
    logger.info(u'Executing {0}'.format(ussd_command))
    try:
        response = modem.sendUssd(ussd_command, TOPUP_USSD_TIMEOUT) 
        
        message = response.message.strip()
        logger.info(u'USSD response: {0}'.format(message))
        
        response_code = xltunai.getResponseCodeByUSSDResponse(message)
        
        if response.sessionActive:
            response.cancel()
            
    except TimeoutException:
        message = "USSD Error: Timeout when executing USSD topup"
        logger.warning(message)
        pushTopupStatus(task['requestId'], '40', message)
        sleep(SLEEP_AFTER_USSD_ERROR)
        return
    except:
        message = "USSD Error: Something wrong when executing USSD topup"
        logger.warning(message)
        pushTopupStatus(task['requestId'], '40', message)
        sleep(SLEEP_AFTER_USSD_ERROR)
        return

    DISABLE_SEM = DISABLE_SEM_ON_TRX
    pushTopupStatus(task['requestId'], response_code, message)

def pull(modem):
    global PULL_COUNT
    global BALANCE
    global DISABLE_SEM
    
    if DISABLE_SEM > 0:
        logger.info('SEMAPHORE is still on, delaying pull')
        DISABLE_SEM -= 1
        return
    
    if not isPullEnable():
        return
        
    r = None
    try:
        r = requests.get(AAA_HOST + '/pull?city=' + CITY + '&nom=' + PRODUCTS)
    except:
        logger.warning("Error requesting to AAA")
        return

    if not r:
        return
        
    task = sate24.parsePullMessage(r.text)
    
    if task['status'] == 'OK':
        
        logger.info(r.text)
        if not checkBalance(modem) or BALANCE == 0:
            pushTopupStatus(task['requestId'], '40', 'Transaksi dibatalkan karena gagal check balance')
            sleep(SLEEP_BETWEEN_BALANCE_N_TOPUP)
            return
            
        sleep(SLEEP_BETWEEN_BALANCE_N_TOPUP)
        
        topupTask(task, modem)
        sleep(SLEEP_AFTER_TOPUP)

def pullLoop(modem):
    while (True):        
        pull(modem)
        sleep(PULL_INTERVAL)

def checkSignal(modem):
    logger.info('Signal: {0}'.format(modem.signalStrength))
    try:
        redis_client.set(CHIPINFO + '.signal', modem.signalStrength)
        redis_client.expire(CHIPINFO + '.signal', 3600*24)
    except:
        logger.warning("Can not save signal strength to redis")

def checkAccount(modem):
    try:        
        ussd_string = '*123*120*8*3#'
        response = modem.sendUssd(ussd_string, 30)
        logger.info('Account Info: {0}'.format(response.message))
        
        if response.sessionActive:
            response.cancel()
    except:
        logger.warning('Error when requesting account info')
        return False
    
def checkBalance(modem):
    global BALANCE
    
    #BALANCE = 0
    try:
        
        ussd_string = '*123*120#'
        response = modem.sendUssd(ussd_string, 30) 
        BALANCE = xltunai.getBalanceFromUSSDResponse(response.message)
        logger.info('Balance: {0}'.format(BALANCE))
        if response.sessionActive:
            response.cancel()
            
        if BALANCE != 0 and BALANCE < MIN_BALANCE:
            logger.info('Disabling pull, balance {0} < {1}'.format(BALANCE, MIN_BALANCE))
            disablePull()
            
    except:
        logger.warning('Error when requesting BALANCE by USSD')
        return False
    
    try:
        redis_client.set(CHIPINFO + '.balance', BALANCE)
    except:
        logger.warning('Failed to save balance to redis')
        
    return True
    
def getSIMCardInfo(modem):
    try:
        ussd_string = xltunai.getSIMCardInfoUSSDCommand()
        response = modem.sendUssd(ussd_string)
        
        message = response.message.strip()
        logger.info('SIM INFO: {0}'.format(message))
        if response.sessionActive:
            response.cancel()
        
        return message
        
    except:
        logger.warning('Error when requesting SIM card info by USSD')
        return ''

def updateChipInfo(msisdn):
    global BASE_CHIPINFO
    global CHIPINFO
    global MSISDN
    
    MSISDN = msisdn
    if CHIPINFO.find(msisdn) == -1:
        CHIPINFO = BASE_CHIPINFO + '_' + msisdn
        
    logger.info('CHIPINFO: {0}'.format(CHIPINFO))
        
def main():
    global logger
    
    log_format = '%(asctime)s %(levelname)s: %(message)s'
    
    logging.basicConfig(format=log_format, level=logging.INFO)
    logger = logging.getLogger(__name__)
    
    logger_formatter = logging.Formatter(log_format)
    logger_handler = TimedRotatingFileHandler('logs/log', when='midnight')
    logger_handler.setFormatter(logger_formatter)
    logger.addHandler(logger_handler)
    
    requests_logger = logging.getLogger('requests')
    requests_logger.setLevel(logging.WARNING)
    
    logger.info('Initializing modem...')
    
    modem = GsmModem(PORT, BAUDRATE, smsReceivedCallbackFunc=handleSms)
    modem.smsTextMode = True 
    modem.connect(PIN)
    
    logger.info('Waiting for network coverage...')
    modem.waitForNetworkCoverage(10)
    
    logger.info('Modem ready')
    
    simcard_info = getSIMCardInfo(modem)
    msisdn = xltunai.getMSISDNFromSIMCardInfo(simcard_info)
    imsi = xltunai.getIMSIFromSIMCardInfo(simcard_info) 
    logger.info('MSISDN: {0} -- IMSI: {1}'.format(msisdn, imsi))
    
    updateChipInfo(msisdn)
    
    sleep(2)
    
    checkSignal(modem)
    
    logger.info('Process stored SMS')
    try:
        modem.processStoredSms()
    except:
        logger.warning('Failed on Process stored SMS')
    
    logger.info('Delete stored SMS')
    try:
        modem.deleteMultipleStoredSms()
    except:
        logger.warning('Failed on delete SMS')
    
    sleep(2)
    
    checkAccount(modem)
    sleep(5)
    
    checkBalance(modem)
    sleep(SLEEP_BETWEEN_BALANCE_N_TOPUP)
    
    enablePull()
    pullLoop(modem)
    logger.info('Waiting for SMS message...')    
    try:    
        modem.rxThread.join(2**31) # Specify a (huge) timeout so that it essentially blocks indefinitely, but still receives CTRL+C interrupt signal
    finally:
        modem.close();

if __name__ == '__main__':
    main()