PageRenderTime 9ms CodeModel.GetById 1ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/scripts/galaxy_messaging/client/amqp_publisher.py

https://bitbucket.org/cistrome/cistrome-harvard/
Python | 100 lines | 74 code | 13 blank | 13 comment | 10 complexity | 1ccc09850308db26b8220c14019a39fd MD5 | raw file
  1'''
  2This script gets barcode data from a barcode scanner using serial communication
  3and sends the state representated by the barcode scanner & the barcode string
  4to the Galaxy LIMS RabbitMQ server. The message is sent in XML which has 2 tags,
  5barcode & state. The state of the scanner should be set in the galaxy_amq.ini
  6file as a configuration variable.
  7'''
  8
  9import array
 10import ConfigParser
 11import optparse
 12import os
 13import serial
 14import sys
 15import time
 16
 17from galaxy import eggs
 18eggs.require("amqp")
 19
 20import amqp
 21
 22
 23xml = \
 24''' <sample>
 25        <barcode>%(BARCODE)s</barcode>
 26        <state>%(STATE)s</state>
 27        <api_key>%(API_KEY)s</api_key>
 28    </sample>'''
 29
 30
 31def handle_scan(states, amqp_config, barcode):
 32    if states.get(barcode[:2], None):
 33        values = dict( BARCODE=barcode[2:],
 34                       STATE=states.get(barcode[:2]),
 35                       API_KEY=amqp_config['api_key'] )
 36        print values
 37        data = xml % values
 38        print data
 39        conn = amqp.Connection(host=amqp_config['host']+":"+amqp_config['port'],
 40                               userid=amqp_config['userid'],
 41                               password=amqp_config['password'],
 42                               virtual_host=amqp_config['virtual_host'],)
 43
 44        chan = conn.channel()
 45        msg = amqp.Message(data,
 46                           content_type='text/plain',
 47                           application_headers={'msg_type': 'sample_state_update'})
 48        msg.properties["delivery_mode"] = 2
 49        chan.basic_publish(msg,
 50                           exchange=amqp_config['exchange'],
 51                           routing_key=amqp_config['routing_key'])
 52        chan.close()
 53        conn.close()
 54
 55def recv_data(states, amqp_config, s):
 56    while True:
 57        bytes = s.inWaiting()
 58        if bytes:
 59            print '%i bytes recvd' % bytes
 60            msg = s.read(bytes)
 61            print msg
 62            handle_scan(states, amqp_config, msg.strip())
 63
 64
 65def main():
 66    parser = optparse.OptionParser()
 67    parser.add_option('-c', '--config-file', help='config file with all the AMQP config parameters',
 68                      dest='config_file', action='store')
 69    parser.add_option('-p', '--port', help='Name of the port where the scanner is connected',
 70                      dest='port', action='store')
 71    (opts, args) = parser.parse_args()
 72    config = ConfigParser.ConfigParser()
 73    config.read(opts.config_file)
 74    amqp_config = {}
 75    states = {}
 76    for option in config.options("galaxy:amqp"):
 77        amqp_config[option] = config.get("galaxy:amqp", option)
 78    # abort if api_key is not set in the config file
 79    if not amqp_config['api_key']:
 80        print 'Error: Set the api_key config variable in the config file before starting the amqp_publisher script.'
 81        sys.exit( 1 )
 82    count = 1
 83    while True:
 84        section = 'scanner%i' % count
 85        if config.has_section(section):
 86            states[config.get(section, 'prefix')] = config.get(section, 'state')
 87            count = count + 1
 88        else:
 89            break
 90    print amqp_config
 91    print states
 92    s = serial.Serial(int(opts.port))
 93    print 'Port %s is open: %s' %( opts.port, s.isOpen())
 94    recv_data(states, amqp_config, s)
 95    s.close()
 96    print 'Port %s is open: %s' %( opts.port, s.isOpen())
 97
 98
 99if __name__ == '__main__':
100    main()