main.c 8.74 KB
Newer Older
1 2 3 4 5
/*
 * Copyright (c) 2014-2016 Cesanta Software Limited
 * All rights reserved
 */

6
#include <stdbool.h>
7
#include <stdio.h>
8
#include <stdlib.h>
9 10
#include <string.h>

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <inc/hw_types.h>
#include <inc/hw_ints.h>
#include <inc/hw_memmap.h>

#include <driverlib/gpio.h>
#include <driverlib/interrupt.h>
#include <driverlib/pin.h>
#include <driverlib/prcm.h>
#include <driverlib/rom.h>
#include <driverlib/rom_map.h>
#include <driverlib/uart.h>
#include <driverlib/utils.h>

#include <example/common/gpio_if.h>
#include <example/common/i2c_if.h>

/* Mongoose.h brings in SimpleLink support. Do not include simplelink.h. */
#include <mongoose.h>

#include <simplelink/include/device.h>
31

32 33
#include "data.h"
#include "wifi.h"
34

35
/* Set up an AP or connect to existing WiFi network. */
36 37 38 39 40
#define WIFI_AP_SSID "Mongoose"
#define WIFI_AP_PASS ""
#define WIFI_AP_CHAN 6
// #define WIFI_STA_SSID "YourWiFi"
// #define WIFI_STA_PASS "YourPass"
41

42
#define DATA_COLLECTION_INTERVAL_MS 20
43

44 45 46
#define CONSOLE_BAUD_RATE 115200
#define CONSOLE_UART UARTA0_BASE
#define CONSOLE_UART_PERIPH PRCM_UARTA0
47
#define MG_TASK_PRIORITY 3
48
#define MG_TASK_STACK_SIZE 8192
49

50
#define BM222_ADDR 0x18
51 52
#define TMP006_ADDR 0x41

Deomid Ryabkov's avatar
Deomid Ryabkov committed
53 54
void fs_slfs_set_new_file_size(const char *name, size_t size);

55 56
static const char *upload_form =
    "\
57 58 59 60 61 62
<h1>Upload file</h1> \
<form action='/upload' method='POST' enctype='multipart/form-data'> \
  <input type='file' name='file'> \
  <input type='submit' value='Upload'> \
</form>";

63 64
static struct mg_str upload_fname(struct mg_connection *nc,
                                  struct mg_str fname) {
65
  struct mg_str lfn;
Deomid Ryabkov's avatar
Deomid Ryabkov committed
66 67 68 69 70 71 72 73 74 75 76 77
  char *fn = malloc(fname.len + 4);
  memcpy(fn, "SL:", 3);
  memcpy(fn + 3, fname.p, fname.len);
  fn[3 + fname.len] = '\0';
  if (nc->user_data != NULL) {
    intptr_t cl = (intptr_t) nc->user_data;
    if (cl >= 0) {
      fs_slfs_set_new_file_size(fn + 3, cl);
    }
  }
  lfn.len = fname.len + 4;
  lfn.p = fn;
78 79 80
  return lfn;
}

81
static void mg_ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
82 83 84
  switch (ev) {
    case MG_EV_ACCEPT: {
      char addr[32];
85 86 87
      mg_conn_addr_to_str(nc, addr, sizeof(addr), MG_SOCK_STRINGIFY_REMOTE |
                                                      MG_SOCK_STRINGIFY_IP |
                                                      MG_SOCK_STRINGIFY_PORT);
88 89 90 91 92
      LOG(LL_INFO, ("%p conn from %s", nc, addr));
      break;
    }
    case MG_EV_HTTP_REQUEST: {
      char addr[32];
93
      struct http_message *hm = (struct http_message *) ev_data;
94
      cs_stat_t st;
95 96 97
      mg_conn_addr_to_str(nc, addr, sizeof(addr), MG_SOCK_STRINGIFY_REMOTE |
                                                      MG_SOCK_STRINGIFY_IP |
                                                      MG_SOCK_STRINGIFY_PORT);
98 99 100
      LOG(LL_INFO,
          ("HTTP request from %s: %.*s %.*s", addr, (int) hm->method.len,
           hm->method.p, (int) hm->uri.len, hm->uri.p));
101
      if (mg_vcmp(&hm->uri, "/upload") == 0 ||
102
          (mg_vcmp(&hm->uri, "/") == 0 && mg_stat("SL:index.html", &st) != 0)) {
103 104 105 106
        mg_send(nc, upload_form, strlen(upload_form));
        nc->flags |= MG_F_SEND_AND_CLOSE;
        break;
      }
107 108
      struct mg_serve_http_opts opts;
      memset(&opts, 0, sizeof(opts));
109
      opts.document_root = "SL:";
110
      mg_serve_http(nc, hm, opts);
111 112 113 114 115 116 117 118
      break;
    }
    case MG_EV_CLOSE: {
      LOG(LL_INFO, ("%p closed", nc));
      break;
    }
    case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {
      LOG(LL_INFO, ("%p switching to data mode", nc));
119
      nc->handler = data_conn_handler;
120
      nc->ev_timer_time = mg_time(); /* Immediately */
121 122 123
      break;
    }
    case MG_EV_TIMER: {
124 125
      data_collect();
      nc->ev_timer_time = mg_time() + (DATA_COLLECTION_INTERVAL_MS * 0.001);
Deomid Ryabkov's avatar
Deomid Ryabkov committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
      break;
    }
    /* SimpleLink FS requires pre-declaring max file size. We use Content-Length
     * for that purpose - it will not exactly match file size, but is guaranteed
     * to exceed it and should be close enough. */
    case MG_EV_HTTP_MULTIPART_REQUEST: {
      struct http_message *hm = (struct http_message *) ev_data;
      struct mg_str *cl_header = mg_get_http_header(hm, "Content-Length");
      intptr_t cl = -1;
      if (cl_header != NULL && cl_header->len < 20) {
        char buf[20];
        memcpy(buf, cl_header->p, cl_header->len);
        buf[cl_header->len] = '\0';
        cl = atoi(buf);
        if (cl < 0) cl = -1;
      }
      nc->user_data = (void *) cl;
      break;
144
    }
145 146 147
    case MG_EV_HTTP_PART_BEGIN:
    case MG_EV_HTTP_PART_DATA:
    case MG_EV_HTTP_PART_END: {
148 149 150 151 152 153 154 155
      struct mg_http_multipart_part *mp =
          (struct mg_http_multipart_part *) ev_data;
      if (ev == MG_EV_HTTP_PART_BEGIN) {
        LOG(LL_INFO, ("Begin file upload: %s", mp->file_name));
      } else if (ev == MG_EV_HTTP_PART_END) {
        LOG(LL_INFO, ("End file upload: %s", mp->file_name));
      }
      mg_file_upload_handler(nc, ev, ev_data, upload_fname);
156
    }
157 158 159
  }
}

160
static void mg_init(struct mg_mgr *mgr) {
161
  LOG(LL_INFO, ("MG task running"));
162 163

  stop_nwp(); /* See function description in wifi.c */
Deomid Ryabkov's avatar
Deomid Ryabkov committed
164
  LOG(LL_INFO, ("Starting NWP..."));
165 166 167 168 169
  int role = sl_Start(0, 0, 0);
  if (role < 0) {
    LOG(LL_ERROR, ("Failed to start NWP"));
    return;
  }
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184

  {
    SlVersionFull ver;
    unsigned char opt = SL_DEVICE_GENERAL_VERSION;
    unsigned char len = sizeof(ver);

    memset(&ver, 0, sizeof(ver));
    sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &opt, &len,
              (unsigned char *) (&ver));
    LOG(LL_INFO, ("NWP v%d.%d.%d.%d started, host v%d.%d.%d.%d",
                  ver.NwpVersion[0], ver.NwpVersion[1], ver.NwpVersion[2],
                  ver.NwpVersion[3], SL_MAJOR_VERSION_NUM, SL_MINOR_VERSION_NUM,
                  SL_VERSION_NUM, SL_SUB_VERSION_NUM));
  }

185
  GPIO_IF_LedToggle(MCU_RED_LED_GPIO);
186

187
  data_init_sensors(TMP006_ADDR, BM222_ADDR);
188

189 190
  sl_fs_init();

191 192 193 194 195 196 197
#if defined(WIFI_STA_SSID)
  if (!wifi_setup_sta(WIFI_STA_SSID, WIFI_STA_PASS)) {
    LOG(LL_ERROR, ("Error setting up WiFi station"));
  }
#elif defined(WIFI_AP_SSID)
  if (!wifi_setup_ap(WIFI_AP_SSID, WIFI_AP_PASS, WIFI_AP_CHAN)) {
    LOG(LL_ERROR, ("Error setting up WiFi AP"));
198
  }
199 200 201
#else
#error WiFi not configured
#endif
202

203
  /* We don't need SimpleLink's web server. */
204 205 206 207 208 209 210
  sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);

  const char *err = "";
  struct mg_bind_opts opts;
  memset(&opts, 0, sizeof(opts));
  opts.error_string = &err;

211
  struct mg_connection *nc = mg_bind_opt(mgr, "80", mg_ev_handler, opts);
212 213
  if (nc != NULL) {
    mg_set_protocol_http_websocket(nc);
214
    nc->ev_timer_time = mg_time(); /* Start data collection */
215 216 217 218 219
  } else {
    LOG(LL_ERROR, ("Failed to create listener: %s", err));
  }
}

220
#ifndef USE_TIRTOS
221 222
/* Int vector table, defined in startup_gcc.c */
extern void (*const g_pfnVectors[])(void);
223
#endif
224 225

int main() {
226
#ifndef USE_TIRTOS
227
  MAP_IntVTableBaseSet((unsigned long) &g_pfnVectors[0]);
228
#endif
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  MAP_IntEnable(FAULT_SYSTICK);
  MAP_IntMasterEnable();
  PRCMCC3200MCUInit();

  /* Console UART init. */
  MAP_PRCMPeripheralClkEnable(CONSOLE_UART_PERIPH, PRCM_RUN_MODE_CLK);
  MAP_PinTypeUART(PIN_55, PIN_MODE_3); /* PIN_55 -> UART0_TX */
  MAP_PinTypeUART(PIN_57, PIN_MODE_3); /* PIN_57 -> UART0_RX */
  MAP_UARTConfigSetExpClk(
      CONSOLE_UART, MAP_PRCMPeripheralClockGet(CONSOLE_UART_PERIPH),
      CONSOLE_BAUD_RATE,
      (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE));
  MAP_UARTFIFOLevelSet(CONSOLE_UART, UART_FIFO_TX1_8, UART_FIFO_RX4_8);
  MAP_UARTFIFOEnable(CONSOLE_UART);

244 245
  setvbuf(stdout, NULL, _IOLBF, 0);
  setvbuf(stderr, NULL, _IOLBF, 0);
246
  cs_log_set_level(LL_INFO);
247
  cs_log_set_file(stdout);
248

249
  LOG(LL_INFO, ("Hello, world!"));
250

251 252 253 254
  MAP_PinTypeI2C(PIN_01, PIN_MODE_1); /* SDA */
  MAP_PinTypeI2C(PIN_02, PIN_MODE_1); /* SCL */
  I2C_IF_Open(I2C_MASTER_MODE_FST);

255 256 257 258 259 260
  /* Set up the red LED. Note that amber and green cannot be used as they share
   * pins with I2C. */
  MAP_PRCMPeripheralClkEnable(PRCM_GPIOA1, PRCM_RUN_MODE_CLK);
  MAP_PinTypeGPIO(PIN_64, PIN_MODE_0, false);
  MAP_GPIODirModeSet(GPIOA1_BASE, 0x2, GPIO_DIR_MODE_OUT);
  GPIO_IF_LedConfigure(LED1);
261
  GPIO_IF_LedOn(MCU_RED_LED_GPIO);
262 263

  if (VStartSimpleLinkSpawnTask(8) != 0) {
264
    LOG(LL_ERROR, ("Failed to create SL task"));
265
  }
266 267

  if (!mg_start_task(MG_TASK_PRIORITY, MG_TASK_STACK_SIZE, mg_init)) {
268
    LOG(LL_ERROR, ("Failed to create MG task"));
269
  }
270

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  osi_start();

  return 0;
}

/* These are FreeRTOS hooks for various life situations. */
void vApplicationMallocFailedHook() {
}

void vApplicationIdleHook() {
}

void vApplicationStackOverflowHook(OsiTaskHandle *th, signed char *tn) {
}

void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *e,
                                  SlHttpServerResponse_t *resp) {
}

void SimpleLinkSockEventHandler(SlSockEvent_t *e) {
}
292 293

void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *e) {
294 295
  LOG(LL_ERROR, ("status %d sender %d", e->EventData.deviceEvent.status,
                 e->EventData.deviceEvent.sender));
296
}