shimatta_kenkyusho_print_label.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. #!/bin/python
  2. import shimatta_label.storage_label
  3. import shimatta_label.component_label
  4. import shimatta_label.brother_ql_wrapper as ql_wrapper
  5. import sys
  6. import requests
  7. import urllib.parse
  8. import getpass
  9. import json
  10. import re
  11. MICE_TOILET_TEMPLATE = 'https://parts.shimatta.net/api/v1/parts/storages/075acbaf-ed60-47b9-9bd5-98bfbc3a79ea/'
  12. SMD_STRAP_PAGE_TEMPLATE = 'https://parts.shimatta.net/api/v1/parts/storages/4df58899-7338-48f5-9d93-cf5a59a6a400/'
  13. def get_child_storages(storage_query_url, token, uuid, expected_amount):
  14. # get children
  15. query_res = requests.get(storage_query_url, headers={'Authorization': f'Token {token}'}, params={'parent_storage':uuid, 'expand_stocks': True})
  16. if query_res.status_code != 200:
  17. print('Request for children unsuccessful')
  18. sys.exit(-3)
  19. storage_json = query_res.json()
  20. if storage_json['count'] != expected_amount:
  21. print('Storage json does not contain correct amount of storage entries')
  22. sys.exit(-1)
  23. # pagination
  24. storage_list = storage_json['results']
  25. while storage_json['next']:
  26. query_res = requests.get(storage_json['next'], headers={'Authorization': f'Token {token}'}, params={'parent_storage':uuid})
  27. storage_json = query_res.json()
  28. storage_list.extend(storage_json['results'])
  29. return {storage['name']: storage for storage in storage_list}
  30. def get_component_print_name(comp):
  31. '''
  32. Generates a human readeable string from the parameters depending on the type
  33. '''
  34. param_dict = {param['ro_parameter_type']: param for param in comp['ro_parameters']}
  35. if comp['ro_component_type'] in ['Resistor', 'Resistor NTC']:
  36. resistor_value = param_dict['Resistance']['value']
  37. if resistor_value >= 10e8:
  38. comp_name = f'{int(resistor_value / 10e8)}G{str(int(resistor_value % 10e8)).rstrip('0')}'
  39. elif resistor_value >= 10e5:
  40. comp_name = f'{int(resistor_value / 10e5)}M{str(int(resistor_value % 10e5)).rstrip('0')}'
  41. elif resistor_value >= 10e2:
  42. comp_name = f'{int(resistor_value / 10e2)}K{str(int(resistor_value % 10e2)).rstrip('0')}'
  43. elif resistor_value >= 1.0:
  44. comp_name = f'{int(resistor_value)}R{str(round(resistor_value % 1, 6))[2:].rstrip('0')}'
  45. elif resistor_value == 0.0:
  46. comp_name = '0R'
  47. else:
  48. comp_name = f'R{str(round(resistor_value % 1, 6))[2:]}'
  49. if comp['ro_component_type'] == 'Resistor NTC':
  50. comp_name += ' NTC'
  51. if param_dict['Resistor technology']['text_value'] == 'laser trim':
  52. comp_name += ' L'
  53. else:
  54. print(f'Unknown component type: {comp['ro_component_type']}')
  55. return None
  56. return comp_name
  57. def char_range(c1, c2):
  58. """Generates the characters from `c1` to `c2`, exclusive."""
  59. for c in range(ord(c1), ord(c2)):
  60. yield chr(c)
  61. def handle_storage_qr_code(base_url, token, uuid):
  62. storage_query_url = urllib.parse.urljoin(base_url, 'api/v1/parts/storages/')
  63. query_res = requests.get(storage_query_url, headers={'Authorization': f'Token {token}'}, params={'id':uuid})
  64. if query_res.status_code != 200:
  65. print('Request unsuccessful')
  66. sys.exit(-3)
  67. print('Storage found: ')
  68. storage_json = query_res.json()
  69. if storage_json['count'] != 1:
  70. print('Storage json does not contain correct amount of storage entries')
  71. sys.exit(-1)
  72. storage = storage_json['results'][0]
  73. print(f'ID: {storage["id"]}')
  74. print(f'Path: {storage["full_path"]}')
  75. labels = []
  76. if storage['template'] == MICE_TOILET_TEMPLATE:
  77. side = input('Select type to be printed (top, bottom, storage) [t,b,s]:')
  78. if side not in ['t', 'b', 's']:
  79. print('Error - invalid side')
  80. return None
  81. if side == 's':
  82. label = shimatta_label.storage_label.StorageLabelSmdMiceToilet()
  83. storage = storage_json['results'][0]
  84. label.put_content(f'[stor_uuid]{storage["id"]}',
  85. storage['full_path'],
  86. storage['verbose_name'])
  87. return [label]
  88. row = input('Select which row shall be printed [1..3]:')
  89. if row not in char_range('1', '4'):
  90. print('Error - invalid row')
  91. return None
  92. row = int(row)
  93. storage_dict = get_child_storages(storage_query_url, token, uuid, 24)
  94. if side == 'b':
  95. for column in char_range('a','i'):
  96. label = shimatta_label.storage_label.StorageLabelSmdMiceToiletBottomQR()
  97. field_uuid = storage_dict[f'{column}{row}']['id']
  98. label.put_content(f'[stor_uuid]{field_uuid}')
  99. labels.append(label)
  100. elif side == 't':
  101. for column in char_range('a','i'):
  102. label = shimatta_label.storage_label.StorageLabelSmdMiceToiletTop()
  103. if not storage_dict[f'{column}{row}']['ro_stocks']:
  104. print("Only printing start of row!!!")
  105. break
  106. comp = storage_dict[f'{column}{row}']['ro_stocks'][0]['ro_component']
  107. param_dict = {param['ro_parameter_type']: param for param in comp['ro_parameters']}
  108. comp_name = get_component_print_name(comp)
  109. if not comp_name:
  110. return[]
  111. label.put_content(comp_name,
  112. f"{param_dict['Tolerance']['value']}% {comp['package_data']['name']}",
  113. comp['ro_manufacturer_name'])
  114. labels.append(label)
  115. elif storage['template'] == SMD_STRAP_PAGE_TEMPLATE:
  116. type = input('Select type to be printed (components, storage) [c,s]:')
  117. if type not in ['c', 's']:
  118. print('Error - invalid type')
  119. return None
  120. if type == 's':
  121. label = shimatta_label.storage_label.StorageLabelSmdStrap()
  122. label.put_content(f'[stor_uuid]{uuid}', storage['full_path'], storage['verbose_name'])
  123. labels.append(label)
  124. return [label]
  125. storage_dict = get_child_storages(storage_query_url, token, uuid, 12)
  126. for row in range(1,13):
  127. label = shimatta_label.component_label.StorageComponentLabelSmdBook()
  128. if not storage_dict[f'{row}']['ro_stocks']:
  129. print("Only printing start of column!!!")
  130. break
  131. storage_uuid = storage_dict[f'{row}']['id']
  132. stock_uuild = storage_dict[f'{row}']['ro_stocks'][0]['id']
  133. comp = storage_dict[f'{row}']['ro_stocks'][0]['ro_component']
  134. param_dict = {param['ro_parameter_type']: param for param in comp['ro_parameters']}
  135. comp_name = get_component_print_name(comp)
  136. if not comp_name:
  137. return[]
  138. label.put_content(f'[stor_uuid]{storage_uuid}',
  139. f'[stck_uuid]{stock_uuild}',
  140. comp_name,
  141. f"{param_dict['Tolerance']['value']}% {comp['package_data']['name']}",
  142. comp['ro_manufacturer_name'])
  143. labels.append(label)
  144. pass
  145. else:
  146. label = shimatta_label.storage_label.StorageLabel()
  147. label.put_content(f'[stor_uuid]{uuid}', storage['full_path'], storage['verbose_name'])
  148. labels.append(label)
  149. return labels
  150. def handle_component_qr_code(base_url, token, uuid):
  151. query_url = urllib.parse.urljoin(base_url, 'api/v1/parts/components/')
  152. query_res = requests.get(query_url, headers={'Authorization': f'Token {token}'}, params={'id': uuid})
  153. if query_res.status_code != 200:
  154. print('Request unsuccessful')
  155. sys.exit(-3)
  156. component = json.loads(query_res.content)
  157. if component['count'] != 1:
  158. sys.exit(-1)
  159. component = component['results'][0]
  160. pkg = ''
  161. name = component['name']
  162. if component.get('package_data') is not None:
  163. pkg = component['package_data']['name']
  164. manufacturer = component.get('ro_manufacturer_name')
  165. if manufacturer is None:
  166. manufacturer = ''
  167. print(f'Component found: Name: {name}, Package: {pkg}, Manufacturer: {manufacturer}')
  168. labels = []
  169. label = shimatta_label.component_label.ComponentLabelSmall()
  170. comp_name = get_component_print_name(component)
  171. if not comp_name:
  172. return[]
  173. label.put_content(f'[comp_uuid]{uuid}', comp_name, manufacturer, pkg)
  174. labels.append(label)
  175. return labels
  176. if len(sys.argv) < 2:
  177. print(f'Usage: {sys.argv[0]} <shimatta kenkyusho url>')
  178. sys.exit(-1)
  179. qr_re = re.compile(r'^\[(?P<prefix>[a-zA-Z_]+)\](?P<uuid>[a-fA-F0-9\-]+)')
  180. kenkyusho_url = sys.argv[1]
  181. print(f"Shimatta Kenkyusho instance: {kenkyusho_url}")
  182. login_url = urllib.parse.urljoin(kenkyusho_url, 'api/v1/token-auth/')
  183. print(f'Token auth url: {login_url}')
  184. username = input('Username: ')
  185. password = getpass.getpass()
  186. ans = requests.post(login_url, data= {'username': username, 'password': password})
  187. if ans.status_code != 200:
  188. print(f'Got status code {ans.status_code}')
  189. sys.exit(-1)
  190. login_token = json.loads(ans.content)['token']
  191. while True:
  192. qr = input('Please scan Storage or Component QR: ')
  193. try:
  194. matches = qr_re.match(qr)
  195. if matches.group('prefix') == 'stor_uuid' :
  196. labels = handle_storage_qr_code(kenkyusho_url, login_token, matches.group('uuid'))
  197. elif matches.group('prefix') == 'comp_uuid':
  198. labels = handle_component_qr_code(kenkyusho_url, login_token, matches.group('uuid'))
  199. else:
  200. print('Invalid QR code!')
  201. continue
  202. if labels:
  203. ql_wrapper.print_labels(labels)
  204. except Exception as ex:
  205. print("Something went wrong:", ex)