modify

Dependencies:   Adafruit_GFX Adafruit_ST7735 GMMP_mbed NTPClient SDFileSystem WIZnet_Library mbed

Fork of ThingPlug_Ethernet_Example_temp_V2 by irina kim

main.cpp

Committer:
irinakim
Date:
2015-08-15
Revision:
11:f15177f282a6
Parent:
9:9179158a0fef

File content as of revision 11:f15177f282a6:

#include "mbed.h"
#include "Adafruit_ST7735.h"
#include "SDFileSystem.h"
#include "mbed_debug.h"

#define BUTTON_NONE 0
#define BUTTON_DOWN 1
#define BUTTON_RIGHT 2
#define BUTTON_SELECT 3
#define BUTTON_UP 4
#define BUTTON_LEFT 5

#define BUFFPIXEL 20
#define MAX_SIZE 100 

SDFileSystem sd(D11, D12, D13, D4, "sd"); // the pinout on the mbed
Adafruit_ST7735 tft(D11, D12, D13, D10, D8, D9); // MOSI, MISO, SCLK, SSEL, TFT_DC, TFT_RST
AnalogIn joystick(A3);
Serial pc(D1,D0);
Serial device(D8,D2);
LocateDef locate;
LocateDef org;
uint8_t readButton(void);
void bmpDraw(char *filename, uint8_t x, uint8_t y);
char str[MAX_SIZE];
char str_l[MAX_SIZE];


#include "config.h"

	#ifdef USE_SNIC_WIFI
	#include "SNIC_WifiInterface.h"
	C_SNIC_WifiInterface     wifi( D8, D2, NC, NC, D3);
	#endif//USE_SNIC_WIFI

	#ifdef USE_WIZNET_W5500
	#include "WIZnetInterface.h"
    WIZnetInterface ethernet(PA_7, PA_6, PA_5, PB_6, PA_9);//scs(PB_6), nRESET(PA_9); // reset pin is dummy, don't affect any pin of WIZ550io
	#endif//USE_WIZNET_W5500

/**
 * GMMP Test Code
 */

#include "GMMP.h"

#define USER_CONTROL_LED 0x80

#define HIGH 0x1
#define LOW  0x0

byte serverIp[4] = THINGPLUG_GMMP_IP_ADDR;
const int nServerPort = THINGPLUG_GMMP_PORT_NUM;
const char* pszDomainCode = THINGPLUG_GMMP_SERVICE_NAME;
const char* pszGWAuthID = THINGPLUG_GMMP_DEVICE_SERIAL_NUM;
const char* pszGWMFID = THINGPLUG_GMMP_DEVICE_MANUFACTURER_ID;
const char* pszDeviceMFID = THINGPLUG_GMMP_SUB_DEVICE_MANUFACTURER_ID;

char* deviceId[LEN_DEVICE_ID];
unsigned char g_mac[6] = DEFAULT_MAC_ADDR;


uint32_t lastDeliverMilli = 0;
uint32_t reportPeriodMilli = 3000;
uint32_t lastHeartbeatMilli = 0;
uint32_t heartbeatPeriodMilli = 10000;
byte regDevCount = 0;
byte regGwCount = 0;

void startSensingTemp();
void delay(int d);

int Recv(GMMPHeader* pstGMMPHeader, void* pBody)
{
  U8 cMessageType = pstGMMPHeader->ucMessageType;

  //info(F("MsgType: "));
  //infoln(cMessageType);
  INFO("MsgType: %d", cMessageType);

  if (cMessageType == OPERATION_GW_REG_RSP) {
    stGwRegistrationRspHdr* pstRspHdr = (stGwRegistrationRspHdr*) pBody;

    if (pstRspHdr->ucResultCode != 0x00) {
      //error(F("GWRegRes Error: "));
      //errorln(pstRspHdr->ucResultCode);
      ERR("GWRegRes Error: %d", pstRspHdr->ucResultCode);
      free(pBody);
      return 1;
    }

    SetAuthKey((char*) pstGMMPHeader->usAuthKey);
    SetGWID((char*) pstRspHdr->usGWID);
    infoln(("GWRegRes has been received:"));
    infoln(g_szAuthKey);
    infoln(GetGWID());
    INFO("GWRegRes has been received:\r\n%s\r\n%s", g_szAuthKey, GetGWID());
    regGwCount++;

    int ret = GO_Profile(GetGWID(), NULL, 0);

    if (ret != GMMP_SUCCESS) {
      errorln("ReqProfile Err!!");
      free(pBody);
      return 1;
    }

    infoln("ProfileReq has been sent.");
  } else if (cMessageType == OPERATION_PROFILE_RSP) {
    stProfileRspHdr* pstRspHdr = (stProfileRspHdr*) pBody;

    if (pstRspHdr->ucResultCode != 0x00) {
      errorln("ProfileRes Error!");
      free(pBody);
      return 1;
    }

    //infoln(F("ProfileRes has been received:"));
    //infoln(Char2int(pstRspHdr->unHeartbeatPeriod, 4));
    //infoln(Char2int(pstRspHdr->unReportOffset, 4));
    //infoln(Char2int(pstRspHdr->unReportPeriod, 4));
    //infoln(Char2int(pstRspHdr->unResponseTimeout, 4));
    INFO("ProfileRes has been received:\r\n%d\r\n%d\r\n%d\r\n%d",
    Char2int(pstRspHdr->unHeartbeatPeriod, 4),
    Char2int(pstRspHdr->unReportOffset, 4),
    Char2int(pstRspHdr->unReportPeriod, 4),
    Char2int(pstRspHdr->unResponseTimeout,4) );
    /* 주기값 재설정
       pstRspHdr->unHeartbeatPeriod;
       pstRspHdr->unReportOffset;
       pstRspHdr->unReportPeriod;
       pstRspHdr->unResponseTimeout;
     */

    reportPeriodMilli = Char2int(pstRspHdr->unReportPeriod, 4) * 1000 * 60;
    //reportPeriodMilli = Char2int(pstRspHdr->unReportPeriod, 4) * 300;
    heartbeatPeriodMilli = Char2int(pstRspHdr->unHeartbeatPeriod, 4) * 1000 * 60;

    long nHeartBeat = Char2int((char*) pstRspHdr->unHeartbeatPeriod, sizeof(pstGMMPHeader->usTID)); //수신받은 Heartbeat 주기 값을 확인.

    //Profile 요청 수신 값에 Heartbeat 주기 값으로 변경
    if (nHeartBeat > 0) {
      //nTimerSec = nHeartBeat;
    }

    int ret = GO_Reg(GetGWID(), pszDeviceMFID);

    if (ret != GMMP_SUCCESS) {
      errorln("DevRegReq Err!!");
      free(pBody);
      return 1;
    }

    infoln("DevRegReq has been sent.");
  } else if (cMessageType == OPERATION_DEVICE_REG_RSP) {
    stDeviceRegistrationRspHdr* pstRspHdr = (stDeviceRegistrationRspHdr*) pBody;

    if (pstRspHdr->ucResultCode != 0x00) {
      errorln("DevRegRes Error!");
      free(pBody);
      return 1;
    }

    if (strlen((char*) pstRspHdr->usDeviceID) <= 0) {
      errorln("No DeviceID!");
      free(pBody);
      return 1;
    }

    int len = strlen((char*) pstRspHdr->usDeviceID);
    memset(deviceId, 0, LEN_DEVICE_ID);
    memcpy(deviceId, pstRspHdr->usDeviceID, len);
    infoln("DevRegRes has been received:");
    infoln((char*) deviceId);
    regDevCount++;

  } else if (cMessageType == OPERATION_DELIVERY_RSP) {
    stPacketDeliveryRspHdr* pstRspHdr = (stPacketDeliveryRspHdr*) pBody;

    if (pstRspHdr->ucResultCode != 0x00) {
//      errorln("DeliverRes Err!!");
      ERR("DeliverRes Err(0x%2x)!!", pstRspHdr->ucResultCode); //lesmin
      free(pBody);
      return 1;
    }
    
    infoln("DeliveryRes has been received.");
  } else if (pstGMMPHeader->ucMessageType == OPERATION_HEARTBEAT_RSP) {
    //stHeartBeatMsgRspHdr* pstRspHdr = (stHeartBeatMsgRspHdr*) pBody;
    
    infoln("HeartbeatRes has been received.");
  } else if (cMessageType  == OPERATION_CONTROL_REQ) {
    stControlReqHdr* pstReqHdr = (stControlReqHdr*) pBody;

    infoln("ControlReq has been received.");

    char cResult = 0x00;

    int len = 0;
    if (pstReqHdr->usMessageBody) {
      len = strlen((char*) pstReqHdr->usMessageBody);
    }
    if (len > 0) {
      info("Control Msg Body: ");
      infoln((char*) pstReqHdr->usMessageBody);
    }

    long nTID = Char2int((char*) pstGMMPHeader->usTID, sizeof(pstGMMPHeader->usTID));

    //debug(F("Received TID: "));
    //debugln(nTID);
    DBG("Received TID: %d\r\n", nTID);

    int ret = GO_Control((char*) pstReqHdr->usGWID, (char*) pstReqHdr->usDeviceID, nTID,
     (char)pstReqHdr->ucControlType, cResult);

    if (ret != GMMP_SUCCESS) {
      errorln("ControRes Err!!");
      free(pBody);
      return 1;
    }

    infoln("ControlRes has been sent.");

    //infoln(pstReqHdr->ucControlType);
    INFO("%d\r\n", pstReqHdr->ucControlType);

    if (pstReqHdr->ucControlType != USER_CONTROL_LED) {
      ERR("Unknown Control Msg: %d\r\n", pstReqHdr->ucControlType);
      free(pBody);
      return 1;
    }

    if (pstReqHdr->usMessageBody[0] == '1') {
      //myled = 1;
      infoln("LED ON");
    } else if (pstReqHdr->usMessageBody[0] == '0') {
      //myled = 0;
      infoln("LED OFF");
    } else {
      errorln("Unknown Control Msg Body; it must be '1' or '0'.");
      free(pBody);
      return 1;
    }

    delay(1000); //msec

    ret = GO_Notifi((char*) pstReqHdr->usGWID, (char*) pstReqHdr->usDeviceID,
        (char)pstReqHdr->ucControlType, cResult, (char*) pstReqHdr->usMessageBody, 0);

    if (ret != GMMP_SUCCESS) {
      ERR("NotiReq Err: %d\r\n", ret);
      free(pBody);
      return 1;
    }

    infoln("Control NotiReq has been sent.");
  } else if (cMessageType  == OPERATION_NOTIFICATION_RSP) {
    stNotificationRspHdr* pstRspHdr = (stNotificationRspHdr*) pBody;

    if (pstRspHdr->ucResultCode != 0x00) {
      //error(F("NotiRes Err: "));
      //errorln(pstRspHdr->ucResultCode);
      ERR("NotiRes Err: %d\r\n", pstRspHdr->ucResultCode);
      free(pBody);
      return 1;
    }

    infoln("NotiRes has been received.");
  } else if (cMessageType == OPERATION_GW_DEREG_RSP) {
    stGwRegistrationRspHdr* pstRspHdr = (stGwRegistrationRspHdr*) pBody;

    if (pstRspHdr->ucResultCode != 0x00) {
      //error(F("DeregGwRes Err: "));
      //errorln(pstRspHdr->ucResultCode);
      ERR("DeregGwRes Err: %d\r\n", pstRspHdr->ucResultCode);
      free(pBody);
      return 1;
    }

    if (strlen((char*) pstRspHdr->usGWID) <= 0) {
      errorln("No GW ID!!");
      free(pBody);
      return 1;
    }

    if (strlen((char*) pstGMMPHeader->usAuthKey) <= 0) {
      errorln("No Auth Key!!");
      free(pBody);
      return 1;
    }

    infoln("DeregGwRes has been received.");
  } else if (cMessageType == OPERATION_DEVICE_DEREG_RSP) {
    stDeviceRegistrationRspHdr* pstRspHdr = (stDeviceRegistrationRspHdr*) pBody;

    if (pstRspHdr->ucResultCode != 0x00) {
      //error(F("DeregDevRes Err: "));
      //errorln(pstRspHdr->ucResultCode);
      ERR("DeregDevRes Err: %d\r\n", pstRspHdr->ucResultCode);
      free(pBody);
      return 1;
    }

    if (strlen((char*) pstRspHdr->usDeviceID) <= 0) {
      errorln("No device ID!!");
      free(pBody);
      return 1;
    }

    infoln("DeregDevRes has been received.");
  }

  free(pBody);
  return 0;
}

byte isSensing = 0;

void startSensingTemp()
{
        printf("Sensing started!\r\n");
        isSensing = 1;
}

void tft_operation(void)
{
	 char temp1[40];
    char temp2[10];
    char buf[40];
    char data[30];
    uint8_t b; 
    uint8_t i=0;
    int cnt = 0;
    char ret;
    buf[0] = 0xec;
    buf[1] = 0xec;
    buf[2] = 0xd6;
    buf[3] = 0xf6;
    buf[4] = 0x56;
    buf[5] = 0x36;
    buf[6] = 0xf6;
    buf[7] = 0x36;
    buf[8] = 0xf6;
    buf[9] = 0xb6;
    buf[10] = 0x16;
    buf[11] = 0xf6;
    buf[12] = 0x56;
    buf[13] = 0x76;
    
	 tft.fillScreen(ST7735_BLACK);
	 sprintf(data,"Name  Date   Etc\n"); 
	 tft.printf("%s",data);
	/* FILE *fp = fopen("/sd/fr_list.txt", "w"); 
        if(fp == NULL) {
            error("Could not open file for write\n");
        }
    */

    
    FILE *db = fopen("/sd/db.txt", "r");
    fscanf(db,"%s%s",&temp1, &temp2);
    
    printf("test\r\n");
    printf("d : %x, %x\r\n", temp1[0], temp1[1]);
    printf("s : %s\r\n", temp2);
    
    while(1) {
  
        if(device.readable()) {
            buf[cnt] = device.getc();
            if(buf[cnt] == 0)
            {
                for(int i=0; i<cnt; i++)
                    printf("%x ", buf[i]);
                printf("\r\n");
                cnt = 0;
                
            }    
            else 
                cnt ++;
        }
    }
     FILE *fp = fopen("/sd/fr_list.txt", "w");
	 if(fp == NULL) {
            error("Could not open file for write\n");
        }    
        /////////////ADD/////////////  
	       
	    fp = fopen("/sd/fr_list.txt", "r");
	    while(fgets(str,MAX_SIZE,fp)!=NULL)
	    {
	       sprintf(str_l, "%s", str);
	       tft.printf("%s",str_l);
	    } fclose(fp);
 
    tft.setCursor(0,0);
    tft.getCursor(&org);
    int8_t count=0;
    while(1)
    {
         b = readButton();
         tft.getCursor(&locate);
        if(b == BUTTON_DOWN)
        {
         	tft.setCursor(120,locate.y_data-8);
         	count--;
         	if(count <=0)
         	{
         		count =0;
         		tft.printf("%s",count);
         	}
         	tft.printf("%s",count);            
         
         }
         else if(b == BUTTON_UP)
         {
         
         	tft.setCursor(120,locate.y_data-8);
         	count++;
         	if(count >=255)
         	{
         		count =0;
         		tft.printf("%s",count);
         	}
         	tft.printf("%s",count);       
        }
        else if(b == BUTTON_SELECT)
        {
             tft.getCursor(&org);
             tft.setCursor(org.x_data,org.y_data+8);
            // printf("x =%d, y=%d\r\n",org.x_data,org.y_data);
        
        }
       
    }
}

#define BUF_SIZE 10
GMMPHeader header;
void *pBody = NULL;
char sendBuf[BUF_SIZE];

Timer g_t; //for Millis()

int setup(void) {

   	pc.baud(9600);

    g_t.start();

  infoln("Start setup()");
  tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab
    tft.fillScreen(ST7735_BLACK);
    mkdir("/sd/fridge_care", 0777);
	#ifdef USE_SNIC_WIFI
	wifi.init();

    wait(0.5);
    int s = wifi.disconnect();
    if( s != 0 ) {
        return -1;
    }

    wait(0.3);
    // Connect AP
    wifi.connect( MBED_AP_SSID
                  , strlen(MBED_AP_SSID)
                  , MBED_AP_SECURITY_TYPE
                  , MBED_AP_SECUTIRY_KEY
                  , strlen(MBED_AP_SECUTIRY_KEY) );
    wait(0.5);
    wifi.setIPConfig( true );     //Use DHCP
    wait(0.5);
    
    tagWIFI_STATUS_T wifi_status;
    if( wifi.getWifiStatus(&wifi_status) ) printf("wifi_status error!\r\n");

    printf("MAC Address is %02x:%02x:%02x:%02x:%02x:%02x\r\n",
    	wifi_status.mac_address[0], wifi_status.mac_address[1], wifi_status.mac_address[2],
    	wifi_status.mac_address[3], wifi_status.mac_address[4], wifi_status.mac_address[5]);
    printf("IP Address is %s\r\n", wifi.getIPAddress());
    #endif//USE_SNIC_WIFI

	#ifdef USE_WIZNET_W5500
	//mbed_mac_address((char *)MAC_Addr); //Use mbed mac addres
    printf("input MAC Address is %02x:%02x:%02x:%02x:%02x:%02x\r\n",
    	g_mac[0], g_mac[1], g_mac[2], g_mac[3], g_mac[4], g_mac[5]);
	
	int ret = ethernet.init(g_mac);
    //printf("SPI Initialized \r\n");
    //wait(1); // 1 second for stable state
    
    printf("W5500 Networking Started \r\n");
    //wait(1); // 1 second for stable state

    if (!ret) {
        printf("Initialized, MAC: %s\r\n", ethernet.getMACAddress());
        ret = ethernet.connect();
        if (!ret) {
            printf("IP: %s, MASK: %s, GW: %s\r\n",
                      ethernet.getIPAddress(), ethernet.getNetworkMask(), ethernet.getGateway());
        } else {
            printf("Error ethernet.connect() - ret = %d\r\n", ret);
            //exit(0);

            // ## 20150812 Eric added, Ethernet interface re-initialize code
            ///////////////////////////////////////////////////////////////////////////
            do{             
                //printf("Ethernet Interface Re-initialize\r\n");               
                #if defined(TARGET_LPC1768) 
                SPI spi(p5, p6, p7); // mosi, miso, sclk        
                #elif defined(TARGET_NUCLEO_F411RE) || defined(TARGET_NUCLEO_F401RE) || defined(TARGET_NUCLEO_F303RE) || defined(TARGET_NUCLEO_F334R8) || defined(TARGET_NUCLEO_L152RE)
                SPI spi(PA_7, PA_6, PA_5);
                #endif
                //wait(0.5);
                
                ethernet.init(g_mac);
                ret = ethernet.connect();
                printf("Re-initialized, MAC: %s\r\n", ethernet.getMACAddress());            
                printf("IP: %s, MASK: %s, GW: %s\r\n",
                          ethernet.getIPAddress(), ethernet.getNetworkMask(), ethernet.getGateway());
            } while(ret);
            ///////////////////////////////////////////////////////////////////////////
        }
    } else {
        printf("Error ethernet.init() - ret = %d\r\n", ret);
        //exit(0);
    }

	#endif//USE_WIZNET_W5500


    startSensingTemp(); //lesmin

  if ( Initialize(serverIp, nServerPort, pszDomainCode, pszGWAuthID, g_mac) ) {
      infoln("Initialize failed!");
      return -1; //lesmin
  }

  infoln("SetCallFunction");
  SetCallFunction(Recv);
  
  ret = GO_Reg(NULL, pszGWMFID);

  if (ret != GMMP_SUCCESS) {
    errorln("RegReq Error!!");
    for(;;);
  }

  infoln("GW RegReq has been sent.");
  return 0;
}

int millis(void) {
    return g_t.read_ms();
}

float getTemperature(void) {
	return 33.3;
}

void delay(int d) {
    float delay_time = d/1000.0;
    wait(delay_time);
}

uint8_t readButton(void) {
    float a = joystick.read();
      
    a *= 5.0;
          
//    printf("Button read analog = %f\r\n",a);
    if (a < 0.2) return BUTTON_DOWN;//BUTTON_LEFT;
    if (a < 1.0) return BUTTON_RIGHT;//BUTTON_DOWN;  
    if (a < 1.7) return BUTTON_SELECT;
    if (a < 2.6) return BUTTON_UP;//BUTTON_RIGHT;
    if (a < 4.6) return BUTTON_LEFT;//BUTTON_UP;
   
    else return BUTTON_NONE;
}

void loop(void)
{
  int ret = GetReadData(&header, &pBody);
  if (ret != E_WOULDBLOCK) {
    //infoln("******** NOT E_WOULDBLOCK *********");
    //info(F("Free memory size: "));
    //infoln(freeRam());
  }

  //byte addr[8];
  float temperature;

  int curMilli = millis();
  byte mustDeliver = (curMilli - lastDeliverMilli) > reportPeriodMilli;
  byte mustHeartbeat = (curMilli - lastHeartbeatMilli) > heartbeatPeriodMilli;
 
  if (!isSensing) {
    printf("Sensor is off...\r\n");
    return;
  }

#if 1
  //int mustGwDereg = digitalRead(DEREGISTRATION_GW_SWITCH_PIN);
  int mustGwDereg = LOW; //lesmin

  if (mustGwDereg == HIGH && regGwCount > 0) {
    ret = GO_DeReg(GetGWID(), NULL);

    if (ret != GMMP_SUCCESS) {
      errorln("DeregGwReq Error!!");
      delay(1000);
      return;
    }

    regGwCount--;
    return;
  }

  //int mustDevDereg = digitalRead(DEREGISTRATION_DEVICE_SWITCH_PIN);
  int mustDevDereg = LOW;

  if (mustDevDereg == HIGH && regDevCount > 0) {
    ret = GO_DeReg(GetGWID(), (char*) deviceId);

    if (ret != GMMP_SUCCESS) {
      errorln("DeregDevReq Error!!");
      delay(1000);
      return;
    }

    regDevCount--;
    return;
  }

  if (mustHeartbeat) {
    DBG("lastHeartbeatMilli: %d\r\ncurMilli: %d\r\n", lastHeartbeatMilli, curMilli);

    ret = GO_HB(GetGWID());

    if (ret != GMMP_SUCCESS) {
      errorln("HeartbeatReq Error!!");
      return;
    }

    infoln("HeartbeatReq has been sent.");

    lastHeartbeatMilli = curMilli;
  }

  if (!mustDeliver) {
    return;
  }
#endif

  temperature = getTemperature();

  memset(sendBuf, 0, BUF_SIZE);

  sprintf(sendBuf, "%.1f", temperature);

  ret = GO_Delivery(GetGWID(), NULL, DELIVERY_COLLECT_DATA, 0x01, sendBuf);

  info("Sent Data: ");
  infoln(sendBuf);
  INFO("Sent Data: %s\r\n", sendBuf);

  if (ret != GMMP_SUCCESS) {
    errorln("DeliveryReq Error!!");
    return;
  }

  lastDeliverMilli = curMilli;
}

int main() {

time_t ctTime;
    char buffer[50];
     char data[30];
    uint8_t b; 
    uint8_t i=0;
    if( setup() < 0 ) return 0;

    while(1) {
        ctTime = time(NULL)+(3600*9);  //TIME with offset for eastern time KR
        //FORMAT TIME FOR DISPLAY AND STORE FORMATTED RESULT IN BUFFER
        strftime(buffer,80,"%a %b %d\r\n%T %p %z\r\n %Z\r\n",localtime(&ctTime));
        
        loop();
	   tft_operation();
    
    }
}