ESP8226 TCP functions breaking I2C functions

I have developed a couple of widgets with the AHT10 T/RH sensor and the Wemo D mini EPS8266 module. One wakes up every 15 or so minutes and connects to the WiFi and a TCP server and pushes the data, then goes back to sleep. It works fine. There is another with the sensor + I2C LED screen and is intended to be powered 24/7, taking a reading every second or so. I would like this second unit to push the data to the TCP server every 900 measurement loops (~15 minutes). I am finding a problem with the second system.
I've included the test code (with only the sensor and the WiFi/TCP sections) with a 10 measurement loop to 1 TCP push. Everything works fine the first time around. The non-TCP data goes out the serial port, the data gets pushed to the TCP server, but the next time around the code breaks at "Wire.write(AHT10_MEAS); " line 140 and trips the HW WDT. For some reason the appears the I2C functions are getting stepped on when the TCP functions have been called. I've been a lot of digging and existing the WiFi client properly and tried what I have found, but have found the solution yet. Any thought are apricated and I would really like to know what I'm missing because there are other devices I have in mind the require these to capabilities to play nice.

Regards,
KS

Testing code:

#include <Wire.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

extern "C" {  //Files for WPA2 Enterprise networks
#include "user_interface.h"
#include "wpa2_enterprise.h"
}

char tp[40]; //General use array for messages
uint32_t _rawDataBuffer[6]; //Sensor data array
uint32_t hum; //humidity bit count
uint32_t tem; //temperature bit count


//AHT10 Stuff
#define led_addr 0x3C
#define AHT10_addr 0x38
#define AHT10_INIT 0xE1
#define AHT10_RESET 0xBA
#define AHT10_MEAS 0xAC
#define AHT10_NORMAL_CMD 0xA8  //normal cycle mode command, no info in datasheet!!!
#define AHT10_INIT_NORMAL_MODE     0x00  //enable normal mode
#define AHT10_INIT_CYCLE_MODE      0x20  //enable cycle mode
#define AHT10_INIT_CMD_MODE        0x40  //enable command mode
#define AHT10_INIT_CAL_ENABLE      0x08  //load factory calibration coeff
#define AHT10_DATA_MEASURMENT_CMD  0x33  //no info in datasheet!!! my guess it is DAC resolution, saw someone send 0x00 instead
#define AHT10_DATA_NOP             0x00  //no info in datasheet!!!
#define AHT10_FORCE_READ_DATA      true  //force to read data
#define AHT10_USE_READ_DATA        false //force to use data from previous read
#define AHT10_ERROR                0xFF  //returns 255, if communication error is occurred
#define AHT10_MEASURMENT_DELAY     80    //at least 75 milliseconds
#define AHT10_POWER_ON_DELAY       40    //at least 20..40 milliseconds
#define AHT10_CMD_DELAY            350   //at least 300 milliseconds, no info in datasheet!!!
#define AHT10_SOFT_RESET_DELAY     20    //less than 20 millisecondsn
#define deno  0X100000

//Default calibration values for the AHT10
float mt = 200.0; //200 default
float bt = -50.0;  //-50 default
float mh = 100.0; //100 default
float bh = 0.0;   //0 Default

//WiFi burst variables
// SSID to connect to
char* ssid = <ssid_name>;
// Username for authentification
char* username = <uid>;
// Password for authentication
char* password = <passkey>;

int checkin = 10;
IPAddress staticIP("xxx.xxx.xxx.xxx");
IPAddress dns("xxx.xxx.xxx.xxx");
IPAddress gateway("xxx.xxx.xxx.xxx");
IPAddress subnet("xxx.xxx.xxx.xxx");


void setup() {
  Wire.begin();
  Serial.begin(115200);
  delay(1000);
  Serial.println();
  Serial.println("Setup");
  Serial.println("Sensor setup");
  //Init Code
  Wire.beginTransmission(AHT10_addr);
  Wire.write(AHT10_NORMAL_CMD);
  Wire.write(AHT10_DATA_NOP);
  Wire.write(AHT10_DATA_NOP);
  if(Wire.endTransmission(true) !=0){
    Serial.println("Init Failed");
    return;
    }
        Serial.println("Init Success");
  delay(AHT10_CMD_DELAY);
  
  //Mode Code
    Wire.beginTransmission(AHT10_addr);
  Wire.write(AHT10_INIT);
  Wire.write(AHT10_INIT_CYCLE_MODE|AHT10_INIT_CAL_ENABLE);
  Wire.write(AHT10_DATA_NOP);
  if(Wire.endTransmission(true) !=0){
        Serial.println("Mode Failed");
    return;
    }
  Serial.println("Mode Success");

//Setup WiFi
      WiFi.config(staticIP, dns, gateway, subnet);
      WiFi.begin();
      wifi_set_opmode(STATION_MODE);
      struct station_config wifi_config;
      memset(&wifi_config, 0, sizeof(wifi_config));
      strcpy((char*)wifi_config.ssid, ssid);
      wifi_station_set_config(&wifi_config);
      wifi_station_clear_cert_key();
      wifi_station_clear_enterprise_ca_cert();
      wifi_station_set_wpa2_enterprise_auth(1);
      wifi_station_set_enterprise_identity((uint8*)username, strlen(username));
      wifi_station_set_enterprise_username((uint8*)username, strlen(username));
      wifi_station_set_enterprise_password((uint8*)password, strlen(password));
      wifi_station_connect();
      // Wait for connection
      delay(1);
      Serial.println();
      Serial.print("Waiting for connection");
      int tries = 0;    
      while (WiFi.status() != WL_CONNECTED) {
      tries++;
      delay(250);
      Serial.print(".");
      if(tries>40){
        Serial.println("\nNetwork connection failed");
        WiFi.mode(WIFI_OFF); //Shut off the radio
        ESP.deepSleep(60e6); //go to sleep for this many micro-seconds      return;
      }
    }
    WiFi.setOutputPower(20.5);
    Serial.println("");
    Serial.print("Connected, IP address: ");
    Serial.println(WiFi.localIP());

}

void loop() {
  // put your main code here, to run repeatedly:
  
  delay(1000); //Delay for 1 secound a loop
  
    Wire.requestFrom(AHT10_addr, 1);
    
  if (Wire.available() != 1){
    Serial.println(AHT10_ERROR); //check rxBuffer & error handler, collision on I2C bus
  }
  else{

    Wire.beginTransmission(AHT10_addr); //Start I2C meassage
        Serial.println("begin");  //Debug output
    Wire.write(AHT10_MEAS);  //send measurment command //code breaks here on second pass thru
        Serial.println("MEAS");  //Debug output
    Wire.write(AHT10_DATA_MEASURMENT_CMD); //send measurment parameter
        Serial.println("DATA");  //Debug output
    Wire.write(AHT10_DATA_NOP); //NOP
        Serial.println("NOP");  //Debug output
    if (Wire.endTransmission(true) != 0){ //Error out IF
       _rawDataBuffer[0] = AHT10_ERROR;
    }
    Wire.requestFrom(AHT10_addr, 6, true); //Get the 6 data registor
    if (Wire.available() != 6) //If there are not 6 valid returns
    {
      _rawDataBuffer[0] = AHT10_ERROR; //Place 0xFF in 1st buffer valvue
    }
    else{ //or fill the buffer values
     for (uint8_t i = 0; i < 6 ; i++)
    {
      _rawDataBuffer[i] = Wire.read();
    }
      
    }
  }
  //if the buffer 0 not 0xff, do the bitwise combining
  if(_rawDataBuffer[0] != AHT10_ERROR){
    hum = _rawDataBuffer[1]<<8;
    hum |= _rawDataBuffer[2];
    hum <<=4;
    hum |= _rawDataBuffer[3]>>4;
    tem = _rawDataBuffer[3] &0XF;
    tem <<=8;
    tem |=_rawDataBuffer[4];
    tem<<=8;
    tem |=_rawDataBuffer[5];
  }
  //If checking is greater than 0 
  if(checkin >0){
    checkin--; //decrement it
  }
  else{ //else push data to TCP server
    
    if(WiFi.status() == WL_CONNECTED){ //if the wifi is connected
    Serial.println("Connected"); //Debug output
    uint8_t mac[6]; //Mac Address array
    WiFi.macAddress(mac); //Get mac address
    char* serverIP = "xxx.xxx.xxx.xxx"; //TCP serve ip
    WiFiClient client; //Define tcp client
    if(client.connect(serverIP,900)){ //Connec to server
      Serial.print("Client Stat: "); //Debug output
      Serial.println(client.status()); //Debug output
      //Move data to tp array
      sprintf(tp,"%d\t%.2f\t%.2f\t%d\t%.2f\t%.2f\t%02X:%02X:%02X:%02X:%02X:%02X\n",tem,mt,bt,hum,mh,bh,mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
      client.println(tp); //Send TCP array
      //client.stop(); //(may not need) Server breaks the connection after detecting line break
    }
//    while(client.status() != CLOSED){ (may not need) wait for client connection ti close
//      delay(10);
//    }
    checkin = 10;  //reset counter
    }
    else{ //if Wifi not connected 
      Serial.println("Not Connceted"); //Debug output
    }
    
    }
    float h = (float)hum*mh/0x100000+bh; //Do the math
    float t = (float)tem*mt/0x100000+bt; 
    sprintf(tp,"%.2f\t%.2f", h, t); //move values to tp array
    Serial.println(tp);   //Send calculate values out serial port
}

This can not normally happen because standard Wire.write() only buffers the data, no transmission right now. It looks to me like a library bug.

How do you know that? Because of the serial output you get? That output gets buffered too, the sketch runs forth while the serial characters are sent over the (very slow) serial interface.

Check the return values of the Wire.requestFrom() calls!

Where in the datasheet of the AHT10 did you find the information that you can read a byte from it without having sent a command before (what you do at the start of the loop())?

Thanks DrD. & pylon.
In response to pylon - Running the code with the Serial.println lines (between 136 and 143) active, the next time thru the loop after the TCP call, the systems prints "begin" out the serial port and then does one of several things. pauses until the hardware WDT times out or throws an exception indicating it's tried a load or store action. (Exception numbers 3 (LoadStoreErrorCause), 9 (LoadStoreAlignmentCause)or 28(LoadProhibitedCause).

The HWWDT lockup maybe because the sensor is busy. I can try placing a status checker loop in front of the section. The Exceptions I see randomly, and sometime frequently, with other code running on a ESP8266. It's usual do to an array size being to small to except the amount of data, but I don't think that the reason here.

Regards,
K

Why do you not always read the input? This may result in a buffer overrun or other wild things.

No, the buffer gets cleared in every Wire.requestFrom() call.

As I already wrote, you cannot use just prints to debug that way. If you want to be sure the content of the previous print() was sent to the host, use Serial.flush(). That waits until the complete buffer was sent.
You will see that the sketch doesn't stop at the Wire.write() calls as they just fill a buffer.

I guess that's because you're requesting data without having told the sensor to provide that data.

Thanks for the input guys. Since this system was based on code that has been moved around and edited a lot. I went back, started with a clean sheet of paper and configured the code so that I could enable/disable different functions as needed. What I found was that the issue only arises when connected/connecting to my office's wireless network, which has the WPA2 Enterprise security. The sensor code, by itself has run for days without a network connection. And at home with standard WPA2 wireless, the whole system has run for over 4 days without a glitch. We have had some connection issues with the office wireless the last couple of month, so I'm thinking the root issue may be when the wifi connection hic-ups, it causes the system to error out. I'll have to learn some more about safely handling wifi connection glitches. Any thoughts are welcome.

KS