示例#1
0
void setup() {
  Serial.begin(9600);
  Serial.println("$CLS#Setup()");
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  LcdInit();

  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    PulseLed(RED, 2, 10, 10);
    PulseLed(BLUE, 2, 10, 10);
    PulseLed(GREEN, 2, 10, 10);

    Serial.print(".");
    LcdPrint(".");
  }
  Udp.begin(localPort);
  setSyncInterval(300);
  setSyncProvider(getNtpTime);

  // Turn on the backlight.
  LcdClear();
  LcdnoBacklight();
  delay(2000);
  LcdBacklight();
}
unsigned long getNTPTimestamp()
{
  unsigned long ulSecs2000;
  
  udp.begin(ntpPort);
  sendNTPpacket(timeServer); // send an NTP packet to a time server
  delay(1000);    // wait to see if a reply is available
  int cb = udp.parsePacket();

  if(!cb)
  {
    Serial.println("Timeserver not accessible! - No RTC support!"); 
    ulSecs2000=0;
  }
  else
  {
    Serial.print("packet received, length=");
    Serial.println(cb);
    udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
    
    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    ulSecs2000  = highWord << 16 | lowWord;
    ulSecs2000 -= 2208988800UL; // go from 1900 to 1970
    ulSecs2000 -= 946684800UL; // go from 1970 to 2000
  }    
  return(ulSecs2000);
}
示例#3
0
AJ_Status AJ_Net_MCastUp(AJ_MCastSocket* mcastSock)
{
    uint8_t ret = 0;

    AJ_InfoPrintf(("AJ_Net_MCastUp(mcastSock=0x%p)\n", mcastSock));

    //
    // Arduino does not choose an ephemeral port if we enter 0 -- it happily
    // uses 0 and then increments each time we bind, up through the well-known
    // system ports.
    //
    ret = g_clientUDP.begin(AJ_EphemeralPort());

    if (ret != 1) {
        g_clientUDP.stop();
        AJ_ErrPrintf(("AJ_Net_MCastUp(): begin() fails. status=AJ_ERR_READ\n"));
        return AJ_ERR_READ;
    } else {
        AJ_IOBufInit(&mcastSock->rx, rxData, sizeof(rxData), AJ_IO_BUF_RX, (void*)&g_clientUDP);
        mcastSock->rx.recv = AJ_Net_RecvFrom;
        AJ_IOBufInit(&mcastSock->tx, txData, sizeof(txData), AJ_IO_BUF_TX, (void*)&g_clientUDP);
        mcastSock->tx.send = AJ_Net_SendTo;
    }

    AJ_InfoPrintf(("AJ_Net_MCastUp(): status=AJ_OK\n"));
    return AJ_OK;
}
示例#4
0
bool radioControlInit() {
  bool result = true;

  if (WiFi.status() == WL_NO_SHIELD) {
    printf( "WiFi shield not present\n");
    result = false;
  }

  String fv = WiFi.firmwareVersion();
  if (fv != "1.1.0") {
    printf( "Please upgrade the firmware\n");
  }

  while (status != WL_CONNECTED) {
     printf( "Attempting to start AP with SSID: %s\n",ssid);
	status = WiFi.apbegin(ssid, channel);
    delay(10000);
  }

  printf( "AP mode already started\n");
   printWifiData();
   printCurrentNet();

   printf( "Establish WiFi Server\n");
  
   Udp.begin(localPort);

  
  memset(receiverBuffer, '\0', sizeof(receiverBuffer));
  memset(transceiverBuffer, '\0', sizeof(transceiverBuffer));

  radio_last_tv=millis();

  return result;
}
示例#5
0
void setup() {

  Serial.begin(115200);
  Serial.println("Booting");
  Serial.println(ESP.getResetInfo());
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  Serial.println("Starting UDP");
  udp.begin(localPort);
  Serial.print("Local port: ");
  Serial.println(udp.localPort());


  // -- OTA
    // OTA options
    // Port defaults to 8266
    // ArduinoOTA.setPort(8266);
    // Hostname defaults to esp8266-[ChipID]
    // ArduinoOTA.setHostname("myesp8266");
    // No authentication by default
    // ArduinoOTA.setPassword((const char *)"123");

    ArduinoOTA.onStart([]() {
      Serial.println("Start");
    });
    ArduinoOTA.onEnd([]() {
      Serial.println("\nEnd");
    });
    ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
      Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
    });
    ArduinoOTA.onError([](ota_error_t error) {
      Serial.printf("Error[%u]: ", error);
      if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
      else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
      else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
      else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
      else if (error == OTA_END_ERROR) Serial.println("End Failed");
    });
    ArduinoOTA.begin();

  Serial.println("Ready");
  Serial.print("IP address: ");
  local_ip_str = WiFi.localIP().toString();
  Serial.println(local_ip_str);

  // neopixel bus
  strip.Begin();
  strip.Show();

}
示例#6
0
void setupTime()
{
  print_dbg("IP number assigned by DHCP is ");
  println_dbg(WiFi.localIP());
  println_dbg("Starting UDP");
  Udp.begin(localPort);
  print_dbg("Local port: ");
  println_dbg(Udp.localPort());
  println_dbg("waiting for sync");
  setSyncProvider(getNtpTime);
}
示例#7
0
int SonosEsp::discoverSonos(){
    _numberOfDevices=0;
    WiFiUDP Udp;
    Udp.begin(1900);
    IPAddress sonosIP;
    bool timedOut = false;
    unsigned long timeLimit = 15000;
    unsigned long firstSearch = millis();
    do {
        Serial.println("Sending M-SEARCH multicast");
        Udp.beginPacketMulticast(IPAddress(239, 255, 255, 250), 1900, WiFi.localIP());
        Udp.write("M-SEARCH * HTTP/1.1\r\n"
        "HOST: 239.255.255.250:1900\r\n"
        "MAN: \"ssdp:discover\"\r\n"
        "MX: 1\r\n"
        "ST: urn:schemas-upnp-org:device:ZonePlayer:1\r\n");
        Udp.endPacket();
        unsigned long lastSearch = millis();

        while((millis() - lastSearch) < 5000){
            int packetSize = Udp.parsePacket();
            if(packetSize){
                char packetBuffer[255];
                //Serial.print("Received packet of size ");
                //Serial.println(packetSize);
                //Serial.print("From ");
                sonosIP = Udp.remoteIP();

                //xxx if new IP, it should be put in an array

                addIp(sonosIP);
                //found = true; 
                Serial.print(sonosIP);
                Serial.print(", port ");
                Serial.println(Udp.remotePort());
                
                // read the packet into packetBufffer
                int len = Udp.read(packetBuffer, 255);
                if (len > 0) {
                    packetBuffer[len] = 0;
                }
                //Serial.println("Contents:");
                //Serial.println(packetBuffer);
            }
            delay(50);
        }
    } while((millis()-firstSearch)<timeLimit);
    //if (!found) {
      //sonosIP.fromString("0.0.0.0"); xxx 
    //}
    return _numberOfDevices;
}
示例#8
0
int16_t Protocol::setup()
{
  uint16_t port = 4000;
  uint16_t portLimit = 5000;

  bool error = false;

  while (Udp.begin(port) != 1) {
    port++;

    if (port > portLimit) {
      return -1;
    }
  }

  return port;
}
示例#9
0
// Init stuff if needed
void init_msgmulti(int node_type) {
  int i;

  // Check if have to clear our array
  if (!numstatuses) {
    for (i = 1; i < ALLSTATUS_SIZE; i++) {
      allstatuses[i].id = -1;
      allstatuses[i].status = STATE_UNDEFINED;
    }
    allstatuses[0].id = 0;
    allstatuses[0].status = STATE_EMERGENCYSTOP;
    numstatuses = 1;
  }
  udp.begin(STATE_UDP_PORT);
  addr_local = WiFi.localIP();
  addr_broadcast = ~WiFi.subnetMask() | WiFi.gatewayIP();
  my_node_type = node_type;
  if (node_type == MSGMULTI_MASTER) {
    for (i = 0; i < MSGMULTI_MAXCLIENTS; i++)
      clients[i].expire = -1;
  }
  for (i = 0; i < MSGMULTI_MAXCLIENTS; i++)
    sent_statuses[i].expire = 0;
} // void init_msgmulti()
示例#10
0
// http://www.arduino.cc/en/Tutorial/WiFiRTC
unsigned long readLinuxEpochUsingNTP()
{
  Udp.begin(localPort);
  sendNTPpacket(timeServer); // send an NTP packet to a time server
  
  // wait to see if a reply is available
  delay(1000);

  if ( Udp.parsePacket() ) {
    Serial.println("NTP time received");
    // We've received a packet, read the data from it
    Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:

    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;

    // now convert NTP time into everyday time:
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:

    Udp.stop();
    return (secsSince1900 - seventyYears + timeZone * SECS_PER_HOUR);
  }

  else {
    Udp.stop();
    return 0;
  }
}
示例#11
0
void setup() {
  memset(voltsChr,0,sizeof(voltsChr));
  memset(amps0Chr,0,sizeof(amps0Chr));
  memset(amps1Chr,0,sizeof(amps1Chr));
  memset(tmpChr,0,sizeof(tmpChr));

    // if the program crashed, skip things that might make it crash
  String rebootMsg = ESP.getResetReason();
  if (rebootMsg=="Exception") safeMode=true;
  else if (rebootMsg=="Hardware Watchdog") safeMode=true;
  else if (rebootMsg=="Unknown") safeMode=true;
  else if (rebootMsg=="Software Watchdog") safeMode=true;

  if (sw1>=0) {
    pinMode(sw1, OUTPUT);
  }
  if (sw2>=0) {
    pinMode(sw2, OUTPUT);
  }
  if (sw3>=0) {
    pinMode(sw3, OUTPUT);
  }
  if (sw4>=0) {
    pinMode(sw4, OUTPUT);
  }

  // "mount" the filesystem
  bool success = SPIFFS.begin();
  if (!success) SPIFFS.format();

  if (!safeMode) fsConfig(); // read node config from FS

#ifdef _TRAILER
  wifiMulti.addAP("DXtrailer", "2317239216");
#else
  wifiMulti.addAP("Tell my WiFi I love her", "2317239216");
#endif

  int wifiConnect = 240;
  while ((wifiMulti.run() != WL_CONNECTED) && (wifiConnect-- > 0)) { // spend 2 minutes trying to connect to wifi
    // connecting to wifi
    delay(1000);
  }

  if (wifiMulti.run() != WL_CONNECTED ) { // still not connected? reboot!
    ESP.reset();
    delay(5000);
  }

  if (hasHostname) { // valid config found on FS, set network name
    WiFi.hostname(String(nodename)); // set network hostname
    ArduinoOTA.setHostname(nodename);  // OTA hostname defaults to esp8266-[ChipID]
    MDNS.begin(nodename); // set mDNS hostname
  }

  WiFi.macAddress(mac); // get esp mac address, store it in memory, build fw update url
  sprintf(macStr,"%x%x%x%x%x%x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  sprintf(theURL,"/iotfw?mac=%s", macStr);

  // request latest config from web api
  if (!safeMode) getConfig();

  // check web api for new firmware
  if (!safeMode) httpUpdater();

  // start UDP for ntp client
  udp.begin(localPort);

  updateNTP();

  setSyncProvider(getNtptime); // use NTP to get current time
  setSyncInterval(600); // refresh clock every 10 min

#ifndef _MINI
  // start the webserver
  httpd.onNotFound(handleNotFound);
  httpd.begin();
  // Add service to MDNS-SD
  MDNS.addService("http", "tcp", 80);
#endif

  // start websockets server
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);

  // setup other things
  setupOTA();
  setupMQTT();

  // setup i2c if configured, basic sanity checking on configuration
  if (hasI2C && iotSDA>=0 && iotSCL>=0 && iotSDA!=iotSCL) {
    sprintf(str,"I2C enabled, using SDA=%u SCL=%u", iotSDA, iotSCL);
    mqtt.publish(mqttpub, str);

    Wire.begin(iotSDA, iotSCL); // from api config file

    //Wire.begin(12, 14); // from api config file
    i2c_scan();

    printConfig();

    if (hasRGB) setupRGB();
    if (hasIout) setupADS();
    if (hasSpeed) setupSpeed();

  }

  // OWDAT = 4;
  if (OWDAT>0) { // setup onewire if data line is using pin 1 or greater
    sprintf(str,"Onewire Data OWDAT=%u", OWDAT);
    mqtt.publish(mqttpub, str);
    oneWire.begin(OWDAT);
    if (hasTout) {
      ds18b20 = DallasTemperature(&oneWire);
      ds18b20.begin(); // start one wire temp probe
    }
    if (hasTpwr>0) {
      pinMode(hasTpwr, OUTPUT); // onewire power pin as output
      digitalWrite(hasTpwr, LOW); // ow off
    }
  }


  if (useMQTT) {
    String rebootReason = String("Last reboot cause was ") + rebootMsg;
    rebootReason.toCharArray(str, rebootReason.length()+1);
    mqtt.publish(mqttpub, str);
  }
}
示例#12
0
void at_connect_udp()
{
  at_udp.begin(AT_UDP_PORT);
}
示例#13
0
//This gets the time from the server and sets the system Time.
//This function is also used as syncProvider:
time_t RRTime::getTime(){
   unsigned int localPort = 8888;      // local port to listen for UDP packets
  
  /* Don't hardwire the IP address or we won't get the benefits of the pool.
   *  Lookup the IP address for the host name instead */
  //IPAddress timeServerIP(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov
  IPAddress timeServerIP; // time.nist.gov NTP server address
  const char* ntpServerName = "europe.pool.ntp.org";
  
  static const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
  
  byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packet
  const int timeZone = 1;     // Central European Time
  WiFiUDP udp; // A UDP instance to let us send and receive packets over UDP
  udp.begin(localPort);
  DEBUGPRINT.print("Local port: ");
  DEBUGPRINT.println(udp.localPort());
  DEBUGPRINT.println("waiting for sync");

     //get a random server from the pool
  if(!WiFi.hostByName(ntpServerName, timeServerIP)){
    DEBUGPRINT.print("ERROR; Could not resolve IP using ");
    IPAddress fallBack(132, 163, 4, 102);
    timeServerIP = fallBack;
    DEBUGPRINT.println(timeServerIP);
    } 
  DEBUGPRINT.print("Timesever IP:");
  DEBUGPRINT.println(timeServerIP);
  while (udp.parsePacket() > 0) ; // discard any previously received packets
  DEBUGPRINT.println("Transmit NTP Request");
  // set all bytes in the buffer to 0
  /////////////////////////////////////////////////////////////////////////
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:                 
  udp.beginPacket(timeServerIP, 123); //NTP requests are to port 123
  udp.write(packetBuffer, NTP_PACKET_SIZE);
  udp.endPacket();
  /////////////////////////////////////////////////////////////////////////
  uint32_t beginWait = millis();
  while (millis() - beginWait < 3000) {
    int size = udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      DEBUGPRINT.println("Receive NTP Response");
      udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      //store last sync:
      lastSync = millis();
      
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  DEBUGPRINT.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}
示例#14
0
void ntpStart() {
    Serial.println("Starting UDP");
    udp.begin(localPort);
    Serial.print("Local port: ");
    Serial.println(udp.localPort());
}