Python Astm
Python Astm
Python Astm
Release 0.5.1-dev
Alexander Shorin
8 Changelog 31
8.1 Release 0.5 (2013-03-16) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
8.2 Release 0.4.1 (2013-02-01) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
8.3 Release 0.4 (2013-02-01) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
8.4 Release 0.3 (2012-12-15) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
8.5 Release 0.2 (2012-12-11) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
8.6 Release 0.1 (2012-12-09) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
9 Licence 33
i
ii
astm Documentation, Release 0.5.1-dev
Contents:
Contents 1
astm Documentation, Release 0.5.1-dev
2 Contents
CHAPTER 1
3
astm Documentation, Release 0.5.1-dev
astm.codec.decode(data, encoding=’latin-1’)
Common ASTM decoding function that tries to guess which kind of data it handles.
If data starts with STX character (0x02) than probably it is full ASTM message with checksum and other
system characters.
If data starts with digit character (0-9) than probably it is frame of records leading by his sequence number.
No checksum is expected in this case.
Otherwise it counts data as regular record structure.
Note, that data should be bytes, not unicode string even if you know his encoding.
Parameters
• data (bytes) – ASTM data object.
• encoding (str) – Data encoding.
Returns List of ASTM records with unicode data.
Return type list
astm.codec.decode_component(field, encoding)
Decodes ASTM field component.
astm.codec.decode_frame(frame, encoding)
Decodes ASTM frame: list of records followed by sequence number.
astm.codec.decode_message(message, encoding)
Decodes complete ASTM message that is sent or received due communication routines. It should contains
checksum that would be additionally verified.
Parameters
• message (bytes) – ASTM message.
• encoding (str) – Data encoding.
Returns
Tuple of three elements:
• int frame sequence number.
• list of records with unicode data.
• bytes checksum.
Raises
5
astm Documentation, Release 0.5.1-dev
7
astm Documentation, Release 0.5.1-dev
9
astm Documentation, Release 0.5.1-dev
11
astm Documentation, Release 0.5.1-dev
13
astm Documentation, Release 0.5.1-dev
The socket must not already be bound. The format of address depends on the address family — re-
fer to the socket documentation for more information. To mark the socket as re-usable (setting the
SO_REUSEADDR option), call the Dispatcher object’s set_reuse_addr() method.
close()
Close the socket.
All future operations on the socket object will fail. The remote end-point will receive no more data (after
queued data is flushed). Sockets are automatically closed when they are garbage-collected.
connect(address)
As with the normal socket object, address is a tuple with the first element the host to connect to, and the
second the port number.
create_socket(family, type)
This is identical to the creation of a normal socket, and will use the same options for creation. Refer to the
socket documentation for information on creating sockets.
handle_accept()
Called on listening channels (passive openers) when a connection can be established with a new remote
endpoint that has issued a connect() call for the local endpoint.
handle_close()
Called when the socket is closed.
handle_connect()
Called when the active opener’s socket actually makes a connection. Might send a “welcome” banner, or
initiate a protocol negotiation with the remote endpoint, for example.
handle_error()
Called when an exception is raised and not otherwise handled. The default version prints a condensed
traceback.
handle_write()
Called when the asynchronous loop detects that a writable socket can be written. Often this method will
implement the necessary buffering for performance. For example:
def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
listen(num)
Listen for connections made to the socket.
The num argument specifies the maximum number of queued connections and should be at least 1; the
maximum value is system-dependent (usually 5).
readable()
Called each time around the asynchronous loop to determine whether a channel’s socket should be added
to the list on which read events can occur. The default method simply returns True, indicating that by
default, all channels will be interested in read events.
recv(buffer_size)
Read at most buffer_size bytes from the socket’s remote end-point.
An empty string implies that the channel has been closed from the other end.
send(data)
Send data to the remote end-point of the socket.
writable()
Called each time around the asynchronous loop to determine whether a channel’s socket should be added
to the list on which write events can occur. The default method simply returns True, indicating that by
default, all channels will be interested in write events.
class astm.asynclib.AsyncChat(sock=None, map=None)
This class is an abstract subclass of Dispatcher. To make practical use of the code you must subclass
AsyncChat, providing meaningful meth:found_terminator method. The Dispatcher methods can be used,
although not all make sense in a message/response context.
Like Dispatcher, AsyncChat defines a set of events that are generated by an analysis of socket conditions
after a select() call. Once the polling loop has been started the AsyncChat object’s methods are called by
the event-processing framework with no action on the part of the programmer.
close_when_done()
Automatically close this channel once the outgoing queue is empty.
discard_buffers()
In emergencies this method will discard any data held in the input and output buffers.
flush()
Sends all data from outgoing queue.
found_terminator()
Called when the incoming data stream matches the termination condition. The default method, which
must be overridden, raises a NotImplementedError exception. The buffered input data should be
available via an instance attribute.
pull(data)
Puts data into incoming queue. Also available by alias collect_incoming_data.
push(data)
Pushes data on to the channel’s fifo to ensure its transmission. This is all you need to do to have the channel
write the data out to the network.
readable()
Predicate for inclusion in the readable for select()
writable()
Predicate for inclusion in the writable for select()
15
astm Documentation, Release 0.5.1-dev
class astm.server.BaseRecordsDispatcher(encoding=None)
Abstract dispatcher of received ASTM records by RequestHandler. You need to override his handlers or
extend dispatcher for your needs. For instance:
class Dispatcher(BaseRecordsDispatcher):
17
astm Documentation, Release 0.5.1-dev
# etc handlers
After defining our dispatcher, we left only to let Server use it:
server = Server(dispatcher=Dispatcher)
on_comment(record)
Comment record handler.
on_header(record)
Header record handler.
on_order(record)
Order record handler.
on_patient(record)
Patient record handler.
on_result(record)
Result record handler.
on_terminator(record)
Terminator record handler.
on_unknown(record)
Fallback handler for dispatcher.
class astm.server.RequestHandler(sock, dispatcher, timeout=None)
ASTM protocol request handler.
Parameters
• sock – Socket object.
• dispatcher (BaseRecordsDispatcher) – Request handler records dispatcher in-
stance.
• timeout (int) – Number of seconds to wait for incoming data before connection closing.
on_timeout()
Closes connection on timeout.
class astm.server.Server(host=’localhost’, port=15200, request=None, dispatcher=None, time-
out=None, encoding=None)
Asyncore driven ASTM server.
Parameters
• host (str) – Server IP address or hostname.
that collecting all records for single session may take some time and server may reject data
by timeout reason.
Type dict
close()
Closes the emitter. Acts in same way as close() for generators.
send(value=None)
Passes value to the emitter. Semantically acts in same way as send() for generators.
If the emitter has any value within local buffer the returned value will be extracted from it unless value is
False.
Parameters value (bool) – Callback value. True indicates that previous record was success-
fully received and accepted by server, False signs about his rejection.
Returns Next record data to send to server.
Return type bytes
state_machine
alias of RecordsStateMachine
throw(exc_type, exc_val=None, exc_tb=None)
Raises exception inside the emitter. Acts in same way as throw() for generators.
If the emitter had catch an exception and return any record value, it will be proceeded in common way.
Based on:
file LABONLINE - HOST connection specifications
author Giuseppe Iannucci
revision 2
date 2011-05-31
23
astm Documentation, Release 0.5.1-dev
• action_code (str) – Action code. Required. Possible values: - None: normal order
result; - Q: quality control;
• danger_code (None) – Danger code. Not used.
• clinical_info (None) – Revelant clinical info. Not used.
• delivered_at (None) – Date/time specimen received.
• biomaterial (str) – Sample material code. Length: 20.
• physician (None) – Ordering Physician. Not used.
• physician_phone (None) – Physician’s phone number. Not used.
• user_field_1 (str) – An optional field, it will be send back unchanged to the host along
with the result. Length: 20.
• user_field_2 (str) – An optional field, it will be send back unchanged to the host along
with the result. Length: 1024.
• laboratory_field_1 (None) – Laboratory field #1. Not used.
• laboratory_field_2 (str) – Primary tube code. Length: 12.
• modified_at (None) – Date and time of last result modification. Not used.
• instrument_charge (None) – Instrument charge to computer system. Not used.
• instrument_section (None) – Instrument section id. Not used.
• report_type (str) – Report type. Always F which means final order request.
• reserved (None) – Reserved. Not used.
• location_ward (None) – Location ward of specimen collection. Not used.
• infection_flag (None) – Nosocomial infection flag. Not used.
• specimen_service (None) – Specimen service. Not used.
• laboratory (None) – Production laboratory. Not used.
class astm.omnilab.server.Result(*args, **kwargs)
ASTM patient record.
Parameters
• type (str) – Record Type ID. Always R.
• seq (int) – Sequence Number. Required.
• test (Test) – Test information structure (aka Universal Test ID).
• value (None) – Measurement value. Numeric, coded or free text value depending on result
type. Required. Length: 1024.
• units (str) – Units. Length: 20.
• references (str) – Normal reference value interval.
• abnormal_flag (str) – Result abnormal flag. Possible values: - 0: normal result; - 1:
result out of normal values; - 2: result out of attention values; - 3: result out of panic values;
+10 Delta-check; +1000 Device alarm. Length: 4.
• abnormality_nature (str) – Nature of abnormality testing. Possible values: - N: nor-
mal value; - L: below low normal range; - H: above high normal range; - LL: below low
critical range; - HH: above high critical range.
• status (str) – Result status. F indicates a final result; R indicating rerun. Length: 1.
• normatives_changed_at (None) – Date of changes in instrument normative values or
units. Not used.
• operator (Operator) – Operator ID.
• started_at (datetime.datetime) – When works on test was started on.
• completed_at (datetime.datetime) – When works on test was done.
• instrument (Instrument) – Instrument ID. Required.
class astm.omnilab.server.Terminator(*args, **kwargs)
ASTM terminator record.
Parameters
• type (str) – Record Type ID. Always L.
• seq (int) – Sequential number. Always 1.
• code (str) – Termination code. Always N.
Changelog
• Rewrite emitter for Client: replace mystic sessions that hides some detail with explicit need of yielding Header
and Terminator records;
• Fix emitter usage with infinity loop;
• Use timer based on scheduled tasks instead of threading.Timer;
• Remove internal states routine;
• Improve overall stability;
• Client now able to send data by chunks and with bulk mode, sending all records with single message;
• Code cleanup;
• Fix astm.codec module: now it only decodes bytes to unicode and encodes unicode to bytes;
• Add records dispatcher for server request handler;
• Add session support for astm client emitter;
• Repeat ENQ on timeout;
• Code cleanup and refactoring;
• Set minimal Python version to 2.6, but 3.2-3.3 also works well.
31
astm Documentation, Release 0.5.1-dev
• Fork, mix and refactor asyncore/asynchat modules to astm.asynclib module which provides more suitable meth-
ods to implement asynchronous operations for our task;
• Implement ASTM client and server that handles common protocol routines.
32 Chapter 8. Changelog
CHAPTER 9
Licence
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
astm Documentation, Release 0.5.1-dev
34 Chapter 9. Licence
CHAPTER 10
• genindex
• modindex
• search
35
astm Documentation, Release 0.5.1-dev
a
astm.asynclib, 13
astm.client, 19
astm.codec, 5
astm.constants, 3
astm.mapping, 9
astm.omnilab.client, 23
astm.omnilab.server, 26
astm.protocol, 17
astm.records, 11
astm.server, 17
37
astm Documentation, Release 0.5.1-dev
D I
DateField (class in astm.mapping), 9 IntegerField (class in astm.mapping), 9
DateTimeField (class in astm.mapping), 9 is_chunked_message() (in module astm.codec), 6
DecimalField (class in astm.mapping), 9 iter_encode() (in module astm.codec), 6
decode() (in module astm.codec), 5
decode_component() (in module astm.codec), 5 J
decode_frame() (in module astm.codec), 5 join() (in module astm.codec), 7
decode_message() (in module astm.codec), 5
39
astm Documentation, Release 0.5.1-dev
N S
send() (astm.asynclib.Dispatcher method), 14
NotUsedField (class in astm.mapping), 9
send() (astm.client.Emitter method), 21
O serve_forever() (astm.server.Server method), 19
Server (class in astm.server), 18
on_ack() (astm.client.Client method), 20 SetField (class in astm.mapping), 9
on_ack() (astm.protocol.ASTMProtocol method), 17 split() (in module astm.codec), 7
on_comment() (astm.server.BaseRecordsDispatcher state_machine (astm.client.Emitter attribute), 21
method), 18
on_enq() (astm.client.Client method), 20 T
on_enq() (astm.protocol.ASTMProtocol method), 17
Terminator (class in astm.omnilab.client), 26
on_eot() (astm.client.Client method), 20
Terminator (class in astm.omnilab.server), 29
on_eot() (astm.protocol.ASTMProtocol method), 17
TextField (class in astm.mapping), 10
on_header() (astm.server.BaseRecordsDispatcher
throw() (astm.client.Emitter method), 21
method), 18
TimeField (class in astm.mapping), 10
on_message() (astm.client.Client method), 20
on_message() (astm.protocol.ASTMProtocol method), 17
on_nak() (astm.client.Client method), 20
W
on_nak() (astm.protocol.ASTMProtocol method), 17 writable() (astm.asynclib.AsyncChat method), 15
on_order() (astm.server.BaseRecordsDispatcher method), writable() (astm.asynclib.Dispatcher method), 14
18
on_patient() (astm.server.BaseRecordsDispatcher
method), 18
on_result() (astm.server.BaseRecordsDispatcher
method), 18
on_terminator() (astm.server.BaseRecordsDispatcher
method), 18
on_timeout() (astm.client.Client method), 20
on_timeout() (astm.protocol.ASTMProtocol method), 17
on_timeout() (astm.server.RequestHandler method), 18
on_unknown() (astm.server.BaseRecordsDispatcher
method), 18
Order (class in astm.omnilab.client), 25
Order (class in astm.omnilab.server), 27
P
Patient (class in astm.omnilab.client), 23
Patient (in module astm.omnilab.server), 27
pull() (astm.asynclib.AsyncChat method), 15
push() (astm.asynclib.AsyncChat method), 15
R
readable() (astm.asynclib.AsyncChat method), 15
readable() (astm.asynclib.Dispatcher method), 14
Record (class in astm.mapping), 9
RecordsDispatcher (class in astm.omnilab.server), 27
recv() (astm.asynclib.Dispatcher method), 14
40 Index