CAN模块的自动代码生成(Python实现)(2)代码文件

CAN模块的自动代码生成(Python实现)(2)代码文件

2016.08.06

生成的代码大概是下面的样子

/* 文件名: unpack.c
   作者:   fc
   时间:   2016-08-04
   说明:   .......
 */

#include "include.h"

unpack_0x0C00000B(data)
{
    int tmp;

    busCurr = (float)(data[0] + data[1] * 256) * 0.1 - 3200;
    busVolt = (float)(data[2] + data[3] * 256) * 0.1;

    mainRlyRb = data[7] & 0x01;
}

代码源文件有以下几部分组成:

  • 文件头:包含文件名、作者、时间、文件说明等
  • 文件引用
  • 函数

建立以下几个类

FileHead()
FileInclud()
FuncEle()
FuncBody()
SourceFile()

将函数中的代码由多个元素ele组成,每个元素都由注释和指令组成。为了添加注释方便,建立了一个生成注释的类。

其中SourceFile类,有一个GetStr方法可以返回此代码文件的字符串,其它的每一个类都有一个GetList方法,返回一个列表,列表中的每个元素表示一行代码。在最后才生成字符串是为了统一计算代码缩进。当然,CAN模块的代码缩进只有一级,所以比较简单。

# fileclass.py
import time

class CommentStr(object):
    def __init__(self, commStr = None):
        self._str = commStr
    def GetStr(self):
        return '// ' + self._str

class FileHead(object):
    def __init__(self, filename = '', author = 'pk', descrip = ''):
        self._filename = filename
        self._author = author
        self._time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        self._descrip = descrip
    def AddProperty(self, filename = '', author = 'pk', descrip = ''):
        self._filename = filename
        self._author = author
        self._descrip = descrip
    def GetList(self):
        tmplist = []
        tmplist.append(CommentStr('file name   :' + self._filename).GetStr())
        tmplist.append(CommentStr('author      :' + self._author).GetStr())
        tmplist.append(CommentStr('time        :' + self._time).GetStr())
        tmplist.append(CommentStr('description :' + self._descrip).GetStr())
        return tmplist

class FileInclud(object):
    def __init__(self, filelist = []):
        self._filelist = filelist
        self._comment = CommentStr('files include')
    def AddProperty(self, filelist):
        self._filelist = filelist
    def GetList(self):
        tmplist = []
        tmplist.append(self._comment.GetStr())
        if self._filelist:
            for fl in self._filelist:
                tmplist.append('#include ' + '"' + fl + '"')
        return tmplist

class FuncEle(object):
    def __init__(self, elecomment = ['element comment'], elebody = []):
        self._elecomm = elecomment
        self._elebody = elebody
    def AddComment(self, comm):
        self._elecomm = comm 
    def AddBody(self,bd):
        self._elebody = bd
    def GetList(self, inden = 4):
        tmplist = []
        for li in self._elecomm:
            tmplist.append(' ' * inden + '// ' + li)
        if self._elebody:
            for li in self._elebody:
                tmplist.append(' ' * inden + li)
            # return tmplist
        tmplist[-1] += '\n'
        return tmplist

class FuncBody(object):
    def __init__(self):
        self._para = 'void'
        self._eles = []
    def AddFuncName(self, name):
        self._name = name
    def AddFuncComment(self, commstr):
        self._comment = CommentStr(commstr).GetStr()
    def AddFuncPara(self, Arg):        
        self._para = Arg
    def AddFuncEle(self, ele):
        self._eles.append(ele)
    def GetList(self, inden = 4):
        tmplist = []
        # function comment
        tmplist.append(self._comment)
        # function name
        tmplist.append('void ' + self._name + '(' + self._para + ')')
        tmplist.append('{')
        # function elements
        for li in self._eles:
            tmplist.extend(li.GetList(inden))
        tmplist[-1] = tmplist[-1][:-1]  # delete '\n' of the last element
        # function end
        tmplist.append('}')
        return tmplist

class SourceFile(object):
    def __init__(self):
        self._indentationNum = 4    
        self._filehead = FileHead()
        self._fileinclude = FileInclud()
        self._funclist = []
    def AddFilehead(self, filename = '', author = 'pk', descrip = ''):
        self._filehead.AddProperty(filename, author, descrip)
    def AddFileInclude(self, filelist):
        self._fileinclude.AddProperty(filelist)
    def AddFunc(self, func):
        self._funclist.append(func)
    def GetStr(self):
        tmpstr = ''
        # file head
        tmpstr += '\n'.join(self._filehead.GetList()) + '\n\n'
        # file include
        tmpstr += '\n'.join(self._fileinclude.GetList()) + '\n\n'
        # functions
        for func in self._funclist:
            tmpstr += '\n'.join(func.GetList(self._indentationNum)) + '\n\n'
        # file end
        tmpstr += '// file end: ' + self._filehead._filename
        return tmpstr

写段代码测试一下:

def test():
    sf = SourceFile()
    sf.AddFilehead('main.c','pk','ok')
    sf.AddFileInclude(['stdio.h', 'math.h'])

    f1 = FuncBody()
    f1.AddFuncComment('f1')
    f1.AddFuncName('unpack0x1313FF01')
    f1.AddFuncPara('char* data, int num')
    f1.AddFuncEle(FuncEle(['temp variable'], ['uint32_T utmp;','int32_T itmp;']))
    f1.AddFuncEle(FuncEle(['signalname', 'startbit','leng'], ['busvolt = data[0];']))
    sf.AddFunc(f1)

    f2 = FuncBody()
    f2.AddFuncComment('f2')
    f2.AddFuncName('unpack0x1313FF01')
    f2.AddFuncPara('char* data, int num')
    f2.AddFuncEle(FuncEle(['temp variable'], ['uint32_T utmp;','int32_T itmp;']))
    f2.AddFuncEle(FuncEle(['signalname', 'startbit','leng'], ['busvolt = data[0];']))
    sf.AddFunc(f2)

    print sf.GetStr()

if __name__ == '__main__':
    test()

输出:

$ python fileclass.py
// file name   :main.c
// author      :pk
// time        :2016-08-06 11:00:07
// description :ok

// files include
#include "stdio.h"
#include "math.h"

// f1
void unpack0x1313FF01(char* data, int num)
{
    // temp variable
    uint32_T utmp;
    int32_T itmp;

    // signalname
    // startbit
    // leng
    busvolt = data[0];
}

// f2
void unpack0x1313FF01(char* data, int num)
{
    // temp variable
    uint32_T utmp;
    int32_T itmp;

    // signalname
    // startbit
    // leng
    busvolt = data[0];
}

// file end: main.c

转载于:https://www.cnblogs.com/fallcolor/p/5743567.html

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值