client2.py
6.5 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
import logging
import os
import signal
import sys
from pprint import pprint
from threading import Thread
from time import (sleep, )
from iso8583_web.read_conf import (ip_conf)
from iso8583_web.read_conf import (read_conf, name_conf)
from iso8583_web.scripts.forwarder import get_db
from opensipkd.string import (exception_message, dict_to_str, )
from opensipkd.tcp.client import Client as BaseClient
from opensipkd.tcp.connection import (
ConnectionManager as BaseConnectionManager,
join_ip_port,
)
from pyramid.paster import setup_logging
from datetime import datetime
from opensipkd.iso8583.bjb.samsat.banten.doc import Doc
from optparse import OptionParser
from iso8583_web.scripts.forwarder import (
CommonConnection, iso_to_dict, create_thread, Log, parser_threads,
log_info, to_str)
from iso8583_web.scripts.forwarder import (
logs, conn_mgr,)
try:
from configparser import (
ConfigParser,
NoOptionError,
)
except ImportError:
from ConfigParser import (
ConfigParser,
NoOptionError,
)
INQUIRY_CODE = '301099'
def get_option(argv):
# bank = conf.host['streamer'] #'bjb'
pars = OptionParser()
count = 10
pars.add_option('-i', '--invoice-id')
pars.add_option('-c', '--count', default=count, help="Default %s" % count)
option, remain = pars.parse_args(argv)
if not option.invoice_id:
print('--invoice-id harus diisi.')
return
return option
# todo: harus nya diimport saja dari scripts inquiry
def inquiry_request(iso, invoice_id, bank_id=None):
bank_id = bank_id and bank_id or '110'
kini = datetime.now()
iso.setBit(2, kini.strftime('%Y%m%d%H%M%S'))
iso.set_transaction_code(INQUIRY_CODE)
iso.setBit(12, kini.strftime('%H%M%S'))
iso.setBit(13, kini.strftime('%m%d'))
iso.setBit(15, kini.strftime('%m%d'))
iso.setBit(18, '6010')
iso.setBit(22, '021')
iso.setBit(32, bank_id)
iso.setBit(33, bank_id.rjust(5, '0')) # forwarder
iso.setBit(37, kini.strftime('%H%M%S'))
iso.setBit(41, '000')
iso.setBit(42, '000000000000000')
iso.setBit(43, 'Nama Bank')
iso.setBit(49, '390')
iso.setBit(61, invoice_id)
class TestInquiry(object):
def __init__(self, argv, client):
self.option = get_option(argv)
if not self.option:
return
self.invoice_id = self.option.invoice_id.replace('-', '')
# print(name_conf['banten'])
self.conf = name_conf[client]
self.bank_id = 'bank_id' in self.conf and self.conf['bank_id'] or '110'
self.count = self.option.count
def run(self):
if not self.option:
return
# print('\nBank kirim inquiry request')
req_iso = Doc(conf=self.conf)
req_iso.inquiry_request()
inquiry_request(req_iso, self.invoice_id, self.bank_id)
raw = self.get_raw(req_iso)
return raw
def get_raw(self, iso):
msg = 'MTI {mti}'.format(mti=iso.getMTI())
# print(msg)
# pprint(iso_to_dict(iso)) # getBitsAndValues())
raw = iso.getRawIso()
# sleep(1)
# print([raw])
return raw
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri>\n'
'(example: "%s test.ini -i invoice_id [-c count]")' % (cmd, cmd))
sys.exit(1)
def check_connection():
log_info("Check Connection")
for ip_port in ip_conf:
if ip_port in conn_mgr:
index = -1
while True:
index += 1
if not conn_mgr[index:]:
break
this_ip_port, conn = conn_mgr[index]
if this_ip_port != ip_port:
continue
if conn.running:
continue
conn_mgr.remove(index)
break
continue
cfg = ip_conf[ip_port]
if cfg['listen']:
continue
start_client(cfg)
sleep(5)
def check_job():
log_info("Check Job")
for ip_port, connection in conn_mgr:
if not connection.running:
continue
if not connection.is_connected():
continue
iso = connection.job.get_iso()
if not iso:
continue
# connection.log_encode(iso)
raw = iso.getRawIso()
connection.send(raw)
def check_parser():
log_info("Check Parser")
i = -1
while True:
i += 1
if not parser_threads[i:]:
break
parser, thread = parser_threads[i]
if not parser.running:
thread.join()
del parser_threads[i]
i -= 1
iso = {}
import socket, sys, time
BUFFER_SIZE = 1024
import threading
REQUESTS = 100
SLEEP = 1
TIMEOUT = 10
THREADS = 5
threads = []
def receiving(s):
while True:
try:
raw = s.recv(BUFFER_SIZE)
print("Received {} ".format(raw[:30]))
except:
print(sys.exc_info()[0])
break
def sending(s, thrs, test_inquiry ):
i = 0
for i in range(REQUESTS):
raw = test_inquiry.run()
raw = raw + '\x03'
l = str(len(raw)).zfill(4)
raw = l+raw
print("Sending Message Thread {} ke {}: {}".format(thrs, i, raw[:30]))
s.send(raw.encode("ASCII"))
TCP_IP = '127.0.0.1'
TCP_PORT = 8589
def main(argv):
config_uri = argv[1]
setup_logging(config_uri)
conf = read_conf(config_uri)
print(conf)
get_db(conf)
log = logging.getLogger(__file__)
logs.append(log)
# running.append(True)
test_inquiry = TestInquiry(argv, 'banten')
running = True
while running == True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Connecting to {} PORT {}...".format(TCP_IP, TCP_PORT))
s.connect((TCP_IP, TCP_PORT))
s.settimeout(TIMEOUT)
print("Connected!")
# Thread For Receiving Message
thread = threading.Thread(target=receiving, args=[s])
thread.daemon = True
thread.start()
threads.append(thread)
# Thread For Receiving Message
for i in range(THREADS):
thread = threading.Thread(target=sending, args=[s, i, test_inquiry])
thread.daemon = True
thread.start()
threads.append(thread)
running = False
except:
running = False
print(sys.exc_info()[0])
time.sleep(1)
for thread in threads:
thread.join()
if __name__ == '__main__':
main(sys.argv)