generate_datatypes.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. from __future__ import print_function
  2. import sys
  3. import time
  4. import platform
  5. import getpass
  6. from collections import OrderedDict
  7. import re
  8. from lxml import etree
  9. import itertools
  10. import argparse
  11. from pprint import pprint
  12. fixed_size = {"UA_Boolean": 1, "UA_SByte": 1, "UA_Byte": 1, "UA_Int16": 2, "UA_UInt16": 2,
  13. "UA_Int32": 4, "UA_UInt32": 4, "UA_Int64": 8, "UA_UInt64": 8, "UA_Float": 4,
  14. "UA_Double": 8, "UA_DateTime": 8, "UA_Guid": 16, "UA_StatusCode": 4}
  15. zero_copy = ["UA_Boolean", "UA_SByte", "UA_Byte", "UA_Int16", "UA_UInt16", "UA_Int32", "UA_UInt32",
  16. "UA_Int64", "UA_UInt64", "UA_Float", "UA_Double", "UA_DateTime", "UA_StatusCode"]
  17. # The order of the builtin-types is not as in the standard. We put all the
  18. # fixed_size types in the front, so they can be distinguished by a simple geq
  19. # comparison. That's ok, since we use the type-index only internally!!
  20. builtin_types = ["UA_Boolean", "UA_SByte", "UA_Byte", # 1 byte
  21. "UA_Int16", "UA_UInt16", # 2 bytes
  22. "UA_Int32", "UA_UInt32", "UA_StatusCode", "UA_Float", # 4 byte
  23. "UA_Int64", "UA_UInt64", "UA_Double", "UA_DateTime", # 8 byte
  24. "UA_Guid", "UA_NodeId", "UA_ExpandedNodeId", "UA_QualifiedName", "UA_LocalizedText", "UA_ExtensionObject", "UA_DataValue", "UA_Variant", "UA_DiagnosticInfo", # fancy types
  25. "UA_String", "UA_ByteString", "UA_XmlElement" # strings (handled as structured types with a single array entry)
  26. ]
  27. excluded_types = ["UA_NodeIdType", "UA_InstanceNode", "UA_TypeNode", "UA_Node", "UA_ObjectNode",
  28. "UA_ObjectTypeNode", "UA_VariableNode", "UA_VariableTypeNode", "UA_ReferenceTypeNode",
  29. "UA_MethodNode", "UA_ViewNode", "UA_DataTypeNode", "UA_ServerDiagnosticsSummaryDataType",
  30. "UA_SamplingIntervalDiagnosticsDataType", "UA_SessionSecurityDiagnosticsDataType",
  31. "UA_SubscriptionDiagnosticsDataType", "UA_SessionDiagnosticsDataType"]
  32. class TypeDescription(object):
  33. def __init__(self, name, nodeid, namespaceid):
  34. self.name = name # without the UA_ prefix
  35. self.nodeid = nodeid
  36. self.namespaceid = namespaceid
  37. def parseTypeDescriptions(filename, namespaceid):
  38. definitions = {}
  39. f = open(filename[0])
  40. input_str = f.read()
  41. f.close()
  42. input_str = input_str.replace('\r','')
  43. rows = map(lambda x:tuple(x.split(',')), input_str.split('\n'))
  44. for index, row in enumerate(rows):
  45. if len(row) < 3:
  46. continue
  47. if row[2] != "DataType":
  48. continue
  49. if row[0] == "BaseDataType":
  50. definitions["UA_Variant"] = TypeDescription(row[0], row[1], namespaceid)
  51. elif row[0] == "Structure":
  52. definitions["UA_ExtensionObject"] = TypeDescription(row[0], row[1], namespaceid)
  53. else:
  54. definitions["UA_" + row[0]] = TypeDescription(row[0], row[1], namespaceid)
  55. return definitions
  56. class BuiltinType(object):
  57. "Generic type without members. Used for builtin types."
  58. def __init__(self, name, description = ""):
  59. self.name = name
  60. self.description = description
  61. def fixed_size(self):
  62. return self.name in fixed_size
  63. def mem_size(self):
  64. return fixed_size[self.name]
  65. def zero_copy(self):
  66. return self.name in zero_copy
  67. def typedef_c(self):
  68. pass
  69. def typelayout_c(self, namespace_0, description, outname):
  70. if description == None:
  71. typeid = "{.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = 0}, "
  72. else:
  73. typeid = "{.namespaceIndex = %s, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = %s}, " % (description.namespaceid, description.nodeid)
  74. return "{.typeId = " + typeid + \
  75. ".memSize = sizeof(" + self.name + "), " + \
  76. ".namespaceZero = UA_TRUE, " + \
  77. ".fixedSize = " + ("UA_TRUE" if self.fixed_size() else "UA_FALSE") + \
  78. ", .zeroCopyable = " + ("UA_TRUE" if self.zero_copy() else "UA_FALSE") + \
  79. ", .isStructure = UA_FALSE" + \
  80. ", .membersSize = 1,\n\t.members = {{.memberTypeIndex = UA_TYPES_" + self.name[3:].upper() + "," + \
  81. ".namespaceZero = UA_TRUE, .padding = 0, .isArray = UA_FALSE }}, " + \
  82. ".typeIndex = %s }" % (outname.upper() + "_" + self.name[3:].upper())
  83. class EnumerationType(object):
  84. def __init__(self, name, description = "", elements = OrderedDict()):
  85. self.name = name
  86. self.description = description
  87. self.elements = elements # maps a name to an integer value
  88. def append_enum(name, value):
  89. self.elements[name] = value
  90. def fixed_size(self):
  91. return True
  92. def mem_size(self):
  93. return 4
  94. def zero_copy(self):
  95. return True
  96. def typedef_c(self):
  97. return "typedef enum { \n " + \
  98. ",\n ".join(map(lambda (key,value) : key.upper() + " = " + value,self.elements.iteritems())) + \
  99. "\n} " + self.name + ";"
  100. def typelayout_c(self, namespace_0, description, outname):
  101. if description == None:
  102. typeid = "{.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = 0}, "
  103. else:
  104. typeid = "{.namespaceIndex = %s, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = %s}, " % (description.namespaceid, description.nodeid)
  105. return "{.typeId = " + typeid + \
  106. ".memSize = sizeof(" + self.name + "), " +\
  107. ".namespaceZero = " + ("UA_TRUE" if namespace_0 else "UA_FALSE") + \
  108. ", .fixedSize = UA_TRUE, .zeroCopyable = UA_TRUE, .isStructure = UA_FALSE, " + \
  109. ".membersSize = 1,\n\t.members = {{.memberTypeIndex = UA_TYPES_INT32," + \
  110. ".namespaceZero = UA_TRUE, .padding = 0, .isArray = UA_FALSE }}, .typeIndex = %s }" % (outname.upper() + "_" + self.name[3:].upper())
  111. def functions_c(self, typeTableName):
  112. return '''#define %s_new (%s*)UA_Int32_new
  113. #define %s_init(p) UA_Int32_init((UA_Int32*)p)
  114. #define %s_delete(p) UA_Int32_delete((UA_Int32*)p)
  115. #define %s_deleteMembers(p) UA_Int32_deleteMembers((UA_Int32*)p)
  116. #define %s_copy(src, dst) UA_Int32_copy((const UA_Int32*)src, (UA_Int32*)dst)
  117. #define %s_calcSizeBinary(p) UA_Int32_calcSizeBinary((UA_Int32*)p)
  118. #define %s_encodeBinary(src, dst, offset) UA_Int32_encodeBinary((UA_Int32*)src, dst, offset)
  119. #define %s_decodeBinary(src, offset, dst) UA_Int32_decodeBinary(src, offset, (UA_Int32*)dst)''' % tuple(itertools.repeat(self.name, 9))
  120. class OpaqueType(object):
  121. def __init__(self, name, description = ""):
  122. self.name = name
  123. self.description = description
  124. def fixed_size(self):
  125. return False
  126. def zero_copy(self):
  127. return False
  128. def typedef_c(self):
  129. return "typedef UA_ByteString " + self.name + ";"
  130. def typelayout_c(self, namespace_0, description, outname):
  131. if description == None:
  132. typeid = "{.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = 0}, "
  133. else:
  134. typeid = "{.namespaceIndex = %s, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = %s}, " % (description.namespaceid, description.nodeid)
  135. return "{.typeId = " + typeid + \
  136. ".memSize = sizeof(" + self.name + "), .fixedSize = UA_FALSE, .zeroCopyable = UA_FALSE, " + \
  137. ".namespaceZero = " + ("UA_TRUE" if namespace_0 else "UA_FALSE") + \
  138. ", .membersSize = 1,\n\t.members = {{.memberTypeIndex = UA_TYPES_BYTESTRING," + \
  139. ".namespaceZero = UA_TRUE, .padding = 0, .isArray = UA_FALSE }}, .typeIndex = %s }" % (outname.upper() + "_" + self.name[3:].upper())
  140. def functions_c(self, typeTableName):
  141. return '''#define %s_new UA_ByteString_new
  142. #define %s_init UA_ByteString_init
  143. #define %s_delete UA_ByteString_delete
  144. #define %s_deleteMembers UA_ByteString_deleteMembers
  145. #define %s_copy UA_ByteString_copy
  146. #define %s_calcSizeBinary UA_ByteString_calcSizeBinary
  147. #define %s_encodeBinary UA_ByteString_encodeBinary
  148. #define %s_decodeBinary UA_ByteString_decodeBinary''' % tuple(itertools.repeat(self.name, 8))
  149. class StructMember(object):
  150. def __init__(self, name, memberType, isArray):
  151. self.name = name
  152. self.memberType = memberType
  153. self.isArray = isArray
  154. class StructType(object):
  155. def __init__(self, name, description, members = OrderedDict()):
  156. self.name = name
  157. self.description = description
  158. self.members = members # maps a name to a member definition
  159. def fixed_size(self):
  160. for m in self.members.values():
  161. if m.isArray or not m.memberType.fixed_size():
  162. return False
  163. return True
  164. def mem_size(self):
  165. total = 0
  166. for m in self.members.values():
  167. if m.isArray:
  168. raise Exception("Arrays have no fixed size!")
  169. else:
  170. total += m.memberType.mem_size()
  171. return total
  172. def zero_copy(self):
  173. for m in self.members.values():
  174. if m.isArray or not m.memberType.zero_copy():
  175. return False
  176. return True
  177. def typedef_c(self):
  178. if len(self.members) == 0:
  179. return "typedef void * " + self.name + ";"
  180. returnstr = "typedef struct {\n"
  181. for name, member in self.members.iteritems():
  182. if member.isArray:
  183. returnstr += " UA_Int32 " + name + "Size;\n"
  184. returnstr += " " + member.memberType.name + " *" +name + ";\n"
  185. else:
  186. returnstr += " " + member.memberType.name + " " +name + ";\n"
  187. return returnstr + "} " + self.name + ";"
  188. def typelayout_c(self, namespace_0, description, outname):
  189. if description == None:
  190. typeid = "{.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = 0}, "
  191. else:
  192. typeid = "{.namespaceIndex = %s, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = %s}, " % (description.namespaceid, description.nodeid)
  193. layout = "{.typeId = "+ typeid + \
  194. ".memSize = sizeof(" + self.name + "), "+ \
  195. ".namespaceZero = " + ("UA_TRUE" if namespace_0 else "UA_FALSE") + \
  196. ", .fixedSize = " + ("UA_TRUE" if self.fixed_size() else "UA_FALSE") + \
  197. ", .zeroCopyable = " + ("sizeof(" + self.name + ") == " + str(self.mem_size()) if self.zero_copy() \
  198. else "UA_FALSE") + \
  199. ", .isStructure = UA_TRUE" + \
  200. ", .typeIndex = " + outname.upper() + "_" + self.name[3:].upper() + \
  201. ", .membersSize = " + str(len(self.members)) + ","
  202. if len(self.members) > 0:
  203. layout += "\n\t.members={"
  204. for index, member in enumerate(self.members.values()):
  205. layout += "\n\t{" + \
  206. ".memberTypeIndex = " + ("UA_TYPES_" + member.memberType.name[3:].upper() if args.namespace_id == 0 or member.memberType.name in existing_types else \
  207. outname.upper() + "_" + member.memberType.name[3:].upper()) + ", " + \
  208. ".namespaceZero = "+ \
  209. ("UA_TRUE, " if args.namespace_id == 0 or member.memberType.name in existing_types else "UA_FALSE, ") + \
  210. ".padding = "
  211. before_endpos = "0"
  212. thispos = "offsetof(%s, %s)" % (self.name, member.name)
  213. if index > 0:
  214. before = self.members.values()[index-1]
  215. before_endpos = "(offsetof(%s, %s)" % (self.name, before.name)
  216. if before.isArray:
  217. before_endpos += " + sizeof(void*))"
  218. else:
  219. before_endpos += " + sizeof(%s))" % before.memberType.name
  220. if member.isArray:
  221. # the first two bytes are padding for the length index, the last three for the pointer
  222. length_pos = "offsetof(%s, %sSize)" % (self.name, member.name)
  223. if index != 0:
  224. layout += "((%s - %s) << 3) + " % (length_pos, before_endpos)
  225. layout += "(%s - sizeof(UA_Int32) - %s)" % (thispos, length_pos)
  226. else:
  227. layout += "%s - %s" % (thispos, before_endpos)
  228. layout += ", .isArray = " + ("UA_TRUE" if member.isArray else "UA_FALSE") + " }, "
  229. layout += "}"
  230. return layout + "}"
  231. def functions_c(self, typeTableName):
  232. return '''#define %s_new() UA_new(%s)
  233. #define %s_init(p) UA_init(p, %s)
  234. #define %s_delete(p) UA_delete(p, %s)
  235. #define %s_deleteMembers(p) UA_deleteMembers(p, %s)
  236. #define %s_copy(src, dst) UA_copy(src, dst, %s)
  237. #define %s_calcSizeBinary(p) UA_calcSizeBinary(p, %s)
  238. #define %s_encodeBinary(src, dst, offset) UA_encodeBinary(src, %s, dst, offset)
  239. #define %s_decodeBinary(src, offset, dst) UA_decodeBinary(src, offset, dst, %s)''' % \
  240. tuple(itertools.chain(*itertools.repeat([self.name, "&"+typeTableName+"[" + typeTableName + "_" + self.name[3:].upper()+"]"], 8)))
  241. def parseTypeDefinitions(xmlDescription, existing_types = OrderedDict()):
  242. '''Returns an ordered dict that maps names to types. The order is such that
  243. every type depends only on known types. '''
  244. ns = {"opc": "http://opcfoundation.org/BinarySchema/"}
  245. tree = etree.parse(xmlDescription)
  246. typeSnippets = tree.xpath("/opc:TypeDictionary/*[not(self::opc:Import)]", namespaces=ns)
  247. types = OrderedDict(existing_types.items())
  248. # types we do not want to autogenerate
  249. def skipType(name):
  250. if name in builtin_types:
  251. return True
  252. if name in excluded_types:
  253. return True
  254. if "Test" in name: # skip all test types
  255. return True
  256. if re.search("NodeId$", name) != None:
  257. return True
  258. return False
  259. def stripTypename(tn):
  260. return tn[tn.find(":")+1:]
  261. def camlCase2CCase(item):
  262. "Member names begin with a lower case character"
  263. return item[:1].lower() + item[1:] if item else ''
  264. def typeReady(element):
  265. "Do we have the member types yet?"
  266. for child in element:
  267. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  268. if stripTypename(child.get("TypeName")) not in types:
  269. return False
  270. return True
  271. def parseEnumeration(typeXml):
  272. name = "UA_" + typeXml.get("Name")
  273. description = ""
  274. elements = OrderedDict()
  275. for child in typeXml:
  276. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  277. description = child.text
  278. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  279. elements[name + "_" + child.get("Name")] = child.get("Value")
  280. return EnumerationType(name, description, elements)
  281. def parseOpaque(typeXml):
  282. name = "UA_" + typeXml.get("Name")
  283. description = ""
  284. for child in typeXml:
  285. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  286. description = child.text
  287. return OpaqueType(name, description)
  288. def parseStructured(typeXml):
  289. "Returns None if we miss member descriptions"
  290. name = "UA_" + typeXml.get("Name")
  291. description = ""
  292. for child in typeXml:
  293. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  294. description = child.text
  295. # ignore lengthfields, just tag the array-members as an array
  296. lengthfields = []
  297. for child in typeXml:
  298. if child.get("LengthField"):
  299. lengthfields.append(child.get("LengthField"))
  300. members = OrderedDict()
  301. for child in typeXml:
  302. if not child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  303. continue
  304. if child.get("Name") in lengthfields:
  305. continue
  306. memberTypeName = "UA_" + stripTypename(child.get("TypeName"))
  307. if not memberTypeName in types:
  308. return None
  309. memberType = types[memberTypeName]
  310. memberName = camlCase2CCase(child.get("Name"))
  311. isArray = True if child.get("LengthField") else False
  312. members[memberName] = StructMember(memberName, memberType, isArray)
  313. return StructType(name, description, members)
  314. finished = False
  315. while(not finished):
  316. finished = True
  317. for typeXml in typeSnippets:
  318. name = "UA_" + typeXml.get("Name")
  319. if name in types or skipType(name):
  320. continue
  321. if typeXml.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  322. t = parseEnumeration(typeXml)
  323. types[t.name] = t
  324. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  325. t = parseOpaque(typeXml)
  326. types[t.name] = t
  327. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  328. t = parseStructured(typeXml)
  329. if t == None:
  330. finished = False
  331. else:
  332. types[t.name] = t
  333. # remove the existing types
  334. for k in existing_types.keys():
  335. types.pop(k)
  336. return types
  337. parser = argparse.ArgumentParser()
  338. parser.add_argument('--ns0-types-xml', nargs=1, help='xml-definition of the ns0 types that are assumed to already exist')
  339. parser.add_argument('--typedescriptions', nargs=1, help='csv file with type descriptions')
  340. parser.add_argument('namespace_id', type=int, help='the id of the target namespace')
  341. parser.add_argument('types_xml', help='path/to/Opc.Ua.Types.bsd')
  342. parser.add_argument('outfile', help='output file w/o extension')
  343. args = parser.parse_args()
  344. outname = args.outfile.split("/")[-1]
  345. inname = args.types_xml.split("/")[-1]
  346. existing_types = OrderedDict()
  347. if args.namespace_id == 0 or args.ns0_types_xml:
  348. existing_types = OrderedDict([(t, BuiltinType(t)) for t in builtin_types])
  349. if args.ns0_types_xml:
  350. OrderedDict(existing_types.items() + parseTypeDefinitions(args.ns0_types_xml[0], existing_types).items())
  351. types = parseTypeDefinitions(args.types_xml, existing_types)
  352. if args.namespace_id == 0:
  353. types = OrderedDict(existing_types.items() + types.items())
  354. typedescriptions = {}
  355. if args.typedescriptions:
  356. typedescriptions = parseTypeDescriptions(args.typedescriptions, args.namespace_id)
  357. fh = open(args.outfile + "_generated.h",'w')
  358. fc = open(args.outfile + "_generated.c",'w')
  359. def printh(string):
  360. print(string, end='\n', file=fh)
  361. def printc(string):
  362. print(string, end='\n', file=fc)
  363. printh('''/**
  364. * @file ''' + outname + '''_generated.h
  365. *
  366. * @brief Autogenerated data types
  367. *
  368. * Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  369. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + '''
  370. */
  371. #ifndef ''' + outname.upper() + '''_GENERATED_H_
  372. #define ''' + outname.upper() + '''_GENERATED_H_
  373. #ifdef __cplusplus
  374. extern "C" {
  375. #endif
  376. #include "ua_types.h" '''
  377. + ('\n#include "ua_types_generated.h"\n' if args.namespace_id != 0 else '') + '''
  378. /**
  379. * @ingroup types
  380. *
  381. * @defgroup ''' + outname + '''_generated Autogenerated ''' + outname + ''' Types
  382. *
  383. * @brief Data structures that are autogenerated from an XML-Schema.
  384. *
  385. * @{
  386. */
  387. ''')
  388. printh("#define " + outname.upper() + "_COUNT %s\n" % (str(len(types))))
  389. printh("extern UA_EXPORT const UA_DataType *" + outname.upper() + ";\n")
  390. i = 0
  391. for t in types.itervalues():
  392. if type(t) != BuiltinType:
  393. printh("")
  394. if t.description != "":
  395. printh("/** @brief " + t.description + " */")
  396. printh(t.typedef_c())
  397. printh("#define " + outname.upper() + "_" + t.name[3:].upper() + " " + str(i))
  398. if type(t) != BuiltinType:
  399. printh(t.functions_c(outname.upper()))
  400. i += 1
  401. printh('''
  402. /// @} /* end of group */\n
  403. #ifdef __cplusplus
  404. } // extern "C"
  405. #endif\n
  406. #endif''')
  407. printc('''/**
  408. * @file ''' + outname + '''_generated.c
  409. *
  410. * @brief Autogenerated data types
  411. *
  412. * Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  413. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + '''
  414. */\n
  415. #include "stddef.h"
  416. #include "ua_types.h"
  417. #include "''' + outname + '''_generated.h"\n
  418. const UA_DataType *''' + outname.upper() + ''' = (UA_DataType[]){''')
  419. for t in types.itervalues():
  420. printc("")
  421. printc("/* " + t.name + " */")
  422. if args.typedescriptions:
  423. td = typedescriptions[t.name]
  424. else:
  425. td = None
  426. printc(t.typelayout_c(args.namespace_id == 0, td, outname) + ",")
  427. printc("};\n")
  428. # if args.typedescriptions:
  429. # printc('const UA_UInt32 *' + outname.upper() + '_IDS = (UA_UInt32[]){')
  430. # for t in types.itervalues():
  431. # print(str(typedescriptions[t.name].nodeid) + ", ", end='', file=fc)
  432. # printc("};")
  433. fh.close()
  434. fc.close()