Python Code Generators

By | January 3, 2016

When confronted by large, repetitive and tedious coding tasks it’s often better to actually write code generators. I’ve written several Python scripts for code generation for different projects and every time it has been totally worthwhile.

The entire communications system used by Firetail UAV is automatically generated. Every single piece of information that is transferred between the autopilot and ground station must be packed and unpacked into a data structure. I found this to be incredibly tedious and a big source of bugs, so I wrote a code generator that reads information about the packets from an XML file and does the hard work for me. If I ever want to add a new feature to the autopilot all I need to do is add the new packet to the XML file, run the script and the communications code is built for me!

I then noticed that settings were a bit of an issue, in that every time I added a new feature or function that required settings, I would have to update the code that reads/writes settings. Well, every setting must be transferred to the autopilot from the ground station, so it makes sense that the communications code generator should also generate code for settings too! So, I went through and added a <setting/> tag to each relevant structure in the XML file and modified the code generator to build settings read/write code too.

This has freed me from heaps of mundane coding work. I can focus on value-adding features rather than grinding through boring code and fretting over silly bugs.

ETK contains a file called conversions.h. It’s purpose is to provide a bunch of inline functions that perform conversions between units of measurement ( like turning meters into feet ). conversions.h was in a pretty pathetic state and I hardly had the patience to maintain it. So, again, I wrote a quick little Python script that generates all the functions for me. All I have to do is enter the SI base unit ( e.g. meters ) and list all the other units for that measurement with their conversion gains in an XML file. The generator then turns 50-odd lines of easily maintainable XML into over 300 lines of C++.

The next time you are losing your mind to boredom and your wrists to RSI, consider scripting something to do the work for you. Very very nifty, Python is.


Leave a Reply

Your email address will not be published. Required fields are marked *