Exemplo n.º 1
0
void WiFiUDP::stopAll()
{
    for (WiFiUDP* it = _s_first; it; it = it->_next) {
        DEBUGV("%s %p %p\n", __func__, it, _s_first);
        it->stop();
    }
}
Exemplo n.º 2
0
AJ_Status AJ_Net_RecvFrom(AJ_IOBuffer* buf, uint32_t len, uint32_t timeout)
{
    AJ_InfoPrintf(("AJ_Net_RecvFrom(buf=0x%p, len=%d., timeout=%d.)\n", buf, len, timeout));

    AJ_Status status = AJ_OK;
    int ret;
    uint32_t rx = AJ_IO_BUF_SPACE(buf);
    unsigned long Recv_lastCall = millis();

    AJ_InfoPrintf(("AJ_Net_RecvFrom(): len %d, rx %d, timeout %d\n", len, rx, timeout));

    rx = min(rx, len);

    while ((g_clientUDP.parsePacket() == 0) && (millis() - Recv_lastCall < timeout)) {
        delay(10); // wait for data or timeout
    }

    AJ_InfoPrintf(("AJ_Net_RecvFrom(): millis %d, Last_call %d, timeout %d, Avail %d\n", millis(), Recv_lastCall, timeout, g_clientUDP.available()));
    ret = g_clientUDP.read(buf->writePtr, rx);
    AJ_InfoPrintf(("AJ_Net_RecvFrom(): read() returns %d, rx %d\n", ret, rx));

    if (ret == -1) {
        AJ_InfoPrintf(("AJ_Net_RecvFrom(): read() fails. status=AJ_ERR_READ\n"));
        status = AJ_ERR_READ;
    } else {
        if (ret != -1) {
            AJ_DumpBytes("AJ_Net_RecvFrom", buf->writePtr, ret);
        }
        buf->writePtr += ret;
        AJ_InfoPrintf(("AJ_Net_RecvFrom(): status=AJ_OK\n"));
        status = AJ_OK;
    }
    AJ_InfoPrintf(("AJ_Net_RecvFrom(): status=%s\n", AJ_StatusText(status)));
    return status;
}
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);
}
Exemplo n.º 4
0
void WiFiUDP::stopAll()
{
    for (WiFiUDP* it = _s_first; it; it = it->_next) {
        DEBUGV("%s %08x %08x\n", __func__, (uint32_t) it, (uint32_t) _s_first);
        it->stop();
    }
}
Exemplo n.º 5
0
time_t getNtpTime() {
  while (Udp.parsePacket() > 0)
    ; // discard any previously received packets
  //Serial.println("$CLS,Y0,X0#TX NTP RQ");
  PulseLed(BLUE, 2, 50, 10);
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  uint32_t waited = millis() - beginWait;
  while (waited < 3000)
  {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      //Serial.println("$CLS,Y0,X0#RX NTP OK");
      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];
      analogWrite(GREEN, 100);
      analogWrite(RED, 0);
      analogWrite(BLUE, 0);
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR + (waited / 1000);
    }
    waited = millis() - beginWait;
  }
  //Serial.println("$CLS,Y0,X0#*** NTP TO ***");
  PulseLed(RED, 4, 50, 10);
  analogWrite(GREEN, 0);
  analogWrite(RED, 100);
  analogWrite(BLUE, 0);
  return 0; // return 0 if unable to get the time
}
Exemplo n.º 6
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;
}
Exemplo n.º 7
0
void radioTransceiverTask(const void *arg) {

	unsigned long tv;
	static unsigned long  radio_last_tv2 = 0;
	while (true){

#if 1
#if 0 //debug
		tv=millis();
		 Serial.println(tv-radio_last_tv2);
		 radio_last_tv2=tv;
#endif

			memset(transceiverBuffer, '\0', sizeof(transceiverBuffer));
			sprintf(transceiverBuffer,
						"@%3.2f:%3.2f:%3.2f:%3.2f:%3.2f:%3.2f:%3.2f:%3.2f:%3.2f:%d:%d:%d:%d:%d#",
						getRoll(), getPitch(), getYaw(), getPidSp(&rollAttitudePidSettings),
						getPidSp(&pitchAttitudePidSettings),  getYawCenterPoint() + getPidSp(&yawAttitudePidSettings),
						getRollGyro(), getPitchGyro(), getYawGyro(),
						getThrottlePowerLevel(), getMotorPowerLevelCCW1(),
						getMotorPowerLevelCW1(), getMotorPowerLevelCCW2(),
						getMotorPowerLevelCW2());
	
				Udp.beginPacket(broadcastIP, localPort);
				Udp.write(transceiverBuffer,strlen(transceiverBuffer));
				Udp.endPacket();
				
			increasePacketAccCounter();
	    os_thread_yield();
		delay(TRANSMIT_TIMER);
#endif
		}

}
Exemplo n.º 8
0
void WiFiUDP::stopAllExcept(WiFiUDP * exC) {
    for (WiFiUDP* it = _s_first; it; it = it->_next) {
        if (it->_ctx != exC->_ctx) {
            DEBUGV("%s %p %p\n", __func__, it, _s_first);
            it->stop();
        }
    }
}
Exemplo n.º 9
0
void WiFiUDP::stopAllExcept(WiFiUDP * exC) {
    for (WiFiUDP* it = _s_first; it; it = it->_next) {
        if (it->_ctx != exC->_ctx) {
            DEBUGV("%s %08x %08x\n", __func__, (uint32_t) it, (uint32_t) _s_first);
            it->stop();
        }
    }
}
Exemplo n.º 10
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();

}
Exemplo n.º 11
0
void Protocol::send(const char* message)
{
  #ifdef MODULE_CAN_DEBUG
  Serial.print("Send message: ");
  Serial.println(message);
  #endif

  Udp.beginPacket(_ip, _port);
  Udp.write(message);
  Udp.endPacket();
}
Exemplo n.º 12
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);
}
Exemplo n.º 13
0
void at_send_udp_packet(const char *format, ...)
{
  /* Construct databuffer to send */
  char mybuffer[AT_UDP_MAX_LENGTH];
  va_list myargs;
  va_start (myargs, format);
  vsnprintf(mybuffer, AT_UDP_MAX_LENGTH, format, myargs);
  va_end(myargs);
  //Serial.println(mybuffer);
  at_udp.beginPacket(drone_ip, AT_UDP_PORT);
  at_udp.print(mybuffer);
  at_udp.endPacket();
}
Exemplo n.º 14
0
void CAIPSendData(CAEndpoint_t *endpoint,
                  const void *data, uint32_t dataLength, bool isMulticast)
{
    OIC_LOG(DEBUG, TAG, "IN");

    VERIFY_NON_NULL_VOID(data, TAG, "data");
    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");

    OIC_LOG_V(DEBUG, TAG, "remoteip: %s", endpoint->addr);
    OIC_LOG_V(DEBUG, TAG, "port: %d", endpoint->port);

    uint8_t ip[4] = {0};
    uint16_t parsedPort = 0;
    CAResult_t res = CAParseIPv4AddressInternal(endpoint->addr, ip, sizeof(ip),
                     &parsedPort);
    if (res != CA_STATUS_OK)
    {
        OIC_LOG_V(ERROR, TAG, "Remote adrs parse fail %d", res);
        return;
    }

    IPAddress remoteIp(ip);
    Udp.beginPacket(remoteIp, endpoint->port);

    uint32_t bytesWritten = 0;
    while (bytesWritten < dataLength)
    {
        // get remaining bytes
        size_t writeCount = dataLength - bytesWritten;
        // write upto max ARDUINO_WIFI_BUFFERSIZE bytes
        writeCount = Udp.write((uint8_t *)data + bytesWritten,
                               (writeCount > ARDUINO_IP_BUFFERSIZE ?
                                ARDUINO_IP_BUFFERSIZE:writeCount));
        if(writeCount == 0)
        {
            // write failed
            OIC_LOG_V(ERROR, TAG, "Failed after %u", bytesWritten);
            break;
        }
        bytesWritten += writeCount;
    }

    if (Udp.endPacket() == 0)
    {
        OIC_LOG(ERROR, TAG, "Failed to send");
        return;
    }
    OIC_LOG(DEBUG, TAG, "OUT");
    return;
}
Exemplo n.º 15
0
time_t getNtptime() {
  time_t epoch = 0;

  //get a random server from the pool
  WiFi.hostByName(ntpServerName, timeServerIP);

  sendNTPpacket(timeServerIP); // send an NTP packet to a time server
  // wait to see if a reply is available
  delay(500);

  int cb = udp.parsePacket();
  if (!cb) {
    //Serial.println("no packet!?");
    wsSend("NTP Error");
  }
  else {
    // Serial.print("packet received, length=");
    // Serial.println(cb);
    // 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;
    // Serial.print("Seconds since Jan 1 1900 = " );
    // Serial.println(secsSince1900);

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

    epoch = epoch - (60 * 60 * ntpOffset); // take off 4 hrs for EDT offset
    sprintf(str, "NTP epoch=%d", epoch);
    wsSend(str);



  }
  return epoch;
}
Exemplo n.º 16
0
void Protocol::loop()
{
  _packetSize = Udp.parsePacket();

  if (_packetSize) {
    now = millis();

    char _packetBuffer[PACKET_SIZE] = {}; // UDP_TX_PACKET_MAX_SIZE is too large: 8192

    Udp.read(_packetBuffer, _packetSize);

    #ifdef MODULE_CAN_DEBUG
    _remoteIP    = Udp.remoteIP();
    _remotePort  = Udp.remotePort();

    Serial.print("New packet received from: ");
    Serial.print(_remoteIP);
    Serial.print(":");
    Serial.println(_remotePort);
    Serial.print("Message: ");
    Serial.println(_packetBuffer);
    #endif

    _lastTalkTime = now;

    if (strcmp(_packetBuffer, "hi") == 0) {
      _isConnected = true;

      _onConnectedCb();
    } else if (strcmp(_packetBuffer, "bye") == 0) {
      _isConnected = false;

      _onDisconnectedCb();
    } else if (strcmp(_packetBuffer, "ping") == 0) {
      send("ping");
    } else {
      _onMessageCb(String(_packetBuffer));
    }
  } else if (_isConnected) {
    now = millis();

    if(now - _lastTalkTime > TIMEOUT) {
      _isConnected = false;

      _onDisconnectedCb();
    }
  }
}
Exemplo n.º 17
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;
}
Exemplo n.º 18
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();
}
Exemplo n.º 19
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;
}
Exemplo n.º 20
0
AJ_Status AJ_Net_SendTo(AJ_IOBuffer* buf)
{
    int ret;
    uint32_t tx = AJ_IO_BUF_AVAIL(buf);

    AJ_InfoPrintf(("AJ_Net_SendTo(buf=0x%p)\n", buf));

    if (tx > 0) {
        // send to subnet-directed broadcast address
#ifdef WIFI_UDP_WORKING
        IPAddress subnet = WiFi.subnetMask();
        IPAddress localIp = WiFi.localIP();
#else
        IPAddress subnet = Ethernet.subnetMask();
        IPAddress localIp = Ethernet.localIP();
#endif
        uint32_t directedBcastAddr = (uint32_t(subnet) & uint32_t(localIp)) | (~uint32_t(subnet));
        IPAddress a(directedBcastAddr);
        ret = g_clientUDP.beginPacket(IPAddress(directedBcastAddr), AJ_UDP_PORT);
        AJ_InfoPrintf(("AJ_Net_SendTo(): beginPacket to %d.%d.%d.%d, result = %d\n", a[0], a[1], a[2], a[3], ret));
        if (ret == 0) {
            AJ_InfoPrintf(("AJ_Net_SendTo(): no sender\n"));
        }

        ret = g_clientUDP.write(buf->readPtr, tx);
        AJ_InfoPrintf(("AJ_Net_SendTo(): SendTo write %d\n", ret));
        if (ret == 0) {
            AJ_ErrPrintf(("AJ_Net_Sendto(): no bytes. status=AJ_ERR_WRITE\n"));
            return AJ_ERR_WRITE;
        }

        buf->readPtr += ret;

        ret = g_clientUDP.endPacket();
        if (ret == 0) {
            AJ_ErrPrintf(("AJ_Net_Sendto(): endPacket() error. status=AJ_ERR_WRITE\n"));
            return AJ_ERR_WRITE;
        }

    }
    AJ_IO_BUF_RESET(buf);
    AJ_InfoPrintf(("AJ_Net_SendTo(): status=AJ_OK\n"));
    return AJ_OK;
}
Exemplo n.º 21
0
// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address) {
  // 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(address, 123); // NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}
Exemplo n.º 22
0
void WiFi_forward_to_argus()
{
    char str_lat[16];
    char str_lon[16];

    dtostrf(fo.latitude, 8, 4, str_lat);
    dtostrf(fo.longtitude, 8, 4, str_lon);

    Udp.beginPacket(ARGUS_HOSTNAME, ARGUS_PORT);

    snprintf(UDPpacketBuffer, sizeof(UDPpacketBuffer), "%u %X %s %s %d %s %s %u", \
      fo.timestamp * 1000, fo.addr, str_lat, str_lon, fo.altitude, "0" , "0" , TypeADSB );

#ifdef SERIAL_VERBOSE
    Serial.println(UDPpacketBuffer);
#endif

    Udp.write(UDPpacketBuffer, strlen(UDPpacketBuffer));
    Udp.endPacket();
}
Exemplo n.º 23
0
time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  println_dbg("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      println_dbg("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];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  println_dbg("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}
Exemplo n.º 24
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;
  }
}
Exemplo n.º 25
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;
}
Exemplo n.º 26
0
void radioTask(const void *arg) {

//while(true){

unsigned long tv;

  char getChar;
  char count = 0;

  char receiverBuffer2[RECEIVER_BUFFER_SIZE];

    while (true){

    if (Udp.read(receiverBuffer, sizeof(receiverBuffer)) > 0) {
	    
		for(int i=0;i<sizeof(receiverBuffer);i++){
			getChar=receiverBuffer[i];
			if (getChar == '@') {
						memset(receiverBuffer2, '\0', sizeof(receiverBuffer2));
						receiverBuffer2[0] = getChar;
						count = 1;
					} else if ((getChar == '#') && (receiverBuffer2[0] == '@')
							&& (count < sizeof(receiverBuffer2))) {
						receiverBuffer2[count] = getChar;
						processRadioMessages( receiverBuffer2, strlen(receiverBuffer2));
						memset(receiverBuffer2, '\0', sizeof(receiverBuffer2));
						count = 0;
					} else {
						if (receiverBuffer2[0] == '@' && (count < sizeof(receiverBuffer2))) {
							receiverBuffer2[count] = getChar;
							count++;
						} else {
							memset(receiverBuffer2, '\0', sizeof(receiverBuffer2));
							count = 0;
						}
					}
		}

      memset(receiverBuffer,'\0',sizeof(receiverBuffer));
	   memset(receiverBuffer2,'\0',sizeof(receiverBuffer2));
    }
	os_thread_yield();
	delay(1);
  }

}
Exemplo n.º 27
0
void WiFi_forward_to_xcsoar()
{
    int bearing = CalcBearing(fo.latitude, fo.longtitude, LATITUDE, LONGTITUDE);
    int alt_diff = fo.altitude - ALTITUDE;
    char *csum_ptr;
    unsigned char cs = 0; //clear any old checksum

    Udp.beginPacket(ARGUS_HOSTNAME, XCSOAR_PORT);
    snprintf(UDPpacketBuffer, sizeof(UDPpacketBuffer), "$PFLAU,0,1,1,1,%d,2,%d,%u,%X*", \
      bearing, alt_diff, (int) fo.distance, fo.addr );

    //calculate the checksum
    for (unsigned int n = 1; n < strlen(UDPpacketBuffer) - 1; n++) {
      cs ^= UDPpacketBuffer[n]; //calculates the checksum
    }

    csum_ptr = UDPpacketBuffer + strlen(UDPpacketBuffer);
    snprintf(csum_ptr, sizeof(UDPpacketBuffer) - strlen(UDPpacketBuffer), "%02X\n", cs);

#ifdef SERIAL_VERBOSE
    Serial.println(UDPpacketBuffer);
#endif

    Udp.write(UDPpacketBuffer, strlen(UDPpacketBuffer));
    Udp.endPacket();

    Udp.beginPacket(XCSOAR_HOSTNAME, XCSOAR_PORT);
    snprintf(UDPpacketBuffer, sizeof(UDPpacketBuffer), "$PFLAA,2,%d,%d,%d,2,%X,,,,,1*",   \
      (int) (fo.distance * cos(dtor(bearing))), (int) (fo.distance * sin(dtor(bearing))), \
      alt_diff, fo.addr );

    cs = 0; //clear any old checksum
    for (unsigned int n = 1; n < strlen(UDPpacketBuffer) - 1; n++) {
      cs ^= UDPpacketBuffer[n]; //calculates the checksum
    }

    csum_ptr = UDPpacketBuffer + strlen(UDPpacketBuffer);
    snprintf(csum_ptr, sizeof(UDPpacketBuffer) - strlen(UDPpacketBuffer), "%02X\n", cs);

#ifdef SERIAL_VERBOSE
    Serial.println(UDPpacketBuffer);
#endif

    Udp.write(UDPpacketBuffer, strlen(UDPpacketBuffer));
    Udp.endPacket();
}
Exemplo n.º 28
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()
Exemplo n.º 29
0
// Send status packet
int send_packet(char *packet, int size, IPAddress exclude) {
  int i;

  if (my_node_type == MSGMULTI_MASTER) {
    for (i = 0; i < MSGMULTI_MAXCLIENTS; i++) {
      if ((clients[i].expire > 0) && (clients[i].client != exclude)) {
	#ifdef DEBUG
	Serial.print("Sending packet to ");
	Serial.println(clients[i].client);
	#endif
        clients[i].expire--;
        udp.beginPacket(clients[i].client, STATE_UDP_PORT);
        udp.write(packet, size);
        return udp.endPacket();
      }
    }
  } else {
    udp.beginPacket(WiFi.gatewayIP(), STATE_UDP_PORT);
    udp.write(packet, size);
    return udp.endPacket();
  }
} // void send_packet(IPaddress dest, char *packet, int size)
Exemplo n.º 30
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);
  }
}