WinHttpRequest.5.1 не подключается к Arduino - PullRequest
0 голосов
/ 23 октября 2018

Я ищу совет, как разрешить странную ситуацию.То, что я собираюсь описать, прекрасно работало до вчерашнего дня.Сегодня это больше не работает, и я не знаю каких-либо соответствующих изменений в аппаратном или программном обеспечении.У меня есть Arduino Nano со щитом Ethernet, на котором работает очень простой веб-сервер.Я хочу использовать его для отправки состояния своих выводов ввода / вывода на мой ПК, где я запускаю сценарий VBA, чтобы зарегистрировать состояние в файле Excel и при необходимости отправить назад некоторые команды.До вчерашнего дня оба отлично общались через Ethernet.в течение 200 мс клиент VBA подключался к серверу Arduino.Сегодня каждая часть может подключаться к веб-страницам, но не друг с другом.То есть я могу отправить сообщение на сервер Arduino из веб-браузера, введя его URL-адрес и текст.Текст получен, и сервер отправляет ответ браузеру, который отображается на этой веб-странице.С другой стороны, мой VBA-клиент отлично и очень быстро подключается к любому веб-сайту, например microsoft.com, но время истекает, когда я добавляю URL-адрес сервера Arduino.Вот соответствующий код обоих.Arduino:

#define sector 0xA1           ' =161
#include <EtherCard.h>
#include <string.h>     
#define STATIC 1  // set to 1 to disable DHCP (adjust myip/gwip values below)
#if STATIC
// ethernet interface ip address
static byte myip[] = { 192,168,1,sector };   
// gateway ip address
static byte gwip[] = { 192,168,1,1 }; 
#endif

// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0xA1 };
byte Ethernet::buffer[500]; // allocate tcp/ip send and receive buffer

void setup() 
 {
   // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);  Serial.begin(9600);    
  if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)   // initialise 
EtherCard library
Serial.println( "Failed to access Ethernet controller");
#if STATIC                  // no DHCP 
  ether.staticSetup(myip, gwip);                // 
https://jeelabs.org/2011/06/19/ethercard-library-api/
#else                       // with DHCP
  if (!ether.dhcpSetup())
Serial.println("DHCP failed");
#endif

  ether.printIp("IP:  ", ether.myip);            // print an IP# to USB port
  ether.printIp("GW:  ", ether.gwip);  


void loop() 
{
   boolean httpSend = false;                  // initialise

// ----------------------   ETHERNET  ------------------------------------
   word len = ether.packetReceive();         // size of new received data 
packet if any
   word pos = ether.packetLoop(len);         // position of new data in 
packet buffer, otherwise zero
   if (pos)                                  // check if valid TCP data is 
received (pos >0)
  {
    String inMsg = (char *) Ethernet::buffer + pos; 
    int s1 = inMsg.indexOf("/[");
    int s2 = inMsg.indexOf("]/");
    if ((s1 > 0) and s2>0)                 //  found
    {
     inMsg = inMsg.substring(s1+2, s2);
     httpSend = true;                     // received a request, need to 
 send a reply
    }
    else
    {
     inMsg = "";
    }
  }

 // ----------------------   INPUT STATUS  --------------------------------- 


  // read the status of all pins bytewise:
(code omitted for clarity)

    httpSend = true;                // need to send the new code

  }

  if (httpSend)
  {
    ether.httpServerReply(outMsg());   // send http data. outMsg() is a 
subroutine defined below
                                       // which returns a pointer into the 
data buffer
    OldInputs = Inputs;
  }

}   
// ----------------  end of program loop  ------------------

// -----------------  subroutines here  -------------------------
    static word outMsg()        // sends http code, returns unsigned int 
pointer into the data buffer
{
     Time = millis();
     BufferFiller bfill = ether.tcpOffset();

     bfill.emit_p(PSTR(
       "HTTP/1.0 200 OK\r\n"
       "Content-Type: text/html\r\n"
       "Pragma: no-cache\r\n"
       "\r\n"                                         //  CR,LF
//       "<meta http-equiv='refresh' content='1'/>"     //  refresh every 10 
seconds
       "<html><head><title>A1</title></head><body>"
       "($H i$D$D$D$D$D$D$D$D #$L w$L t$L)"                // placeholders: 
$H=HEX integer, $D=DEC integer, $L=unsigned long, $F=string
       "</span></body></html>"),
       sector, Inputs>>7&1, Inputs>>6&1, Inputs>>5&1, Inputs>>4&1, 
Inputs>>3&1, Inputs>>2&1, Inputs>>1&1, Inputs&1, WGcode, WGtime, Time);
     return bfill.position(); 
    //
}   // ----------------  end of outMsg  ------------------

Код VBA

Sub HTTPTest()
    Set HTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
        'https://docs.microsoft.com/es-es/windows/desktop/WinHttp/iwinhttprequest-interface

        url = "http://192.168.1.161/"               ' Must start with "http://" and end with "/"
        hs = 0
        hst = ""
        t0 = GetTickCount                           ' local time in msec (resolution 16...17 msec)
        t1 = 0                                      ' start transmission
        time0 = Now()                               ' reference time and date

   With HTTP
        .Open "GET", url, True                  ' establishes asynchronous connection.
        .send ("")                              ' the parameter is transmitted only with "POST" method, not with GET.
        .WaitForResponse (10)                    ' wait 1 second
        t1 = GetTickCount - t0                  ' t1 is time from sending message to receiving response
        If t1 < 500 Then                        ' success!
           hs = .Status                        ' check status
           hst = .StatusText
           response = .responseText            ' reads the response text. Other methods: responseBody, responseStream, responseXML
        Else
            .abort                              ' needs to be aborted if timeout
        End If
    End With


End Sub

Я ценю любые советы о том, где искать.Может быть, проблема даже не в коде.Сегодня утром я не смог подключиться к интернету.Запустив подпрограмму Windows для обнаружения проблем с сетью, я получил ответ «У петлевого адаптера npcap нет правильной конфигурации IP. После того, как я исправил это и перезапустил, у меня было подключение к сети, но позже заметил, что возникла описанная выше проблема.Я склонен не верить в эту причину, потому что связь между этими двумя компонентами существует только локально, а не в сети. Но это единственное примечательное, что я могу придумать.

...