示例#1
0
//set wifi ON or OFF
int
mon_wifi(int argc, char **argv){
  if(argc!=2){
    printf("specify [on] or [off]\n");
    return -1;
  }
  if(strcmp(argv[1],"on")==0){
    b_wifi_enabled = true;
    if(wifi_init()!=0){
      b_wifi_enabled=false;
      printf("error starting wifi\n");
    }
    else{
      //good to go! turn light green
      rgb_led_set(LED_LT_GREEN,0);
      printf("wifi on\n");
    }
    return 0;
  }
  else if(strcmp(argv[1],"off")==0){
    b_wifi_enabled = false;
    printf("wifi off\n");
    rgb_led_set(LED_BLUE,0);
    return 0;
  }
  printf("specify [on] or [off]\n");
  return -1;
}
String wifiInit(String APname,String APpassword){
int counter=0;
wifi_init();
while(!moduleResponds()){
  counter++;
    if(counter>=5){
        SerialUSB.println("Wi-Fi Module Response Failed!");
        return "Error: 1";  //Wi-Fi Module Response Failed!
                  }
                        }
counter = 0;
while(!setWifiMode()){
  counter++;
    if(counter>=5){
        SerialUSB.println("Setting Wi-Fi Mode Failed!");
        return "Error: 2";  //Setting Wi-Fi Mode Failed!
                  }
                      }
counter = 0;
while(!setWifiTransmissionMode()){
  counter++;
    if(counter>=5){
        SerialUSB.println("Setting Wi-Fi Transmission Mode Failed!");
        return "Error: 3";  //Setting Wi-Fi Transmission Mode Failed!
                  }
                                 }
counter = 0;
while(!setWifiConnectionMode()){
  counter++;
    if(counter>=5){
        SerialUSB.println("Setting Wi-Fi Connection Mode Failed!");
        return "Error: 4";  //Setting Wi-Fi Connection Mode Failed!
    }
}
counter = 0;
while(!disconnectFromAP()){
  counter++;
    if(counter>=5){
        SerialUSB.println("Wi-Fi Disconnection from AP Failed!");
        return "Error: 5";  //Wi-Fi Disconnection from AP Failed!
    }
}
counter = 0;
while(!connectToAP(APname,APpassword)){
  counter++;
    if(counter>=5){
        SerialUSB.println("Wi-Fi Connecting to AP Failed!");
        return "Error: 6";  //Wi-Fi Connecting to AP Failed!
    }
}
counter = 0;
while(!getIP()){
  counter++;
    if(counter>=5){
        SerialUSB.println("Wi-Fi Getting IP Failed!");
        return "Error: 7";  //Wi-Fi Getting IP Failed!
    }
}

 return "OK";                                    }
示例#3
0
int main()
{
  printf("System Restarted!!!\n");
  //unsigned char mydata[8];

  //strcpy(fifo,"######");

  Uart_init();//Register RS232_RXD
  wifi_init();//initialize the wifi module


  while(1)
  {
	  //led_init();
	 test_key();
	 test_alarm();
	 test_alarm_en();
	  welcome();
	  Alarm();
	  //printf("%X\n",ringbell);
	  //printf("%x",IORD_ALTERA_AVALON_PIO_DATA(MYINPUT_BASE));

	  Uart_send_n("AT",2);
	  Uart_send(0x0d);
	  Uart_send(0x0a);

	  usleep(2000000);//2s
  }
  return 0;
}
示例#4
0
void ICACHE_FLASH_ATTR user_init(void) {
    wifi_init();
    uart_init_new();
    tcp_shell_init();
    UART_SetPrintPort( debugPort );
    xTaskCreate( forthright_task, "forthright", 256, NULL, 2, &tasks[0] ); // create root FORTH interpreter
}
示例#5
0
static void mqtt_app_start(void)
{
    const esp_mqtt_client_config_t mqtt_cfg = {
        .uri = "mqtts://test.mosquitto.org:8884",
        .event_handle = mqtt_event_handler,
        .client_cert_pem = (const char *)client_cert_pem_start,
        .client_key_pem = (const char *)client_key_pem_start,
    };

    ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
    esp_mqtt_client_start(client);
}

void app_main()
{
    ESP_LOGI(TAG, "[APP] Startup..");
    ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
    ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());

    esp_log_level_set("*", ESP_LOG_INFO);
    esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
    esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);

    nvs_flash_init();
    wifi_init();
    mqtt_app_start();

}
示例#6
0
/***********************************************************************
		module		:	[WIFI]
		function	:	[wifi初始化(开机调用)]
  		return		:	[无]
		comment		:	[全局普通函数]
		machine		:	[EH-0818]
		language	:	[CHN]
 		keyword		:	[WIFI]
		date		:	[11/07/25]
 		author		:	[chen-zhengkai]
************************************************************************/
void wifiInit_open()
{
	char ret = 0;	//wifi初始化结果
	char errBuf[25] = {0};	//错误信息
	char retBuf[] = "按任意键返回";	//返回信息
	
	DispStr_CE(0,6,"WIFI初始化中",DISP_CENTER|DISP_CLRSCR);
	DispStr_CE(0,8,"请耐心等待...",DISP_CENTER);
	ret = wifi_init();
	switch ((int)ret) {
		case -1:
			strcpy(errBuf, "模块初始化失败");
			break;
		case -2:
			strcpy(errBuf, "模块连接失败");
			break;
		case -3:
			strcpy(errBuf, "电源设置失败");
			break;
		case -4:
			strcpy(errBuf, "信道设置失败");
			break;
		case -5:
			strcpy(errBuf, "通信速率设置失败");
			break;
	}
	if (ret) {
		DispStr_CE(0,6,errBuf,DISP_CENTER|DISP_CLRSCR);
		DispStr_CE(0,8,retBuf,DISP_CENTER);
		delay_and_wait_key( 3, EXIT_KEY_ALL, 0 );
	}
}
示例#7
0
void user_init(void) {
    uart_set_baud(0, 115200);

    wifi_init();
    if (button_create(BUTTON_PIN, button_callback)) {
        printf("Failed to initialize button\n");
    }
    homekit_server_init(&config);
}
示例#8
0
文件: my_app.c 项目: Halfery/Firmware
int my_app_main(int argc, char *argv[])
{
	//uint8_t buf[100];
	//parameter receiver_arg;
	PX4_INFO("In my_test_app");
	int uart1 = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK);
	if (uart1 < 0) {
		printf("ERROR opening UART1, aborting..\n");
		return uart1;
	}
	struct termios uart1_config;
	int set = fcntl(uart1, F_SETFL, 0);
/*
	receiver_arg.fd = uart1;
	receiver_arg.buf = buf;
	receiver_arg.bytes_num = 1;
*/	

	//struct termios uart1_config_original;

	int termios_state = 0;

	int ret;

	if ((termios_state = tcgetattr(uart1, &uart1_config)) < 0) {
		printf("ERROR getting termios config for UART1: %d\n", termios_state);
		ret = termios_state;
		close(uart1);
		return ret;
	}

	if (cfsetspeed(&uart1_config, B115200) < 0) {
		printf("ERROR setting termios config for UART1: %d\n", termios_state);
		ret = ERROR;
		close(uart1);
		return ret;
	}

	if ((termios_state = tcsetattr(uart1, TCSANOW, &uart1_config)) < 0) {
		printf("ERROR setting termios config for UART1\n");
		ret = termios_state;
		close(uart1);
		return ret;
	}

	printf("c_iflag: %x, c_oflag: %x, c_cflag: %x, c_lflag: %x, speed: %d\n", uart1_config.c_iflag, uart1_config.c_oflag, uart1_config.c_cflag, uart1_config.c_lflag, uart1_config.c_speed);

	int r=0;

	wifi_init(uart1);
	//iniRD();
	r++;
	set++;
	close(uart1);
	return 0;
}
示例#9
0
void ICACHE_FLASH_ATTR user_init(void)
{
    int ret;
    dmsg_init();
    uart_init();
    shell_init(uart0_putchar);
    i2c_init();
    wifi_init();
    xTaskCreate(shell_task, "shell", 256, NULL, tskIDLE_PRIORITY + 2, NULL);
}
示例#10
0
void ICACHE_FLASH_ATTR user_init(void) {
	uart_div_modify(0, UART_CLK_FREQ / BAUD);
	os_printf("Startup\r\n");

	/*** Initialize subsystems ***/
	psu_init();
	ws2811dma_init();
	wifi_init();
	mxp_init(ws2811dma_put);
	psu_server_init();

	/*** Use LED strip as status indicator ***/
	wifi_set_event_handler_cb(onWifiEvent);
	status_indicate(STAT_NO_CONNECT);
}
void wifi_initial_task() {
  struct netif *sta_if;
  wifi_init(&wifi_config, NULL);
  lwip_tcpip_init(&tcpip_config, WIFI_MODE_STA_ONLY);

  ip_ready = xSemaphoreCreateBinary();

  sta_if = netif_find_by_type(NETIF_TYPE_STA);
  netif_set_status_callback(sta_if, _ip_ready_callback);
  dhcp_start(sta_if);

  xSemaphoreTake(ip_ready, portMAX_DELAY);
  mcs_tcp_init(tcp_callback);
  vTaskDelete(NULL);
}
示例#12
0
void app_main()
{
    ESP_LOGI(TAG, "[APP] Startup..");
    ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
    ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());

    esp_log_level_set("*", ESP_LOG_INFO);
    esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_WS", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
    esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);

    nvs_flash_init();
    wifi_init();
    mqtt_app_start();
}
示例#13
0
void user_init(void) {
	stdout_init();
	io_init();
	dht_init(SENSORTYPE, POOLTIME);

	// 0x40200000 is the base address for spi flash memory mapping, ESPFS_POS is the position
	// where image is written in flash that is defined in Makefile.
#ifdef ESPFS_POS
	espFsInit((void*)(0x40200000 + ESPFS_POS));
#else
	espFsInit((void*)(webpages_espfs_start));
#endif
	httpdInit(builtInUrls, 80);

        wifi_init();
	config_init();	
        action_init();
	os_printf("\nESP Ready\n");
}
String wakeupSendSleep(String APname,String APpassword,String data,String path,String servername,String datatype,int port, String* res){
  String str = "";
  String response;
  wifi_init();
  int counter = 0;
  wakeup();
  String APconnect = wifiInit(APname, APpassword);
  if(APconnect == "OK"){
  str = connectAndSend(data,path,servername,datatype,port,res);

  while(!sleep(1000)){
    counter++;
    if(counter>=5){
      SerialUSB.println("Wi-Fi sleeping Failed!");
      return "Error: 13";  //Wi-Fi sleeping Failed!
    }
  }
  }
  else{
    return APconnect;
  }
  return str;
}
示例#15
0
void setup() {

	Serial.begin(115200);

	Notify(PSTR("initializing WiFi\n"));
	wifi_init();

	Notify(PSTR("waiting for connection\n"));
	wifi_connect();

	Notify(PSTR("setting up USB\n"));
	usb_setup();

	hokuyo_data = (char*) malloc(HOKUYO_DATA_LENGTH);
	if (hokuyo_data) {
		Notify(PSTR("hokuyo_data allocated\n"));
	}

	hokuyo_on();
	Notify(PSTR("hokuyo on\n"));

	Wire.begin(I2C_MASTER_ADDRESS);
	Wire.onReceive(receive);
}
示例#16
0
void notmain(void) {
	_output_type output_type = OUTPUT_TYPE_MONITOR;
	uint8_t mac_address[6] ALIGNED;
	struct ip_info ip_config;
	E131Params e131params;
	DMXParams dmxparams;
	uuid_t uuid;
	char uuid_str[UUID_STRING_LENGTH + 1] ALIGNED;

	hardware_init();

	(void) e131params.Load();

	if (e131params.isHaveCustomCid()) {
		memcpy(uuid_str, e131params.GetCidString(), UUID_STRING_LENGTH);
		uuid_str[UUID_STRING_LENGTH] = '\0';
		uuid_parse((const char *)uuid_str, uuid);
	} else {
		hardware_uuid(uuid);
		uuid_unparse(uuid, uuid_str);
	}

	output_type = e131params.GetOutputType();

	if (output_type == OUTPUT_TYPE_MONITOR) {
		//
	} else {
		output_type = OUTPUT_TYPE_DMX;
		(void) dmxparams.Load();
	}

	printf("[V%s] %s Compiled on %s at %s\n", SOFTWARE_VERSION, hardware_board_get_model(), __DATE__, __TIME__);
	printf("WiFi sACN E.131 DMX Out / Real-time DMX Monitor");

	console_set_top_row(3);

	(void) ap_params_init();
	const char *ap_password = ap_params_get_password();

	hardware_watchdog_init();

	console_status(CONSOLE_YELLOW, "Starting Wifi ...");

	wifi_init(ap_password);

	hardware_watchdog_stop();

	printf("ESP8266 information\n");
	printf(" SDK      : %s\n", system_get_sdk_version());
	printf(" Firmware : %s\n\n", wifi_get_firmware_version());

	if (network_params_init()) {
		console_status(CONSOLE_YELLOW, "Changing to Station mode ...");
		if (network_params_is_use_dhcp()) {
			wifi_station(network_params_get_ssid(), network_params_get_password());
		} else {
			ip_config.ip.addr = network_params_get_ip_address();
			ip_config.netmask.addr = network_params_get_net_mask();
			ip_config.gw.addr = network_params_get_default_gateway();
			wifi_station_ip(network_params_get_ssid(), network_params_get_password(), &ip_config);
		}
	}

	const _wifi_mode opmode = wifi_get_opmode();

	if (opmode == WIFI_STA) {
		printf("WiFi mode : Station\n");
	} else {
		printf("WiFi mode : Access Point (authenticate mode : %s)\n", *ap_password == '\0' ? "Open" : "WPA_WPA2_PSK");
	}

	if (wifi_get_macaddr(mac_address)) {
		printf(" MAC address : "MACSTR "\n", MAC2STR(mac_address));
	} else {
		console_error("wifi_get_macaddr");
	}

	printf(" Hostname    : %s\n", wifi_station_get_hostname());

	if (wifi_get_ip_info(&ip_config)) {
		printf(" IP-address  : " IPSTR "\n", IP2STR(ip_config.ip.addr));
		printf(" Netmask     : " IPSTR "\n", IP2STR(ip_config.netmask.addr));
		printf(" Gateway     : " IPSTR "\n", IP2STR(ip_config.gw.addr));
		if (opmode == WIFI_STA) {
			const _wifi_station_status status = wifi_station_get_connect_status();
			printf("      Status : %s\n", wifi_station_status(status));
			if (status != WIFI_STATION_GOT_IP){
				console_error("Not connected!");
				for(;;);
			}
		}
	} else {
		console_error("wifi_get_ip_info");
	}

	if (fota_params_init()) {
		console_newline();
		fota(fota_params_get_server());
		for(;;);
	}

	console_status(CONSOLE_YELLOW, "Starting UDP ...");
	udp_begin(E131_DEFAULT_PORT);

	console_status(CONSOLE_YELLOW, "Join group ...");

	uint32_t group_ip;
	(void)inet_aton("239.255.0.0", &group_ip);
	const uint16_t universe = e131params.GetUniverse();
	group_ip = group_ip | ((uint32_t)(((uint32_t)universe & (uint32_t)0xFF) << 24)) | ((uint32_t)(((uint32_t)universe & (uint32_t)0xFF00) << 8));
	udp_joingroup(group_ip);

	E131Bridge bridge;
	DMXSend dmx;
	DMXMonitor monitor;

	bridge.setCid(uuid);
	bridge.setUniverse(universe);
	bridge.setMergeMode(e131params.GetMergeMode());

	if (output_type == OUTPUT_TYPE_MONITOR) {
		bridge.SetOutput(&monitor);
		console_set_top_row(20);
	} else {
		bridge.SetOutput(&dmx);

		dmx.SetBreakTime(dmxparams.GetBreakTime());
		dmx.SetMabTime(dmxparams.GetMabTime());

		const uint8_t refresh_rate = dmxparams.GetRefreshRate();
		uint32_t period = (uint32_t) 0;

		if (refresh_rate != (uint8_t) 0) {
			period = (uint32_t) (1E6 / refresh_rate);
		}
		dmx.SetPeriodTime(period);
	}

	printf("\nBridge configuration\n");
	const uint8_t *firmware_version = bridge.GetSoftwareVersion();
	printf(" Firmware     : %d.%d\n", firmware_version[0], firmware_version[1]);
	printf(" CID          : %s\n", uuid_str);
	printf(" Universe     : %d\n", bridge.getUniverse());
	printf(" Merge mode   : %s\n", bridge.getMergeMode() == E131_MERGE_HTP ? "HTP" : "LTP");
	printf(" Multicast ip : " IPSTR "\n", IP2STR(group_ip));
	printf(" Unicast ip   : " IPSTR "\n\n", IP2STR(ip_config.ip.addr));

	if (output_type == OUTPUT_TYPE_DMX) {
		printf("DMX Send parameters\n");
		printf(" Break time   : %d\n", (int) dmx.GetBreakTime());
		printf(" MAB time     : %d\n", (int) dmx.GetMabTime());
		printf(" Refresh rate : %d\n", (int) (1E6 / dmx.GetPeriodTime()));
	}

	hardware_watchdog_init();

	console_status(CONSOLE_GREEN, "Bridge is running");

	for (;;) {
		hardware_watchdog_feed();
		(void) bridge.Run();
		led_blink();
	}
}
示例#17
0
int main(void)
{
    int server;

    video_init();
    wifi_init();
    while (!wifi_connect());
    server = wifi_listen();

    while (1) {
	static Connection conn;
	int i;
	uint32 data_goal;
	
	connection_accept(&conn, server);

	conn.card_type = cardmeGetType();
	iprintf("Card type %d\n", conn.card_type);
	if (conn.card_type <= 0) {
	    close(conn.fd);
	    continue;
	}

	conn.card_size = cardmeSize(conn.card_type);
	iprintf("%d byte EEPROM\n", conn.card_size);

	for (conn.address = 0;
	     conn.address < conn.card_size;
	     conn.address += sizeof conn.buffer) {
	    int sent = 0;

	    cardmeReadEeprom(conn.address, conn.buffer, sizeof conn.buffer, conn.card_type);

	    data_goal = Wifi_GetStats(WSTAT_TXDATABYTES) + sizeof conn.buffer;

	    do {
		sent += send(conn.fd, conn.buffer + sent, sizeof conn.buffer - sent, 0);
	    } while (sent < sizeof conn.buffer);

	    /*
	     * dswifi's TCP stack is buggy... or sometihing. It's retransmitting every packet
	     * several times. This seems to help a little. Also, this should help work around
	     * the fact that dswifi doesn't flush any buffers on close().
	     */	   
	    while (Wifi_GetStats(WSTAT_TXDATABYTES) < data_goal) {
		swiWaitForVBlank();
	    }

	    iprintf("(%d bytes)\x1b[60D", conn.address);
	}	
	iprintf("Complete.        \n");

	/*
	 * Wait for the other end to close the connection.
	 * Closing it immediately seems to just lose data in
	 * dswifi's buffers...
	 */
	while (recv(conn.fd, conn.buffer, sizeof conn.buffer, 0) > 0);
	close(conn.fd);
    }

    return 0;
}
示例#18
0
文件: main.c 项目: elzk/nds-ide
int
main(void)
{
    int ret;
    int run, debug;

#ifndef _WIN32
	consoleDemoInit();
	fatInitDefault();
#endif

	iprintf("DallShell, %s %s\n", __DATE__, __TIME__);
	iprintf("nds.sevencore.co.kr\n");

	switch (Config.download_channel) {
        case CHANNEL_WIFI   :
            if (wifi_init()) {
                iprintf("WIFI Initialize Error\n");
                return -1;
            }
            break;
        case CHANNEL_USB    :
            if (usb_init()) {
                iprintf("USB Initialize Error\n");
                return -1;
            }
            break;
        case CHANNEL_SERIAL :
            if (serial_init()) {
                iprintf("Serial Initialize Error\n");
                return -1;
            }
            break;
        default :
            iprintf("Configuration Error\n");
            break;
	}

loop:
	if ((ret = download(CHANNELS + Config.download_channel, &run, &debug)) == 0) {
	    iprintf("Download Succefully Done\n");
	} else {
        iprintf("Download Stoped by Error %d\n", ret);
        goto loop;
	}
	if (run) {
	    extern void _copy_bin_and_jump(void);
	    extern unsigned char XXX_BUF_[];
	    void (*calljump)(void);

	    calljump = (void(*)(void))XXX_BUF_;
	    iprintf("\n\n\n\n\nDOWNLOAD DONE and COPY\n\n\n\n");
	    _copy_bin_and_jump();                  // Call to jump.s
        iprintf("COPY DONE and JUMP\n\n\n\n");
        { unsigned char *p = XXX_BUF_;
          int i;
          for (i = 0; i < 48; i++)
              printf("%02X ", *p++);
          iprintf("\n----\n");
        }

        calljump();
	    // RIP : never return
	}
	iprintf("Now What to do ? - LOOP !\n");
	goto loop;
    return 0;
}
示例#19
0
void monitor(void){
  uint32_t prev_tick=0;

  //allocate memory for buffers and flush them
  cmd_buf = membag_alloc(CMD_BUF_SIZE);
  if(!cmd_buf)
    core_panic();
  memset(cmd_buf,0x0,CMD_BUF_SIZE);
  //initialize the power packet buffers
  tx_pkt = &power_pkts[0];
  cur_pkt = &power_pkts[1];
  //both are empty
  tx_pkt->status = POWER_PKT_EMPTY;
  cur_pkt->status = POWER_PKT_EMPTY;

  //initialize runtime configs
  wemo_config.echo = false;
  wemo_config.debug_level = DEBUG_ERROR;
  wemo_config.collect_data = true; //collect power data

  //check if we are on USB
  if(gpio_pin_is_high(VBUS_PIN)){
    rgb_led_set(LED_LT_BLUE,0); 
    //don't start wifi because we are configuring
    b_wifi_enabled=false;
    //don't collect power data
    wemo_config.collect_data = false;
  }
  //check if the plug is in calibrate mode
  if(wemo_config.calibrate){
    //start the calibration PWM
    pwm_channel_enable_interrupt(PWM,CAL_PWM_CHANNEL,CAL_PWM_CHANNEL);
    pwm_channel_enable(PWM,CAL_PWM_CHANNEL);
    //don't start wifi because we are in calibration mode
    b_wifi_enabled=false;
    wemo_config.standalone = true;
    wemo_config.collect_data = false;
    //indicate cal mode with a purple LED
    rgb_led_set(LED_PURPLE,0);
  }
  //check if reset is pressed
  if(gpio_pin_is_low(BUTTON_PIN)){
    //erase the configs
    memset(wemo_config.nilm_id,0x0,MAX_CONFIG_LEN);
    memset(wemo_config.nilm_ip_addr,0x0,MAX_CONFIG_LEN);
    memset(wemo_config.wifi_ssid,0x0,MAX_CONFIG_LEN);
    memset(wemo_config.wifi_pwd,0x0,MAX_CONFIG_LEN);
    //save the erased config
    fs_write_config();
    core_log("erased config");
    //erase the stored data 
    
    //spin until button is released
    rgb_led_set(LED_ORANGE,500);
    while(gpio_pin_is_low(BUTTON_PIN));
    rgb_led_set(LED_ORANGE,0); //disable blink
  }
  //setup WIFI
  if(b_wifi_enabled){
    if(wifi_init()!=0){
      rgb_led_set(LED_PURPLE,0);
    }
    else{
      //good to go! turn light green
      rgb_led_set(LED_LT_GREEN,0);
    }
  }
  //initialize the wifi_rx buffer and flag
  wifi_rx_buf_full = false;
  memset(wifi_rx_buf,0x0,WIFI_RX_BUF_SIZE);
  while (1) {
    //***** SYS TICK ACTIONS ******
    if(sys_tick!=prev_tick){
      //check if there is a valid wemo sample
      if(wemo_sample.valid==true && wemo_config.collect_data){
	core_log_power_data(&wemo_sample);
      }
      wemo_read_power();
      wdt_restart(WDT);
      prev_tick = sys_tick;
    }
    //check for pending data from the Internet
    if(wifi_rx_buf_full){
      core_process_wifi_data();
      wifi_rx_buf_full=false;
    }
    //see if we have any commands to run
    if(cmd_buf_full){
      runcmd(cmd_buf); //  run it
      //clear the buffer
      cmd_buf_idx = 0;
      memset(cmd_buf,0x0,CMD_BUF_SIZE);
      if(wemo_config.echo)
	printf("\r> "); //print the prompt
      cmd_buf_full=false;
    }
  }
    
}
示例#20
0
/////////////////////////
// core_log_power_data
//     Add a power_sample to the current power_pkt
//     When the pkt is full switch to the other pkt
//     (ping pong buffer). Throws an error if the 
//     next buffer is not empty (still being TX'd)
void core_log_power_data(power_sample *sample){
  static int wemo_sample_idx = 0;
  static int dropped_pkt_count = 0; //reset wifi when this reaches MAX_DROPPED_PACKETS
  power_pkt *tmp_pkt;
  //check for error conditions
  switch(cur_pkt->status){
  case POWER_PKT_EMPTY:
    if(wemo_sample_idx!=0){
      printf("Error, empty packet but nonzero index\n");
      return;
    }
    //set the timestamp for the packet with the first one
    rtc_get_time_str(cur_pkt->timestamp,PKT_TIMESTAMP_BUF_SIZE);
    break;
  case POWER_PKT_TX_IN_PROG:
    printf("Error, this packet is still being transmitted\n");
    return;
  case POWER_PKT_TX_FAIL:
    printf("Error, this packet failed TX and isn't clean\n");
    break;
  case POWER_PKT_READY:
    if(wemo_config.debug_level>=DEBUG_WARN)
      printf("Transmit this packet first!\n");
    //see if the other buffer is ready, if so set this up for
    //transmission and start filling the other one
    if(tx_pkt->status==POWER_PKT_EMPTY){
      tmp_pkt = cur_pkt;
      cur_pkt = tx_pkt;
      tx_pkt = tmp_pkt;
      wemo_sample_idx = 0;
    }
    return;
  }
  cur_pkt->status = POWER_PKT_FILLING;
  cur_pkt->vrms[wemo_sample_idx]  = sample->vrms;
  cur_pkt->irms[wemo_sample_idx]  = sample->irms;
  cur_pkt->watts[wemo_sample_idx] = sample->watts;
  cur_pkt->pavg[wemo_sample_idx]  = sample->pavg;
  cur_pkt->freq[wemo_sample_idx]  = sample->freq;
  cur_pkt->pf[wemo_sample_idx]    = sample->pf;
  cur_pkt->kwh[wemo_sample_idx]   = sample->kwh;
  wemo_sample_idx++;
  if(wemo_sample_idx==PKT_SIZE){
    cur_pkt->status=POWER_PKT_READY;
    //save the packet to disk
    fs_write_power_pkt(cur_pkt);
    //see if we can switch buffers
    if(tx_pkt->status==POWER_PKT_EMPTY){
      tmp_pkt = cur_pkt;
      cur_pkt = tx_pkt;
      tx_pkt = tmp_pkt;
      //reset dropped packet counter b/c successful transmission
      dropped_pkt_count = 0;
    } else {
      //other buffer is being TX'd, erase this one and refill
      cur_pkt->status=POWER_PKT_EMPTY;
      //if this happens [MAX_DROPPED_PACKETS] times in a row, reset the wifi
      //***Disable this for SmartEE since we aren't necessarily pinging it for data 
      // all the time, if you set up a daemon to monitor the plugs, then this can be 
      // enabled to act as a type of watchdog reset on the wifi ***
      if(dropped_pkt_count++ > MAX_DROPPED_PACKETS){
	dropped_pkt_count = 0;
	core_log("lost NILM, load off and resetting WiFi");
	printf("lost NILM, load off and resetting WiFi");
	//turn off relay for safety (since we lost control of the plug)
	gpio_set_pin_low(RELAY_PIN);
	//restart the wifi
	wifi_init();
      }
      //if(wemo_config.debug_level>=DEBUG_WARN)
      //printf("dropped packet before TX'd\n");
    }
    //start filling the new buffer
    wemo_sample_idx = 0;
  }
}
示例#21
0
void do_command()
{
    wifi_init();
    // main command line loop
    while(1)
    {
        CLEAR_CMD_BUF();
        CLEAR_SEND_BUF();
        printf("$: ");
        // get user's command and put it in cmd_buf
        fgets(cmd_buf, BUF_SIZE-1, stdin);

        // quit
        if(strcmp(cmd_buf, "q\n") == 0)
            return;

        // toggle socket.
        else if((cmd_buf[0] == 's') && (cmd_buf[1] <= '3' && cmd_buf[1] >= '1'))
        {
            if(strcmp(cmd_buf+2, "1\n") == 0)
                send_cmd_toggle_socket(cmd_buf[1], SOCKET_ON);

            else if(strcmp(cmd_buf+2, "0\n") == 0)
                send_cmd_toggle_socket(cmd_buf[1], SOCKET_OFF);

            else
                PRINT_USAGE_AND_CONTINUE();
        }
        // socket state
        else if(strcmp(cmd_buf, "ss\n") == 0)
            send_cmd_request_socket_status();
        // all on
        else if(strcmp(cmd_buf, "a1\n") == 0)
        {
            for(char i = '1'; i <= '4'; i ++)
                send_cmd_toggle_socket(i, SOCKET_ON);
        }
        // all off
        else if(strcmp(cmd_buf, "a0\n") == 0)
        {
            for(char i = '1'; i <= '4'; i++)
                send_cmd_toggle_socket(i, SOCKET_OFF);
        }
        // set time
        else if(strcmp(cmd_buf, "st\n") == 0)
            send_cmd_set_time();
        // calculate energy
        else if(cmd_buf[0] == 'e' && is_number(cmd_buf[1])) // e3h
        {
            int32_t duration = atoi(&cmd_buf[1]);
            if(duration == 0)
                PRINT_USAGE_AND_CONTINUE();

            // get the position of the first letter after numbers
            int32_t i = 1;
            for(; i < strlen(cmd_buf) - 1; i++)
                if(!is_number(cmd_buf[i]))
                    break;

            printf("energy used during the past %d ", duration);
            switch(cmd_buf[i])
            {
                case 'h':
                printf("hour");
                if(duration > 1)
                    printf("s");
                printf(":\n");
                send_cmd_energy_query(time(0) - ONE_HOUR_IN_SEC * duration, time(0));
                break;

                case 'd':
                printf("day");
                if(duration > 1)
                    printf("s");
                printf(":\n");
                send_cmd_energy_query(time(0) - ONE_DAY_IN_SEC * duration, time(0));
                break;

                case 'w':
                printf("week");
                if(duration > 1)
                    printf("s");
                printf(":\n");
                send_cmd_energy_query(time(0) - ONE_DAY_IN_SEC * 7 * duration, time(0));
                break;

                case 'm':
                printf("month");
                if(duration > 1)
                    printf("s");
                printf(":\n");
                send_cmd_energy_query(time(0) - ONE_DAY_IN_SEC * 30 * duration, time(0));
                break;

                case 'y':
                printf("year");
                if(duration > 1)
                    printf("s");
                printf(":\n");
                send_cmd_energy_query(time(0) - ONE_DAY_IN_SEC * 365 * duration, time(0));
                break;

                default:
                printf("\'%c\'? I don't know what that is.\n", cmd_buf[i]);
                printf("e#[h,d,w,m,y]: get energy usage for the last # hour/day/week/month/year\n");
                continue;
            }
        }
        // energy between two points in time
        // eg YYYY MM DD hr min sec YYYY MM DD hr min sec
        else if(strncmp(cmd_buf, "eq ", 3) == 0)
        {
            int32_t date_valus[12];
            for(int32_t i = 0, j = 0; i < strlen(cmd_buf) - 1; i++)
                if((cmd_buf[i] == ' ') && (cmd_buf[i + 1] != ' '))
                {
                    date_valus[j] = atol(&cmd_buf[i]);
                    if(++j >= 12)
                        break;
                }
            struct tm start_tm_local, end_tm_local;
            start_tm_local.tm_year = date_valus[0] - 1900;
            start_tm_local.tm_mon = date_valus[1] - 1;
            start_tm_local.tm_mday = date_valus[2];
            start_tm_local.tm_hour = date_valus[3];
            start_tm_local.tm_min = date_valus[4];
            start_tm_local.tm_sec = date_valus[5];
            start_tm_local.tm_isdst = -1;
            end_tm_local.tm_year = date_valus[6] - 1900;
            end_tm_local.tm_mon = date_valus[7] - 1;
            end_tm_local.tm_mday = date_valus[8];
            end_tm_local.tm_hour = date_valus[9];
            end_tm_local.tm_min = date_valus[10];
            end_tm_local.tm_sec = date_valus[11];
            end_tm_local.tm_isdst = -1;
            send_cmd_energy_query(mktime(&start_tm_local), mktime(&end_tm_local));
        }
        // debug command, flush recv_buf
        else if(strcmp(cmd_buf, "f\n") == 0)
            flush_recv_buf(1);
        else
            PRINT_USAGE_AND_CONTINUE();
    }
}
示例#22
0
void core_process_wifi_data(void){
  int BUF_SIZE=XL_BUF_SIZE;
  char *buf;
  int chan_num, data_size, r;
  unsigned int red,green,blue, blink;
  unsigned int yr,mo,dt,dw,hr,mn,sc;
  int time_buf_size =  MD_BUF_SIZE;
  char *time_buf;

  //match against the data
  if(strlen(wifi_rx_buf)>BUF_SIZE){
    printf("can't process rx'd packet, too large\n");
    core_log("can't process rx'd packet, too large");
    return;
  }
  //allocate memory
  buf = core_malloc(BUF_SIZE);
  r=sscanf(wifi_rx_buf,"\r\n+IPD,%d,%d:%s", &chan_num, &data_size, buf);
  if(r!=3){
    printf("rx'd corrupt data, ignoring\n");
    core_log("rx'd corrupt data, ignoring\n");
    //free memory
    core_free(buf);
    return;
  }

  if(wemo_config.debug_level>DEBUG_INFO)
    printf("Got [%d] bytes on channel [%d]\n",
	   data_size, chan_num);
  //discard responses from the NILM to power logging packets, but keep the response
  //if another core function has requested some data, this is done with the callback 
  //function. The requesting core function registers a callback and this function calls
  //it and then resets the callback to NULL
  if(chan_num==4){
    //close the socket
    wifi_send_cmd("AT+CIPCLOSE=4","Unlink",buf,BUF_SIZE,1);
    //execute the callback
    if(tx_callback!=NULL){
      (*tx_callback)(wifi_rx_buf);
      tx_callback=NULL;
    }
    //clear the server buffer
    memset(wifi_rx_buf,0x0,WIFI_RX_BUF_SIZE);
    //free memory
    core_free(buf);
    return;
  }
  ///////////////////
  //this data must be inbound to the server port, process the command
  //
  //     RELAY ON
  if(strcmp(buf,"relay_on")==0){
    gpio_set_pin_high(RELAY_PIN);
    printf("relay ON\n");
    //return "OK" to indicate success
    wifi_send_txt(0,"OK");
  }
  //     RELAY OFF
  else if(strcmp(buf,"relay_off")==0){
    gpio_set_pin_low(RELAY_PIN);
    printf("relay OFF\n");
    //return "OK" to indicate success
    wifi_send_txt(0,"OK");
  }
  //     LED SET
  else if(strstr(buf,"set_led")==buf){
    if(sscanf(buf,"set_led_%u_%u_%u_%u.",&red,&green,&blue,&blink)!=4){
      core_log("corrupt led_set request");
    } else {
      rgb_led_set(red,green,blue,blink);
      if(wemo_config.echo)
	printf("set led: [%u, %u, %u, %u]\n",red,green,blue,blink);
      wifi_send_txt(0,"OK");
    }
  }
  //     RTC SET
  else if(strstr(buf,"set_rtc")==buf){
    if(sscanf(buf,"set_rtc_%u_%u_%u_%u_%u_%u_%u.",
	      &yr,&mo,&dt,&dw,&hr,&mn,&sc)!=7){
      core_log("corrupt rtc_set request");
    } else {
      if(i2c_rtc_set_time(sc,mn,hr,dw,dt,mo,yr)!=0)
	printf("error setting RTC\n");
      else{
	time_buf = membag_alloc(time_buf_size);
	if(time_buf==NULL)
	  core_panic();
	rtc_get_time_str(time_buf,time_buf_size);
	if(wemo_config.echo)
	  printf("wifi set rtc to: %s\n",time_buf);
	core_log("wifi set rtc");
	membag_free(time_buf);
	wifi_send_txt(0,"OK");
      }
    }
  }
  //     SEND DATA
  else if(strcmp(buf,"send_data")==0){
    if(tx_pkt->status!=POWER_PKT_READY){
      r = wifi_send_txt(chan_num,"error: no data");
      if(r==TX_ERR_MODULE_RESET)
	while(wifi_init()!=0); //fail!!! anger!!!! reset the module
    } else {
      //send the data
      r=wifi_send_raw(chan_num,(uint8_t*)tx_pkt,sizeof(*tx_pkt));
      if(r==TX_ERR_MODULE_RESET){
	while(wifi_init()!=0); //fail!! anger!!! reset the module
      } else {
	//clear out the packet so we can start again
	memset(tx_pkt,0,sizeof(*tx_pkt));
	tx_pkt->status=POWER_PKT_EMPTY;
	if(wemo_config.debug_level>=DEBUG_INFO)
	  printf("sent data\n");
      }
    }
  }
  else{
    printf("unknown command: %s\n",buf);
    wifi_send_txt(chan_num,"error: unknown command");
    //free memory
    core_free(buf);
    return;
  }
  //clear the server buffer
  memset(wifi_rx_buf,0x0,WIFI_RX_BUF_SIZE);
  //free the memory
  core_free(buf);
  return;
}
示例#23
0
void core_transmit_power_packet_http(power_pkt *wemo_pkt){
  int r, i, j;
  int TX_BUF_SIZE = XL_BUF_SIZE;
  int PAYLOAD_BUF_SIZE = XL_BUF_SIZE;
  int DATA_BUF_SIZE = MD_BUF_SIZE;
  char *tx_buf, *payload_buf;
  char *bufs[7];
  int32_t *srcs[7] = {wemo_pkt->vrms, wemo_pkt->irms, wemo_pkt->pavg, wemo_pkt->watts,
		    wemo_pkt->pf, wemo_pkt->freq, wemo_pkt->kwh};
  char *buf; int32_t *src;
  
  //make sure all the data is present
  if(wemo_pkt->status != POWER_PKT_READY){
    printf("Error, packet is not ready to tx!\n");
    return;
  }
  //now we are filling up the POST request
  wemo_pkt->status = POWER_PKT_TX_IN_PROG;

  //allocate memory for the POST request
  tx_buf = core_malloc(TX_BUF_SIZE);
  payload_buf = core_malloc(DATA_BUF_SIZE);

  //print out the data arrays as strings
  for(j=0;j<7;j++){
    src = srcs[j];
    buf = core_malloc(DATA_BUF_SIZE);
    bufs[j] = buf;
    for(i=0;i<PKT_SIZE;i++){
      snprintf(buf+strlen(buf),DATA_BUF_SIZE,"%li",src[i]);
      if(i<(PKT_SIZE-1))
	snprintf(buf+strlen(buf),DATA_BUF_SIZE,", ");
    }
  }
  //stick them in a json format
  snprintf(payload_buf,PAYLOAD_BUF_SIZE,
	   "{\"plug\":\"%s\",\"ip\":\"%s\",\"time\":\"%s\","
	   "\"vrms\":[%s],\"irms\":[%s],\"watts\":[%s],\"pavg\":[%s],"
	   "\"pf\":[%s],\"freq\":[%s],\"kwh\":[%s]}",
	   wemo_config.serial_number,wemo_config.ip_addr,wemo_pkt->timestamp,
	   bufs[0],bufs[1],bufs[2],bufs[3],bufs[4],bufs[5],bufs[6]);
  snprintf(tx_buf,TX_BUF_SIZE,
	     "POST /config/plugs/log HTTP/1.1\r\n"
	     "User-Agent: WemoPlug\r\n"
	     "Host: NILM\r\nAccept:*/*\r\n"
	     "Connection: keep-alive\r\n"
	     "Content-Type: application/json\r\n"
	     "Content-Length: %d\r\n"
	     "\r\n%s",
	     strlen(payload_buf),payload_buf);
  //send the packet!
  r = wifi_transmit(wemo_config.nilm_ip_addr,80,tx_buf);
  switch(r){
  case TX_SUCCESS:
    wemo_pkt->status = POWER_PKT_EMPTY;
    break;
  case TX_BAD_DEST_IP: //if we can't find NILM, get its IP from the manager
    wemo_pkt->status = POWER_PKT_EMPTY; //just dump the packet
    core_get_nilm_ip_addr();
    break;
  case TX_ERR_MODULE_RESET:
    wifi_init(); //re-initialize WiFi on reset error
  case TX_ERROR: //just fall through and register the failure
  case TX_TIMEOUT:
  default:
    wemo_pkt->status = POWER_PKT_TX_FAIL;
  }
  //free memory
  core_free(tx_buf);
  core_free(payload_buf);
  for(j=0;j<7;j++){
    core_free(bufs[j]);
  }
}
示例#24
0
void notmain(void) {
	hardware_init();

	ltc_reader_params_init();

	output.console_output = ltc_reader_params_is_console_output();
	output.lcd_output = ltc_reader_params_is_lcd_output();
	output.midi_output = ltc_reader_params_is_midi_output();
	output.artnet_output = ltc_reader_params_is_artnet_output();

	if(output.midi_output) {
		midi_send_init();
	}

	if (output.lcd_output) {
		output.lcd_output = lcd_detect();
	}

	if (output.artnet_output) {
		output.artnet_output = wifi_detect();
	}

	ltc_reader_init(&output);

	printf("[V%s] %s Compiled on %s at %s\n", SOFTWARE_VERSION, hardware_board_get_model(), __DATE__, __TIME__);
	printf("SMPTE TimeCode LTC Reader / Converter");

	console_set_top_row(3);

	console_set_cursor(0, 12);
	console_puts("Console output : "); handle_bool(output.console_output); console_putc('\n');
	console_puts("LCD output     : "); handle_bool(output.lcd_output); console_putc('\n');
	console_puts("MIDI output    : "); handle_bool(output.midi_output); console_putc('\n');
	console_puts("ArtNet output  : "); handle_bool(output.artnet_output);console_puts(" (not implemented)\n");

	if (output.artnet_output) {
		uint8_t mac_address[6];
		struct ip_info ip_config;

		(void) ap_params_init();
		const char *ap_password = ap_params_get_password();

		console_status(CONSOLE_YELLOW, "Starting Wifi ...");

		wifi_init(ap_password);

		printf("\nESP8266 information\n");
		printf(" SDK      : %s\n", system_get_sdk_version());
		printf(" Firmware : %s\n\n", wifi_get_firmware_version());

		if (network_params_init()) {
			console_status(CONSOLE_YELLOW, "Changing to Station mode ...");
			if (network_params_is_use_dhcp()) {
				wifi_station(network_params_get_ssid(), network_params_get_password());
			} else {
				ip_config.ip.addr = network_params_get_ip_address();
				ip_config.netmask.addr = network_params_get_net_mask();
				ip_config.gw.addr = network_params_get_default_gateway();
				wifi_station_ip(network_params_get_ssid(), network_params_get_password(), &ip_config);
			}
		}

		const _wifi_mode opmode = wifi_get_opmode();

		if (opmode == WIFI_STA) {
			printf("WiFi mode : Station\n");
		} else {
			printf("WiFi mode : Access Point (authenticate mode : %s)\n", *ap_password == '\0' ? "Open" : "WPA_WPA2_PSK");
		}

		if (wifi_get_macaddr(mac_address)) {
			printf(" MAC address : "MACSTR "\n", MAC2STR(mac_address));
		} else {
			console_error("wifi_get_macaddr");
		}

		printf(" Hostname    : %s\n", wifi_station_get_hostname());

		if (wifi_get_ip_info(&ip_config)) {
			printf(" IP-address  : " IPSTR "\n", IP2STR(ip_config.ip.addr));
			printf(" Netmask     : " IPSTR "\n", IP2STR(ip_config.netmask.addr));
			printf(" Gateway     : " IPSTR "\n", IP2STR(ip_config.gw.addr));
			if (opmode == WIFI_STA) {
				const _wifi_station_status status = wifi_station_get_connect_status();
				printf("      Status : %s\n", wifi_station_status(status));
				if (status != WIFI_STATION_GOT_IP){
					console_error("Not connected!");
					for(;;);
				}
			}
		} else {
			console_error("wifi_get_ip_info");
		}

		console_status(CONSOLE_YELLOW, "Starting UDP ...");
		udp_begin(6454);

		console_status(CONSOLE_GREEN, "Wifi is started");
	}

	for (;;) {
		ltc_reader();
	}
}