最近在搞一个分布式控制系统,所有控制器通过以太网链接,考虑到系统的方便扩展(将来可能有不同平台的控制器接入到控制网络)以及网络传输的安全性,对通讯内容分进行asn.1编码。这里做一个笔记以便以后偷懒。
首先是安装asn.1编译器,目前的编译器有好几种,这里选用了免费开源的asn1c编译器(http://lionet.info/asn1c/basics.html),步骤如下:
1、下载asn1c的源码(http://lionet.info/asn1c/download.html或者https://github.com/vlm/asn1c)
2、解压源码:tar -zxvf asn1c-0.9.27.tar.gz
3、进入源码目录:cd asn1c-0.9.27/
4、配置:./configure
5、编译:make
6、安装:sudo make install(注意需要管理员权限)
至此安装结束,可以用asn1c命令做一下测试,接下来做一个例子,例子见使用说明文档
1、新建一个rectangle.asn1文件并编辑如下文本:
RectangleTest DEFINITIONS ::=
BEGIN
Rectangle ::= SEQUENCE {
height INTEGER, -- Height of the rectangle
width INTEGER -- Width of the rectangle
}
END
2、对rectangle.asn1进行编译:asn1c -fnative-types rectangle.asn1 ,执行完毕后会在该目录下生成跟编码相关的c语言文件
3、使用eclipse新建一个c工程并将上一步生成的c文件加入到工程中,新建一个main.c,编辑如下代码
#include <stdio.h>#include <sys/types.h>#include <Rectangle.h> /* Rectangle ASN.1 type *//* * This is a custom function which writes the * encoded output into some FILE stream. */static int write_out(const void *buffer, size_t size, void *app_key){ FILE *out_fp = app_key; size_t wrote; wrote = fwrite(buffer, 1, size, out_fp); return (wrote == size) ? 0 : -1;}int main(int ac, char **av){ Rectangle_t *rectangle; /* Type to encode */ asn_enc_rval_t ec; /* Encoder return value */ /* Allocate the Rectangle_t */ rectangle = calloc(1, sizeof(Rectangle_t)); /* not malloc! */ if (!rectangle) { perror("calloc() failed"); exit(71); /* better, EX_OSERR */ } /* Initialize the Rectangle members */ rectangle->height = 42; /* any random value */ rectangle->width = 23; /* any random value */ /* BER encode the data if filename is given */ if (ac < 2) { fprintf(stderr, "Specify filename for BER output\n"); } else { const char *filename = av[1]; FILE *fp = fopen(filename, "wb"); /* for BER output */ if (!fp) { perror(filename); exit(71); /* better, EX_OSERR */ } /* Encode the Rectangle type as BER (DER) */ ec = der_encode(&asn_DEF_Rectangle, rectangle, write_out, fp); fclose(fp); if (ec.encoded == -1) { fprintf(stderr, "Could not encode Rectangle (at %s)\n", ec.failed_type ? ec.failed_type->name : "unknown"); exit(65); /* better, EX_DATAERR */ } else { fprintf(stderr, "Created %s with BER encoded Rectangle\n", filename); } } /* Also print the constructed Rectangle XER encoded (XML) */ xer_fprint(stdout, &asn_DEF_Rectangle, rectangle); return 0; /* Encoding finished successfully */}
4、将编码文件夹中的converter-sample.c文件删除
5、编译运行,Console会打印如下内容:
Specify filename for BER output<Rectangle><height>42</height><width>23</width></Rectangle>
如果需要在arm平台运行的话,直接将工程中的编译器换成交叉编译器即可