Esempio n. 1
0
int main(void)
{
// Must include this line in all programs using "cm530.h/.c"
	SysInit();

	while(1)
	{
		// Reset the LEDs
		SetLED(TXD, 0);
		SetLED(RXD, 0);
		SetLED(AUX, 0);

		SetLED(MANAGE, 0);
		SetLED(PROGRAM, 0);
		SetLED(PLAY, 0);

		mDelay(1000);

		SetLED(TXD, 1);
		SetLED(RXD, 1);
		SetLED(AUX, 1);

		SetLED(MANAGE, 1);
		SetLED(PROGRAM, 1);
		SetLED(PLAY, 1);

		mDelay(1000);
	}

	return 0;
}
/**
  * @brief  MQTT协议测试主循环
  * @retval None
  **/
void MQTT_Loop(void)
{
    static int timeout_count = 0;
    int publish_state = 0;
    int exit = 0;
    int j = 0;
    /*初始化MQTT上下文,在该api内部配置了设备ID等信息*/
    if(MqttSample_Init(smpctx) < 0)
    {
        return;
    }
    printf("\r\ndevice id:%s\r\n", MQTT_DEVICE_ID);
    printf("we publish topic:%s %s %s\r\n",DS_TO_PUBLISH,DS_TO_PUBLISH_T,DS_TO_PUBLISH_RH);
    printf("connect to mqtt server\r\n");
    /*发送MQTT连接请求报文*/
    MqttSample_CmdConnect(smpctx);
		printf("\r\n");
    mDelay(2000);
    Mqtt_RecvPkt(smpctx->mqttctx);
    mDelay(2000);
    /*发送MQTT订阅topic报文*/
    MqttSample_CmdSubscribe(smpctx);//开机订阅
		printf("\r\n");
    mDelay(2000);
    Mqtt_RecvPkt(smpctx->mqttctx);
    printf("begin loop\n");
    /*进入主循环*/
    while(!exit)
    {
        j++;
        if(j == 3)
        {
            //MqttSample_CmdPublish(smpctx,TIME_OUT);
            /*周期性发布温湿度和一个状态数据,状态每次取反*/
            publish_state = MqttSample_CmdPublishNormal(smpctx, TIME_OUT);
            if(publish_state < 0)
            {
                timeout_count++;
                if(timeout_count == 5)
                {
                    timeout_count = 0;
                    /*you can do some thing*/
                }
            }
            j = 0;
        }
        if(Mqtt_RecvPkt(smpctx->mqttctx)<0)
				{
					 smpctx->publish_state=0;
				}
				printf("\r\n");
        mDelay(100);
    }
    /*reclaim the resource防止内存泄露*/
    MqttBuffer_Destroy(smpctx->mqttbuf);
    Mqtt_DestroyContext(smpctx->mqttctx);
    printf("bye...\n");
    return;
}
/*
 *  @brief  发送PING包维持心跳
 */
void Ping_Server(void)
{
    EdpPacket *send_pkg;
    printf("%s %d\n", __func__, __LINE__);
    /* 组装ping包 */
    send_pkg = PacketPing();

    DoSend(0, (const uint8_t *)send_pkg->_data,
           send_pkg->_write_pos);
    mDelay(500);
    /* 必须释放这个内存,否则造成泄露 */
    DeleteBuffer(&send_pkg);
    mDelay(100);
}
Esempio n. 4
0
int main(void)
{
    uint16_t temp, humi;    //温湿度
    char HTTP_Buf[400];     //HTTP报文缓存区
    char tempStr[5];       //字符串格式温度
    char humiStr[5];       //字符串格式湿度
    int len;

    USART1_Config();        //USART1作为调试串口
    USART2_Config();        //USART2用于连接ESP8266模块
    Hal_I2C_Init();			//I2C初始化,用于连接温湿度传感器

    ESP8266_Init();         //ESP8266初始化
		printf("ESP8266 init over\r\n");
    //SHT20_loop();         //
	
    while(1)
    {
        /* 获取温湿度 */
        SHT2x_MeasureHM(SHT20_Measurement_T_HM, &temp);
        mDelay(500);
        SHT2x_MeasureHM(SHT20_Measurement_RH_HM, &humi);

        /* 转化为字符串形式 */
        sprintf(tempStr, "%d", temp);
        sprintf(humiStr, "%d", humi);

        //printf("%s   %s\r\n", tempStr, humiStr);

        USART2_Clear();
        len = HTTP_PostPkt(HTTP_Buf, API_KEY, DEV_ID, "temp", tempStr); //HTTP组包
        USART2_Write(USART2, (unsigned char *)(HTTP_Buf), len);			//报文发送
        printf("send HTTP msg:\r\n%s\r\n", HTTP_Buf);

        mDelay(1000);
        printf("rcv response:\r\n%s\r\n", usart2_rcv_buf);

        USART2_Clear();
        len = HTTP_PostPkt(HTTP_Buf, API_KEY, DEV_ID, "humi", humiStr); //HTTP组包
        USART2_Write(USART2, (unsigned char *)(HTTP_Buf), len);			//报文发送
        printf("send HTTP msg:\r\n%s\r\n", HTTP_Buf);

        mDelay(1000);
        printf("rcv response:\r\n%s\r\n", usart2_rcv_buf);

        mDelay(5000);
    }
}
/*
 *  @brief  EDP协议向Onenet上传湿度信息,数据点格式TYPE=3
 */
void Save_HumToOneNet(void)
{
    EdpPacket* send_pkg;
    uint16_t hum[1];
    SHT20_read_user_reg();
    mDelay(200);//延迟,设备没有那么快的响应时间,否则总线处理忙等待
    SHT2x_MeasureHM(SHT20_Measurement_RH_NHM, hum);

    printf("%s %d hum:%d\n", __func__, __LINE__, (uint32_t)hum[0]);

    send_pkg = PacketSavedataInt(kTypeSimpleJsonWithoutTime, NULL, "hum", (uint32_t)hum[0], 0, NULL);

    DoSend(0, (const uint8_t *)send_pkg->_data, send_pkg->_write_pos);
    DeleteBuffer(&send_pkg);
    mDelay(1000);
}
/**
  * @brief  通过USART2连接ESP8266发送数据.
  * @param  buf: 要发送的数据缓冲区地址
    * @param  len: 要发送的数据缓长度
  * @retval 发送的数据长度
  **/
uint32_t ESP8266_SendData(int8_t * buf, uint32_t len)
{
    memset(usart2_rcv_buf, 0, strlen(usart2_rcv_buf));
    usart2_rcv_len = 0;
    USART2_Write(USART2, buf, len);
    mDelay(100);
}
Esempio n. 7
0
/**
  * @brief  通过USART2连接MT6311发送数据.
  * @param  buf: 要发送的数据缓冲区地址
    * @param  len: 要发送的数据缓长度
  * @retval 发送的数据长度
  **/
int32_t M6311_SendData(uint8_t * buf,uint32_t len)
{
	int32_t ret=0,i=0;
	memset(usart2_rcv_buf,0,strlen(usart2_rcv_buf));
	usart2_rcv_len=0;
	USART2_Write(USART2,buf,len);	
	mDelay(20);	
}
Esempio n. 8
0
/**
  * @brief  通过USART2连接MT6311发送数据.
  * @param  buf: 要发送的数据缓冲区地址
    * @param  len: 要发送的数据缓长度
  * @retval 发送的数据长度
  **/
int32_t M6311_SendData(uint8_t * buf,uint32_t len)
{
	memset(usart2_rcv_buf,0,strlen((const char *)usart2_rcv_buf));
	usart2_rcv_len=0;
	USART2_Write(USART2,buf,len);	
	mDelay(20);	
	return len;
}
Esempio n. 9
0
void USART_Configuration(u8 PORT, u32 baudrate)
{

	USART_InitTypeDef USART_InitStructure;

	USART_StructInit(&USART_InitStructure);


	USART_InitStructure.USART_BaudRate = baudrate;
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;
	USART_InitStructure.USART_StopBits = USART_StopBits_1;
	USART_InitStructure.USART_Parity = USART_Parity_No ;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;


	if( PORT == USART_DXL )
	{
		USART_DeInit(USART1);
		mDelay(10);
		/* Configure the USART1 */
		USART_Init(USART1, &USART_InitStructure);

		/* Enable USART1 Receive and Transmit interrupts */
		USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
		//USART_ITConfig(USART1, USART_IT_TC, ENABLE);

		/* Enable the USART1 */
		USART_Cmd(USART1, ENABLE);
	}

	else if( PORT == USART_PC )
	{
		USART_DeInit(USART3);
		mDelay(10);
		/* Configure the USART3 */
		USART_Init(USART3, &USART_InitStructure);

		/* Enable USART3 Receive and Transmit interrupts */
		//USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
		//USART_ITConfig(USART3, USART_IT_TC, ENABLE);

		/* Enable the USART3 */
		USART_Cmd(USART3, ENABLE);
	}
}
Esempio n. 10
0
/*
 *  @brief USART2串口发送AT命令用
 *  @para  cmd  AT命令
 *  @para  result 预期的正确返回信息
 *  @para  timeOut延时时间,ms
 */
void SendCmd(char* cmd, char* result, int timeOut)
{
    while(1)
    {
        USART2_Clear();
        USART2_Write(USART2, (uint8_t *)cmd, strlen(cmd));
        mDelay(timeOut);
        printf("%s %d cmd:%s,rsp:%s\n", __func__, __LINE__, cmd, usart2_rcv_buf);
        if((NULL != strstr((const char *)usart2_rcv_buf, (const char *)result)))	//判断是否有预期的结果
        {
            break;
        }
        else
        {
            mDelay(100);
        }
    }
}
Esempio n. 11
0
main()     
{   
    uchar i,j;   
    while(1)   
    {   
        out=0;   
        for(i=100;i<250;i++)   
        {      
            mDelay(250);   
            mDelay(100);   
			mDelay(250); 
			mDelay(250); 

            for(j=0;j<10;j++)   
                send(0);   
            send(i);   
        }   
    }      
}  
Esempio n. 12
0
/*
 *  @brief  EDP协议向自己透传数据,用于测试,将src_dev替换成目标DEVICE ID即可
 */
void Push_DataToMyself(void)
{
    EdpPacket* send_pkg;
    int8_t push_data[] = {44};
    printf("%s %d\n", __func__, __LINE__);
    send_pkg = PacketPushdata(src_dev, push_data, sizeof(push_data));
    DoSend(0, (const uint8_t *)send_pkg->_data, send_pkg->_write_pos);
    DeleteBuffer(&send_pkg);
    mDelay(1000);
}
Esempio n. 13
0
/*
 *  @brief USART2串口发送AT命令用
 */
void SendCmd(int8_t* cmd, int8_t* result, int32_t timeOut)
{
    while(1)
    {
        memset(usart2_rcv_buf, 0, strlen((const char *)usart2_rcv_buf));
        usart2_rcv_len = 0;

        USART2_Write(USART2, (uint8_t*)cmd, strlen((const char *)cmd));
        mDelay(timeOut);
        printf("%s %d cmd:%s,rsp:%s\n", __func__, __LINE__, cmd, usart2_rcv_buf);
        if((NULL != strstr((const char *)usart2_rcv_buf, (const char *)result)))
        {
            break;
        }
        else
        {
            mDelay(100);
        }
    }
}
Esempio n. 14
0
int main(void)
{
    USART1_Init();
    USART2_Init();
    mDelay(1000);
    Hal_I2C_Init();
    /*初始化8266,并连接CWJAP配置的AP,与MQTT_CIPSTART配置的服务器建立TCP连接*/
    ESP8266_Init((int8_t *)MQTT_CIPSTART, (int8_t *)CWJAP);
    /*进入MQTT协议测试主循环*/
    MQTT_Loop();
}
Esempio n. 15
0
void ADXL345_init(void)
{
    uint8_t data_fmt_val = 0;
    uint8_t pw_ctl = 0x28, ret = 0;
    uint8_t int_en = 0x00;
    uint8_t devid;

    //0 ±16g,13位模式
#define DATA_FORMAT_REG  0x31
    //0x08 测量模式
#define POWER_CTL                0x2d
    //0x80 使能DATA_READY中断,需要吗,需要禁止的吧。
#define INT_ENABLE       0x2e
#define BW_RATE 0x2c
#define OFSX 0x1e
#define OFSY 0x1f
#define OFSZ 0x20
    mDelay(20);
    Hal_I2C_ByteRead(I2C2, ADXL345_ADDRESS, 0x00, &devid);
    printf("\r\ndevice ID=%x,\r\n", devid);
#if 0
    mDelay(500);
    Hal_I2C_ByteWrite(I2C2, ADXL345_ADDRESS, POWER_CTL, &pw_ctl); //链接使能,测量模式
    mDelay(2000);
#endif
    ret = 0X2B;
    Hal_I2C_ByteWrite(I2C2, ADXL345_ADDRESS, DATA_FORMAT_REG, &ret); //低电平中断输出,13位全分辨率,输出数据右对齐,16g量程
    ret = 0x0A;
    Hal_I2C_ByteWrite(I2C2, ADXL345_ADDRESS, BW_RATE, &ret); //数据输出速度为100Hz
    ret = 0x28;
    Hal_I2C_ByteWrite(I2C2, ADXL345_ADDRESS, POWER_CTL, &ret);    //链接使能,测量模式
    ret = 0x00;
    Hal_I2C_ByteWrite(I2C2, ADXL345_ADDRESS, INT_ENABLE, &ret);     //不使用中断
    ret = 0x00;
    Hal_I2C_ByteWrite(I2C2, ADXL345_ADDRESS, OFSX, &ret);
    ret = 0x00;
    Hal_I2C_ByteWrite(I2C2, ADXL345_ADDRESS, OFSY, &ret);
    ret = 0x00;
    Hal_I2C_ByteWrite(I2C2, ADXL345_ADDRESS, OFSZ, &ret);
    mDelay(500);
}
Esempio n. 16
0
/*
 *  @brief  EDP协议向Onenet上传温湿度信息,使用简单字符串格式,数据点格式TYPE=5,FEILD type 2.
 */
void Save_TempHumToOneNet(void)
{
    EdpPacket* send_pkg;
    uint16_t hum[1], temperature[1];
    int8_t data_string[64] = ",;temperature,%d;hum,%d", data_string_dst[64];

    SHT20_read_user_reg();
    mDelay(200);//延迟,设备没有那么快的响应时间,否则总线处理忙等待
    SHT2x_MeasureHM(SHT20_Measurement_RH_NHM, hum);
    mDelay(200);
    SHT2x_MeasureHM(SHT20_Measurement_T_HM, temperature);
    printf("%s %d hum:%d\n", __func__, __LINE__, (uint32_t)hum[0]);
    printf("%s %d t:%d\n", __func__, __LINE__, (uint32_t)temperature[0]);
    snprintf(data_string_dst, sizeof(data_string), data_string, (uint32_t)temperature[0], (uint32_t)hum[0]);
    printf("%s %d t:%s\n", __func__, __LINE__, data_string_dst);
    send_pkg = PacketSavedataSimpleString(NULL, data_string_dst);

    DoSend(0, (const uint8_t *)send_pkg->_data, send_pkg->_write_pos);
    DeleteBuffer(&send_pkg);
    mDelay(1000);
}
static int MqttSample_RecvPkt(unsigned char *buf)
{
    int bytes;
    int timeout = 200;

    int i = 0;

    while(1)
    {
        mDelay(100);
        bytes = USART2_GetRcvNum();
        //USART2_GetRcvData(buf, bytes);
        if(bytes > 0)
        {
					  mDelay(50);
						bytes = USART2_GetRcvNum();
						USART2_GetRcvData(buf, bytes);
            break;
        }
        if(timeout == 0)
        {

            break;
        }
        timeout--;
    }
    printf("bytes=%d\n", bytes);
    if(bytes > 0)
    {
        printf("\r\n----------\r\n");
        for(i = 0; i < bytes; i++)
        {
            printf("0x%x ", ((unsigned char *)buf)[i]);
        }
        printf("\r\n----------\r\n");
    }
    return bytes;
}
Esempio n. 18
0
void ESP8266_Init(int8_t * server, int8_t * ssid_pwd)
{
    SendCmd(AT, "OK", 1000); /*进入AT命令模式*/
    SendCmd(CWMODE, "OK", 1000);
    SendCmd(RST, "OK", 2000);   /*重置模组式*/
    SendCmd(CIFSR, "OK", 1000); /*查询设备IP,可放在需要的位置*/
    SendCmd(ssid_pwd, "OK", 2000);  /*配置要连接的路由器SSID和密码*/
    SendCmd(server, "OK", 2000); /*与服务器建立TCP连接*/
    SendCmd(CIPMODE, "OK", 1000); /*透传模式*/
    memset(usart2_rcv_buf, 0, strlen(usart2_rcv_buf)); /*先清除接收缓冲区*/
    usart2_rcv_len = 0;
    USART2_Write(USART2, CIPSEND, strlen(CIPSEND)); /*开始透传*/
    mDelay(500);
    if((NULL != strstr(usart2_rcv_buf, "ERROR")))
    {
        return;
    }
}
Esempio n. 19
0
void RGBLEDs::blinkRGB(uint8_t _led_number, uint8_t _red_code, uint8_t _green_code, uint8_t _blue_code){
    if(_led_number < 1 or _led_number > 3){
        printf("Wrong LED selection...\n");
        return;
//        return;
    }
//    if(leds_status[_led_number-1] == 0x00){
        rgbCode[0] = (uint16_t)(_red_code*pwmRatio);
        rgbCode[1] = (uint16_t)(_green_code*pwmRatio);
        rgbCode[2] = (uint16_t)(_blue_code*pwmRatio);
        pwmModule->setPWM((uint8_t)((_led_number - 1)*3),(uint8_t)3,rgbCode);
        mDelay(1000);
        ledOff(_led_number);
//        leds_status[_led_number-1] = 0x01;
//    }else{
//        ledOff(_led_number);
//        leds_status[_led_number-1] = 0x00;
//    }
}
Esempio n. 20
0
void Connect_RequestType1(int8_t *devid, int8_t *api_key)
{
    EdpPacket *send_pkg;

    send_pkg = PacketConnect1((const int8_t *)devid, (const int8_t *)api_key);
    if(send_pkg == NULL)
    {
        return;
    }
    /* send_pkg = PacketConnect2("433223", "{ \"SYS\" : \"0DEiuApATHgLurKNEl6vY4bLwbQ=\" }"); */
    /* send_pkg = PacketConnect2("433223", "{ \"13982031959\" : \"888888\" }"); */

    /* 向设备云发送连接请求 */
    printf("send connect to server, bytes: %d\n", send_pkg->_write_pos);
    DoSend(0, (const uint8_t *)send_pkg->_data, send_pkg->_write_pos);
    /* 必须释放这个内存,否则造成泄露 */
    DeleteBuffer(&send_pkg);
    mDelay(1000);
}
Esempio n. 21
0
void Save_AllSensorsToOneNet(void)
{
    EdpPacket* send_pkg;
    uint16_t f;
    uint16_t hum[1], temperature[1];
    int16_t adxl[3], hmc5883l[3];
    /*读取温湿度*/
    memset(data_string_dst, 0, sizeof(data_string_dst));
    SHT20_read_user_reg();
    mDelay(200);//延迟,设备没有那么快的响应时间,否则总线处理忙等
    SHT2x_MeasureHM(SHT20_Measurement_T_HM, temperature);
    mDelay(1000);
    SHT2x_MeasureHM(SHT20_Measurement_RH_HM, hum);
    mDelay(400);
    f = (uint16_t)Read_BH1750();
    snprintf(data_string_t, sizeof(data_string_t), ",;BH1750FVI,%d;SHT20_temperature,%d;SHT20_hum,%d;", (uint16_t)f, (uint16_t)temperature[0], (uint16_t)hum[0]);
    /*读取BH1750FVI*/
    printf("%s\n", data_string_t);
    mDelay(400);
    /*读取ADXL345*/
    ADXL345_GETXYZ(adxl);
    snprintf(data_string_adxl, sizeof(data_string_adxl), "ADXL345_x,0x%x;ADXL345_y,0x%0x;ADXL345_z,0x%x;", (uint16_t)adxl[0], (uint16_t)adxl[1], (uint16_t)adxl[2]);
    printf("%s\n", data_string_adxl);
    mDelay(400);
    /*读取HMC588CL*/
    HMC5883L_GetXYZ(hmc5883l);

    snprintf(data_string_hmc5883l, sizeof(data_string_hmc5883l), "HMC5883L_x,0x%x;HMC5883L_y,0x%x;HMC5883L_z,0x%x", (uint16_t)hmc5883l[0], (uint16_t)hmc5883l[2], (uint16_t)hmc5883l[1]);
    printf("%s\n", data_string_hmc5883l);
    strcat(data_string_dst, data_string_t);
    strcat(data_string_dst, data_string_adxl);
    strcat(data_string_dst, data_string_hmc5883l);
    printf("%s\n", data_string_dst);
    send_pkg = PacketSavedataSimpleString(NULL, data_string_dst);

    DoSend(0, (const uint8_t *)send_pkg->_data, send_pkg->_write_pos);
    DeleteBuffer(&send_pkg);
    mDelay(1000);
}
Esempio n. 22
0
/*
 *  @brief  EDP协议测试主循环
 */
void EDP_Loop(void)
{

    mDelay(2000);
    while(1)
    {
        Connect_RequestType1(src_dev, src_api_key);
        mDelay(1000);
        mDelay(1000);
        mDelay(1000);
        mDelay(1000);
        printf("%s %d\n", __func__, __LINE__);
        Recv_Thread_Func();
        mDelay(1000);
        mDelay(1000);
#if 0
        Ping_Server();
        printf("%s %d\n", __func__, __LINE__);
        Recv_Thread_Func();
        mDelay(1000);
        Save_TemperatueToOneNet();
        mDelay(1000);
        Recv_Thread_Func();
        mDelay(1000);
        Save_HumToOneNet();
        mDelay(1000);
        Recv_Thread_Func();
        mDelay(1000);
        Save_TempHumToOneNet();
#endif
        Save_AllSensorsToOneNet();
        mDelay(1000);
        Recv_Thread_Func();
        mDelay(1000);
    }
}
Esempio n. 23
0
void M6311_Init(void)
{	 
		mDelay(2000);	
		mDelay(2000);
	  SendCmd("AT+SSYS?\r\n","OK",300);
		mDelay(500);
	  SendCmd("AT+SIM1\r\n","OK",300);
		mDelay(500);
	  SendCmd("AT+CPIN?\r\n", "+CPIN: READY",1000); //确保SIM卡PIN码解锁,返回READY,表示解锁成功
		mDelay(1500);
		SendCmd("AT+CREG?\r\n","0,5",1000);    //确认网络搜索成功,OK
		mDelay(1000);
		SendCmd("AT+CSQ\r\n","OK", 1000);//查看信号质量
		mDelay(1000);
		//SendCmd(CGDCONT,"OK", 1000);//
		//Delay(1000);
		SendCmd("AT+CGACT=1,1\r\n","OK", 1000);//激活
		mDelay(1000);
		SendCmd("AT+CGATT=1\r\n","OK", 1000);  //
		mDelay(1000);
		SendCmd("AT+CMMUX=0\r\n","OK", 1000);  //single way
	  mDelay(1000);
	  SendCmd("AT+CMMODE=1\r\n","OK",1000);   //配置透传
		mDelay(1000);
	  SendCmd("AT+CMTCFG=1,1024,1\r\n","OK",1000);   //配置透传,最大长度2000字节,间隔是100ms。配置成hex模式
		mDelay(1500);	
		//SendCmd("AT+IPSTART=\"TCP\",\"183.230.40.33\",80\r\n","CONNECT",1000); //连接EDP服务器
		SendCmd("AT+IPSTART=\"TCP\",\"183.230.40.39\",876\r\n","CONNECT",3000);//AT+IPSTART="TCP","183.230.40.39",876
	  mDelay(1000);
}
Esempio n. 24
0
int main(void)
{

	byte bCount;
	long lTemp;

	System_Configuration();

	dxl_set_power(OFF);
	//dxl_set_power(ON);
	Zigbee_SetState(ON);
	//gbDxlPwr = ON;

	//LED_SetState(LED_POWER, ON);
	//	LED_RGB_SetState(LED_R|LED_G|LED_B);
	//LED_RGB_SetState(OFF);

	BufferClear(USART_DXL);
	BufferClear(USART_PC);
	BufferClear(USART_ZIGBEE);

	setBuzzerOff();

/*
	for(bCount =0; bCount < 50; bCount++ )
	{
		setBuzzerData(bCount);
		setBuzzerPlayLength(10);
		PlayBuzzer();
		//mDelay(3000);
		while(getBuzzerState());
		mDelay(500);
	}
*/


/*
	//BKP_WriteBackupRegister((P_OPERATING_MODE+1)<<2, 0xffff);

	  if(BKP_ReadBackupRegister((P_OPERATING_MODE+1)<<2) == 0xffff) //Initialize to Factory Default or reset mode restart
	  {
	    for(bCount=0; bCount < ROM_CONTROL_TABLE_LEN; bCount++)
	    {
	        //ROM_CAST(bCount) = gbpControlTable[bCount] = ROM_INITIAL_DATA[bCount];
	    	gbpControlTable[bCount] = ROM_INITIAL_DATA[bCount];
	        BKP_WriteBackupRegister((bCount+1)<<2, WORD_CAST(gbpControlTable[bCount]));
	    }
	    gbLEDBlinkCounter = 32;
	  }
	  else
	  {
	    for(bCount=0; bCount < ROM_CONTROL_TABLE_LEN; bCount++)
	    {
	      //gbpControlTable[bCount] = (byte)(BKP_ReadBackupRegister((bCount+1)<<2)); !!!!!
	      gbpControlTable[bCount] = ROM_INITIAL_DATA[bCount];
	    }
	    gbLEDBlinkCounter = 8;
	  }

	for (bCount = 0; bCount < 3; bCount++) {
		LED_SetState(LED_MANAGE|LED_EDIT|LED_PLAY, ON);
		mDelay(50);
		LED_SetState(LED_MANAGE|LED_EDIT|LED_PLAY, OFF);
		mDelay(50);
	}
*/
	/*
	if( (EEPROM_Read(P_OPERATING_MODE) == 0xffff) || (EEPROM_Read(P_OPERATING_MODE) == 0xff) ) //Initialize to Factory Default or reset mode restart
	{
		EEPROM_Write( P_BAUD_RATE, ROM_INITIAL_DATA[P_BAUD_RATE] );
		EEPROM_Write( P_OPERATING_MODE, 0);
	}
	else if(EEPROM_Read(P_OPERATING_MODE) == 0x11) //Digital Reset
	{
		EEPROM_Write( P_BAUD_RATE, ROM_INITIAL_DATA[P_BAUD_RATE] );
		EEPROM_Write( P_OPERATING_MODE, 0);
	}
	*/


	for(bCount=0; bCount < ROM_CONTROL_TABLE_LEN; bCount++)
	{
		  gbpControlTable[bCount] = ROM_INITIAL_DATA[bCount];
	}
	//GB_BAUD_RATE = EEPROM_Read(P_BAUD_RATE);
/*
	lTemp = 2000000;
	lTemp /= (GB_BAUD_RATE+1);
	USART_Configuration(USART_DXL,lTemp);
	USART_Configuration(USART_PC,lTemp);
*/


    gbLEDBlinkCounter = 8;





	for (bCount = 0; bCount < 3; bCount++) {
		LED_SetState(LED_MANAGE|LED_EDIT|LED_PLAY, ON);
		mDelay(50);
		LED_SetState(LED_MANAGE|LED_EDIT|LED_PLAY, OFF);
		mDelay(50);
	}
/*
	dxl_set_power(1);
	gbDxlPwr = 1;
	mDelay(100);

	GPIO_ResetBits(PORT_ENABLE_RXD, PIN_ENABLE_RXD);	// RX Disable
	GPIO_SetBits(PORT_ENABLE_TXD, PIN_ENABLE_TXD);	// TX Enable
	  while(1)
	  {
		GPIO_ResetBits(PORT_ENABLE_RXD, PIN_ENABLE_RXD);	// RX Disable
		GPIO_SetBits(PORT_ENABLE_TXD, PIN_ENABLE_TXD);	// TX Enable

		  USART_SendData(USART1, 'a');
			while( USART_GetFlagStatus(USART1, USART_FLAG_TC)==RESET );

			GPIO_ResetBits(PORT_ENABLE_TXD, PIN_ENABLE_TXD);	// TX Disable
			GPIO_SetBits(PORT_ENABLE_RXD, PIN_ENABLE_RXD);	// RX Enable
			mDelay(100);

	  }

*/

	Process();

	while(1);

}
/**
  * @brief 周期性发布数据,暂时没有使用,因为采用JSON发布,前端暂时不支持Json显示,但可以正常发布
  * @param  ctx:上下文变量
  * @retval ret:0,成功,<0 失败
  **/
static int MqttSample_CmdPublish(struct MqttSampleContext *ctx)
{
    uint8_t cause = 0; //only for test
    int err = 0;
    int bytes = 0;
    static unsigned char count = 0;
    int64_t ts = 0; //no time
    uint16_t temprature[1], rh[1];
    printf("%s %d,count=%d,cause=%d\n", __func__, __LINE__, count, cause);
    // ts = (int64_t)time(NULL) * 1000;

    SHT2x_MeasureHM(SHT20_Measurement_RH_HM, temprature);
    mDelay(1500);
    SHT2x_MeasureHM(SHT20_Measurement_T_HM, rh);

    err |= Mqtt_PackDataPointStart(ctx->mqttbuf, 1, MQTT_QOS_LEVEL2, 0, 1);
    if((count == 0) || (cause == EVENT))
    {
        err |= Mqtt_AppendDPStartObject(ctx->mqttbuf, DS_TO_PUBLISH, ts);
        if(cause == TIME_OUT)
        {
            ir_state = !ir_state;
        }
        if(ir_state == 0x1)
        {
            err |= Mqtt_AppendDPSubvalueString(ctx->mqttbuf, DS_TO_PUBLISH, "设备在位");
        }
        else if(ir_state == 0)
        {
            err |= Mqtt_AppendDPSubvalueString(ctx->mqttbuf, DS_TO_PUBLISH, "设备离位");
        }
        else
        {
            err |= Mqtt_AppendDPSubvalueString(ctx->mqttbuf, DS_TO_PUBLISH, "未知初始状态");
        }
        if(count != 2)
        {
            count++;
        }
    }
    else if(count == 1)
    {
        err |= Mqtt_AppendDPStartObject(ctx->mqttbuf, DS_TO_PUBLISH_T, ts);
        err |= Mqtt_AppendDPSubvalueInt(ctx->mqttbuf, DS_TO_PUBLISH_T, temprature[0]);
        count++;
    }
    else if(count == 2)
    {
        err |= Mqtt_AppendDPStartObject(ctx->mqttbuf, DS_TO_PUBLISH_RH, ts);
        err |= Mqtt_AppendDPSubvalueInt(ctx->mqttbuf, DS_TO_PUBLISH_RH, rh[0]);
        count = 0;

    }
    err |= Mqtt_AppendDPFinishObject(ctx->mqttbuf);
    err |= Mqtt_PackDataPointFinish(ctx->mqttbuf);
    if(err)
    {
        printf("Failed to pack data point package.err=%d\n", err);
        return -1;
    }
    bytes = Mqtt_SendPkt(ctx->mqttctx, ctx->mqttbuf, 0);
    MqttBuffer_Reset(ctx->mqttbuf);
    return 0;
}
/**
  * @brief 周期性发布数据,这里是测试代码,发布温湿度和一个状态信息,三个数据流轮流发布
  * @param  ctx:上下文变量
    * @param  cause:发布原因,TIMEOUT,定时发送,EVENT则是由设备事件触发
  * @retval ret:0,成功,<0 失败
  **/
static int MqttSample_CmdPublishNormal(struct MqttSampleContext *ctx, uint8_t cause)
{
    int err = 0, ir_index = 0;
    int bytes = 0;
    struct MqttExtent *ext;
    unsigned char dis[3][64] = {"未知初始状态", "设备在位", "设备离位"};
    static unsigned char count = 0;
    int64_t ts = 0; //no time
    uint16_t temprature[1], rh[1];
    if(ctx->publish_state != 0)
    {
        printf("publsh busy\n");
        return -1;
    }
    ctx->publish_state = 1;
    printf("%s %d,count=%d,cause=%d\n", __func__, __LINE__, count, cause);
    // ts = (int64_t)time(NULL) * 1000;
    SHT2x_MeasureHM(SHT20_Measurement_RH_HM, temprature);
    mDelay(1500);
    SHT2x_MeasureHM(SHT20_Measurement_T_HM, rh);

    if((count == 0) || (cause == EVENT))
    {
        //no time
        if(cause == TIME_OUT)
        {
            ir_state = !ir_state;
        }
        if(ir_state == 0xff)
        {
            ir_index = 0;
        }
        if(ir_state == 0x1)
        {
            ir_index = 1;
        }
        if(ir_state == 0)
        {
            ir_index = 2;

        }
        if(count != 2)
        {
            count++;
        }
        //append data; String
        printf("pub state\n");
        err |= Mqtt_PackDataPointStartNormal(ctx->mqttbuf, (char *)(DS_TO_PUBLISH), 1, MQTT_QOS_LEVEL2, 0, 1);
        ext = MqttBuffer_AllocExtent(ctx->mqttbuf, 1 + strlen(dis[ir_index]));
        if(!ext)
        {
            return MQTTERR_OUTOFMEMORY;
        }
        ext->payload[0] = 0x84;;
        memcpy(&ext->payload[1], dis[ir_index], strlen(dis[ir_index]));
        MqttBuffer_AppendExtent(ctx->mqttbuf, ext);
    }
    else if(count == 1)
    {
        printf("pub temprature\n");
        err |= Mqtt_PackDataPointStartNormal(ctx->mqttbuf, (char *)(DS_TO_PUBLISH_T), 1, MQTT_QOS_LEVEL2, 0, 1);
        //append data; int32
        ext = MqttBuffer_AllocExtent(ctx->mqttbuf, 1 + sizeof(int));
        if(!ext)
        {
            return MQTTERR_OUTOFMEMORY;
        }
        ext->payload[0] = 0x81;
        ext->payload[1] = 0;
        ext->payload[2] = 0;
        ext->payload[3] = 0;
        ext->payload[4] = temprature[0];
        MqttBuffer_AppendExtent(ctx->mqttbuf, ext);
        count++;
    }
    else if(count == 2)
    {
        printf("rh\n");
        err |= Mqtt_PackDataPointStartNormal(ctx->mqttbuf, (char *)(DS_TO_PUBLISH_RH), 1, MQTT_QOS_LEVEL2, 0, 1);
        //append data; int32
        ext = MqttBuffer_AllocExtent(ctx->mqttbuf, 1 + sizeof(int));
        if(!ext)
        {
            return MQTTERR_OUTOFMEMORY;
        }
        ext->payload[0] = 0x81;;
        ext->payload[1] = 0;
        ext->payload[2] = 0;
        ext->payload[3] = 0;
        ext->payload[4] = rh[0];
        MqttBuffer_AppendExtent(ctx->mqttbuf, ext);
        count = 0;
    }

    if(err)
    {
        printf("Failed to pack data point package.err=%d\n", err);
        return -1;
    }
    err = Mqtt_AppendLength(ctx->mqttbuf, ext->len);
    if(MQTTERR_NOERROR != err)
    {
        return err;
    }

    bytes = Mqtt_SendPkt(ctx->mqttctx, ctx->mqttbuf, 0);
    MqttBuffer_Reset(ctx->mqttbuf);
    return 0;
}
Esempio n. 27
0
/*
 *  @brief  串口接收处理线程
 */
void Recv_Thread_Func(void)
{
    int32_t error = 0;
    int32_t rtn;
    uint8_t mtype, jsonorbin;
    uint8_t buffer[128];
    RecvBuffer *recv_buf = NewBuffer();
    EdpPacket *pkg;

    int8_t *src_devid;
    int8_t *push_data;
    uint32_t push_datalen;

    cJSON *desc_json;
    int8_t *desc_json_str;
    int8_t *save_bin;
    uint32_t save_binlen;
    int8_t *json_ack;

    int8_t *cmdid;
    uint16_t cmdid_len;
    int8_t *cmd_req;
    uint32_t cmd_req_len;
    EdpPacket *send_pkg;
    int8_t *ds_id;
    double dValue = 0;

    int8_t *simple_str = NULL;
    int8_t cmd_resp[] = "ok";
    uint32_t cmd_resp_len = 0;

    printf("\n[%s] recv thread start ...\r\n", __func__);

    while (error == 0)
    {
        /* 试着接收1024个字节的数据 */
        int32_t rcv_len = 0;

        rcv_len = USART2_GetRcvNum();
        if (rcv_len <= 0)
        {
            printf("%s %d No Data\n", __func__, __LINE__);
            break;
        }
				mDelay(50);
				rcv_len = USART2_GetRcvNum();
        USART2_GetRcvData(buffer, rcv_len);
        printf("recv from server, bytes: %d\r\n", rcv_len);
        /* wululu test print send bytes */
        hexdump((const uint8_t *)buffer, rcv_len);
        printf("\n");
        /* 成功接收了n个字节的数据 */
        WriteBytes(recv_buf, buffer, rcv_len);
        while (1)
        {
            /* 获取一个完成的EDP包 */
            if ((pkg = GetEdpPacket(recv_buf)) == 0)
            {
                printf("need more bytes...\n");
                break;
            }
            /* 获取这个EDP包的消息类型 */
            mtype = EdpPacketType(pkg);
            printf("mtype=%d\n", mtype);
            /* 根据这个EDP包的消息类型, 分别做EDP包解析 */
            switch (mtype)
            {
                case CONNRESP:
                    /* 解析EDP包 - 连接响应 */
                    rtn = UnpackConnectResp(pkg);
                    printf("recv connect resp, rtn: %d\n", rtn);
                    break;
                case PUSHDATA:
                    /* 解析EDP包 - 数据转发 */
                    UnpackPushdata(pkg, &src_devid, &push_data,
                                   &push_datalen);
                    printf
                    ("recv push data, src_devid: %s, push_data: %s, len: %d\n",
                     src_devid, push_data, push_datalen);
                    free(src_devid);
                    free(push_data);
                    break;
                case SAVEDATA:
                    /* 解析EDP包 - 数据存储 */
                    if (UnpackSavedata(pkg, &src_devid, &jsonorbin)
                        == 0)
                    {
                        if (jsonorbin == kTypeFullJson
                            || jsonorbin ==
                            kTypeSimpleJsonWithoutTime
                            || jsonorbin ==
                            kTypeSimpleJsonWithTime)
                        {
                            printf("json type is %d\n",
                                   jsonorbin);
                            /* 解析EDP包 - json数据存储 */
                            /* UnpackSavedataJson(pkg, &save_json); */
                            /* save_json_str=cJSON_Print(save_json); */
                            /* printf("recv save data json, src_devid: %s, json: %s\n", */
                            /*     src_devid, save_json_str); */
                            /* free(save_json_str); */
                            /* cJSON_Delete(save_json); */

                            /* UnpackSavedataInt(jsonorbin, pkg, &ds_id, &iValue); */
                            /* printf("ds_id = %s\nvalue= %d\n", ds_id, iValue); */

                            UnpackSavedataDouble(jsonorbin,
                                                 pkg,
                                                 &ds_id,
                                                 &dValue);
                            printf
                            ("ds_id = %s\nvalue = %f\n",
                             ds_id, dValue);

                            /* UnpackSavedataString(jsonorbin, pkg, &ds_id, &cValue); */
                            /* printf("ds_id = %s\nvalue = %s\n", ds_id, cValue); */
                            /* free(cValue); */
                            free(ds_id);
                        }
                        else if (jsonorbin == kTypeBin)     /* 解析EDP包 - bin数据存储 */
                        {
                            UnpackSavedataBin(pkg,
                                              &desc_json,
                                              (uint8_t **) &
                                              save_bin,
                                              &save_binlen);
                            desc_json_str =
                                cJSON_Print(desc_json);
                            printf
                            ("recv save data bin, src_devid: %s, desc json: %s, bin: %s, binlen: %d\n",
                             src_devid, desc_json_str,
                             save_bin, save_binlen);
                            free(desc_json_str);
                            cJSON_Delete(desc_json);
                            free(save_bin);
                        }
                        else if (jsonorbin == kTypeString)
                        {
                            UnpackSavedataSimpleString(pkg,
                                                       &simple_str);
                            printf("%s\n", simple_str);
                            free(simple_str);
                        }
                        free(src_devid);
                    }
                    else
                    {
                        printf("error\n");
                    }
                    break;
                case SAVEACK:
                    json_ack = NULL;
                    UnpackSavedataAck(pkg, &json_ack);
                    printf("save json ack = %s\n", json_ack);
                    free(json_ack);
                    break;
                case CMDREQ:
                    if (UnpackCmdReq
                        (pkg, &cmdid, &cmdid_len, &cmd_req,
                         &cmd_req_len) == 0)
                    {
                        /*
                         * 用户按照自己的需求处理并返回,响应消息体可以为空,此处假设返回2个字符"ok"。
                         * 处理完后需要释放
                         */
                        cmd_resp_len = strlen(cmd_resp);
                        send_pkg =
                            PacketCmdResp(cmdid, cmdid_len,
                                          cmd_resp,
                                          cmd_resp_len);
#ifdef _ENCRYPT
                        if (g_is_encrypt)
                        {
                            SymmEncrypt(send_pkg);
                        }
#endif
                        DoSend(0, (const uint8_t *)
                               send_pkg->_data,
                               send_pkg->_write_pos);
                        DeleteBuffer(&send_pkg);

                        free(cmdid);
                        free(cmd_req);
                    }
                    break;
                case PINGRESP:
                    /* 解析EDP包 - 心跳响应 */
                    UnpackPingResp(pkg);
                    printf("recv ping resp\n");
                    break;
                default:
                    /* 未知消息类型 */
                    error = 1;
                    printf("recv failed...\n");
                    break;
            }
            DeleteBuffer(&pkg);
        }
    }
    DeleteBuffer(&recv_buf);

#ifdef _DEBUG
    printf("[%s] recv thread end ...\n", __func__);
#endif
}