一、代码框架
1、新建一个4G文件,在把如图所示的4个.c文件放到工程里,加入.h文件路径
2、
2.1 cstring.c包含一些字符串操作函数
2.2 fat_core.c用于实现数据发送给模块
2.3 AXK_MD5.c 用于实现阿里的登录信息的hamcMD5算法
2.4 connet_aliyun.c就是连接阿里云的流程代码实现,包括了一机一密和一型一密。通过全局变量来切换注册方式regesit_mode
3、主函数说明,精简代码如下
int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级
/*继电器控制管教和指示灯管脚初始化*/
IO_Init();
Power_ON_init(); // 开机检测脚和电源使能脚初始化
init_all(); // 变量初始?
uart_init(); //串口初始化为115200
Timer2_Init(99,7199); //定时10ms,作为南华机型粘度检测的计时基准。
reg_fat_uart_send_byte(uart2_send_byte);
read_stmflash();
SysTick_init(10); //滴答定时器10ms中断初始化
while(1)
{
if(HttpConnectFlag == 0)
{
connet_aliyun(regesit_mode);
}
else
{
}
}
}
3.1 定义了定时器2,中断10ms;
3.2 reg_fat_uart_send_byte(uart2_send_byte);//注册用于和模块的通信串口,这里是串口2和模块通信,串口1用于打印日志
3.3 在while主循环中调用连接阿里云函数connet_aliyun(regesit_mode),如果连接上了,就在else语句下添加自己的要实现的发布消息和处理服务器下发的消息
4、连接阿里云流程的代码解析
void connet_aliyun(u8 mode)
{
static int state = MD_RESET;
int ret = 0;
switch (state)
{
//复位模块
case MD_RESET:
if (module_reset())
{
wait_timeout(LTE_POWER_ON_WAIT_TIME);
state = MD_AT_REQ;
}
break;
//AT握手
case MD_AT_REQ:
if (fat_send_wait_cmdres_nonblocking("AT\r\n", 3000))//3s
{
if (fat_cmdres_keyword_matching("OK"))
{
ucErrorTimes = 0;
state = MD_WORK_STA_CHK;
}
else
{
if (ucErrorTimes++ > 30)
{
state = MD_ERR;
}
}
}
break;
//模块状态检测
case MD_WORK_STA_CHK:
ret = module_is_ready();
if (ret == MD_OK)
{
ucErrorTimes = 0;
state = MD_CONNETINIT;
}
else if (ret == MD_ERR)
{
state = MD_FLIGHTMODE;
}
break;
//连接参数初始化
case MD_CONNETINIT:
ret = module_connet_parm_init();
if (ret == MD_OK)
{
state = MD_CONNETED;
}
else if (ret == MD_ERR)
{
state = MD_FLIGHTMODE;
}
break;
//数据通信处理
case MD_CONNETED:
ret = MqttConnect();
if( ret == MD_OK)
{
HttpConnectFlag = 1;
printf("阿里云连接成功\r\n");
}
else if (ret == MD_ERR)
{
HttpConnectFlag = 0;
state = MD_FLIGHTMODE;
}
break;
//飞行模式处理
case MD_FLIGHTMODE:
ret = module_flightmode();
if(ret == MD_WORK_STA_CHK)
{
state = MD_WORK_STA_CHK;
}
else if(ret == MD_ERR)
{
ucFlightModeTimes = 0;
state = MD_ERR;
}
break;
//错误
case MD_ERR:
ucErrorTimes = 0;
state = MD_RESET;
break;
default:
break;
}
}
4.1先复位模块(stm32连接模块的电源使能脚),拉低再拉高,然后等待2S(非阻塞等待)
4.2然后发送AT指令等待应答,调用的函数fat_send_wait_cmdres_nonblocking(或者fat_send_wait_cmdres_blocking),函数原型
* @description: 发送命令后,开启定时计数,在设置的定时时间到达后返回1,用户此时可以进行对命令的响应结果进行处理
* @param cmd:要发送的命令
* @param timeoutval:定时时间
* @return 0:未到达定时时间,1:定时时间到达
*/
int fat_send_wait_cmdres_blocking(char *cmd, unsigned short int timeoutval)
{
/* 发送命令,开启定时计数 */
if (ucTimeOutStartFlg == 0)
{
FAT_DBGPRT_INFO("uart send: %s\r\n",cmd);
fat_uart_clean();
fat_uart_send_str((unsigned char *)cmd);
usTimeOutVal = timeoutval / FAT_TIMER_VAL;
ucTimeOutStartFlg = 1;
}