Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# -*- coding: utf-8 -*- 

2from __future__ import unicode_literals 

3import string 

4import datetime 

5import random 

6import logging 

7 

8logger = logging.getLogger(__file__) 

9 

10 

11def ishl7(line): 

12 """Determines whether a *line* looks like an HL7 message. 

13 This method only does a cursory check and does not fully 

14 validate the message. 

15 

16 :rtype: bool 

17 """ 

18 # Prevent issues if the line is empty 

19 return line and (line.strip()[:3] in ['MSH']) or False 

20 

21 

22def isfile(line): 

23 """ 

24 Files are wrapped in FHS / FTS 

25 FHS = file header segment 

26 FTS = file trailer segment 

27 """ 

28 return line and (line.strip()[:3] in ['FHS']) or False 

29 

30 

31def split_file(hl7file): 

32 """ 

33 Given a file, split out the messages. 

34 Does not do any validation on the message. 

35 Throws away batch and file segments. 

36 """ 

37 rv = [] 

38 for line in hl7file.split('\r'): 

39 line = line.strip() 

40 if line[:3] in ['FHS', 'BHS', 'FTS', 'BTS']: 

41 continue 

42 if line[:3] == 'MSH': 

43 newmsg = [line] 

44 rv.append(newmsg) 

45 else: 

46 if len(rv) == 0: 

47 logger.error('Segment received before message header [%s]', line) 

48 continue 

49 rv[-1].append(line) 

50 rv = ['\r'.join(msg) for msg in rv] 

51 for i, msg in enumerate(rv): 

52 if not msg[-1] == '\r': 

53 rv[i] = msg + '\r' 

54 return rv 

55 

56 

57alphanumerics = string.ascii_uppercase + string.digits 

58 

59 

60def generate_message_control_id(): 

61 """Generate a unique 20 character message id. 

62 

63 See http://www.hl7resources.com/Public/index.html?a55433.htm 

64 """ 

65 d = datetime.datetime.utcnow() 

66 # Strip off the decade, ID only has to be unique for 3 years. 

67 # So now we have a 16 char timestamp. 

68 timestamp = d.strftime("%y%j%H%M%S%f")[1:] 

69 # Add 4 chars of uniqueness 

70 unique = ''.join(random.sample(alphanumerics, 4)) 

71 return timestamp + unique