Arduino + ESP8266模块TCP通信

light2.py

wifi_20170601_1.ino

#include <SoftwareSerial.h>
#include <FastLED.h>

#define LED_DATA_PIN 3 // led spi data pin
#define NUM_LEDS 120

#define ctsPin 2 // Pin for capactitive touch sensor

CRGB leds[NUM_LEDS]; // all leds' color data

// RGB random color data
int Rlist[] = {255, 21, 0, 0, 0, 128};
int Glist[] = {5, 174, 255, 225, 0, 0};
int Blist[] = {180, 103, 0, 255, 255, 255};

// software serial for esp8266 wifi
SoftwareSerial mySerial(10, 11); // RX, TX 配置10、11为软串口

void setup()
{
  Serial.begin(115200);
  mySerial.begin(115200);

  pinMode(ctsPin, INPUT);
  FastLED.addLeds<WS2811, LED_DATA_PIN, RGB>(leds, NUM_LEDS);

LABEL_RETRY:
  delay(2000);
  send_wifi_at("AT", 100, "OK");
  send_wifi_at("ATE1", 100, "OK");
  delay(1000);
  send_wifi_at("AT+CWMODE=3", 100, "OK");
  send_wifi_at("AT+CWQAP", 100, "OK");
  send_wifi_at("AT+RST", 5000, "WIFI GOT IP");

  Serial.println("Connecting Wifi....");

  // send_wifi_at("AT+CWJAP=\"PP\",\"1234pppp\"", 5000, "CONNECTED");
  send_wifi_at("AT+CWJAP=\"MIWIFI8\",\"12345678\"", 5000, "CONNECTED");

  // send_wifi_at("AT+CIPMUX=0", 100, "");
  Serial.println("lalala");
  delay(1000);

  send_wifi_at("AT+CIPSTART=\"TCP\",\"192.168.31.156\",1234", 5000, "CONNECT");
  // send_wifi_at("AT+CIPSTART=\"TCP\",\"172.20.10.2\",1234", 5000, "CONNECT");

  delay(2000);
  send_wifi_at("AT+CIPMODE=1", 1000, "OK");
  delay(2000);

  bool final_result = send_wifi_at("AT+CIPSEND", 1000, "OK");
  if (!final_result)
  {
    Serial.println("I cannot connect, goto retry..");
    goto LABEL_RETRY;
  }
  delay(1000);
  // eat all extra messages
  while (mySerial.available())
  {
    Serial.write(mySerial.read());
    delay(100);
  }
  Serial.println("eat messages end.");
  delay(1000);
  mySerial.write("-");
  Serial.println("setup() end.");
}

int color_index = -1;

void loop()
{
  if (color_index == -1) {
    color_index = check_touch_change_color();
  }
  if (mySerial.available())
  {
    int one_char = mySerial.read();
    change_color_from_wifi(one_char);
    // forwarding a char from usb to wifi
    Serial.write(one_char);

    // check touch sensor
    if (color_index == -1) mySerial.print("-");
    else {
      mySerial.print(color_index);
      color_index = -1;
    }
    // then delay and eat on char
    delay(100);
    mySerial.read();
  }

  // forwarding a char from usb to wifi
  if (Serial.available())
    mySerial.write(Serial.read());
}

// change color from wifi by one character
void change_color_from_wifi(int one_char)
{
  Serial.print("one_char=");
  Serial.println(one_char);

  if (one_char > 48 && one_char <= 60)
  {
    Serial.println("set_color in 12 colors");
    set_color(22 * (one_char - 48), 255, 0);
  }
  else
  {
    Serial.println("NOT in 12 colors");
  }
}

// previous value of touch sensor
int ctsValue = LOW;

// check need change color from touch
int check_touch_change_color()
{
  int color_index = -1;
  ctsValue = digitalRead(ctsPin);

  if (ctsValue == HIGH)
  {
    Serial.println("Touch detected!!");
    int colorpop = random(6);
    color_index = colorpop;
    int r = Rlist[colorpop];
    int g = Glist[colorpop];
    int b = Blist[colorpop];

    set_color(r, g, b);
    Serial.print("set_color: ");
    Serial.print(r);
    Serial.print(",");
    Serial.print(g);
    Serial.print(",");
    Serial.print(b);
    Serial.println();
  }
  return color_index;
}

// change all led to one color
void set_color(int r, int g, int b)
{
  for (int i = 0; i < NUM_LEDS; i++)
  {
    // 检查下是grb还是rgb?
    leds[i] = CRGB(r, g, b);
  }
  FastLED.show();
}

// send AT command and wait for OK
bool send_wifi_at(String cmd, int t, String expected)
{
  Serial.print("[DEBUG] command: " + cmd + " in ");
  Serial.print(t);
  Serial.println(" ms");

  delay(100); // must have a delay here
  mySerial.println(cmd);
  delay(100);
  String line = String();
  for (int retry = 0; retry < 3; retry++)
  {
    delay(t);
    while (mySerial.available())
    {
      char c = mySerial.read();
      line += c;
      if (c == '\n' || c == '\r')
      {
        String trimLine = String(line);
        line = ""; // clear prev line
        trimLine.trim();
        if (trimLine.length() > 0) {
          Serial.print("[DEBUG] wifi: ");
          Serial.println(trimLine);
        }
        if (trimLine.indexOf(expected) >= 0)
        {
          Serial.println("[DEBUG] FOUND EXPECTED");
          return true;
        }
      }
    }
  }
  Serial.println("[DEBUG] retried 3 times.");
  return false;
}



#!/usr/bin/python

import socket
import threading
import random
import time
import datetime

time_dict = {}

def need_refresh_minute(ip):
    global time_dict
    last_minute = time_dict.get(ip, -1)
    t = datetime.datetime.now()
    current = t.minute
    if last_minute != current:
        time_dict[ip] = current
        last_minute = current
        minute_12 = current % 12
        print "need_refresh_minute: ", minute_12
        return minute_12
    return -1
def need_refresh_hour(ip):
    global time_dict
    last_hour = time_dict.get(ip, -1)
    t = datetime.datetime.now()
    current = t.hour
    if last_hour != current:
        time_dict[ip] = current
        hour_12 = current % 12
        print "need_refresh_hour: ", hour_12
        return hour_12
    return -1
class ThreadedServer(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((self.host, self.port))

    def listen(self):
        self.sock.listen(5)
        while True:
            client, address = self.sock.accept()
            print "connected: ", client, address
            client.settimeout(60)
            threading.Thread(target = self.listenToClient, args = (client, address)).start()

    def listenToClient(self, client, address):
        size = 1024
        while True:
            try:
                data = client.recv(size)
                if data:
                    print client, address, data
                    ip = address[0]
                    time.sleep(0.2) # must delay for arduino setup loop
                    # tcp connecting from arduino is ready for response
                    need_refresh = need_refresh_minute(ip)
                    if need_refresh != -1:
                        # need refresh light
                        # need_refresh -> index mapping is 0->11, 1->0, 2->1, etc.. 11->10
                        color_index = (need_refresh + 11) % 12
                        color_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<']
                        color_char = color_list[color_index]
                        print "New Refresh! color_index: " + str(color_index) + ", color_char: " + color_char
                        client.send(color_char)
                    else:
                        print "No refresh, sleep 5 seconds for arduino's next pull"
                        time.sleep(5) # sleep 5s for arduino's next pull
                        print "No refresh, wake up, send '0' for no change."
                        client.send("0");
                    # initialize, sleep or directly response, all need to close this connection
            except Exception, ex:
                print repr(ex)
                print "close a connection"
                client.close()
                return False

if __name__ == "__main__":
    print "preparing to listen on port 1234.."
    ThreadedServer('0.0.0.0', 1234).listen()
    print "exited."

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">