B4R Question ESP8266 - connect as Server to B4A [solved]

derez

Expert
Licensed User
Longtime User
I have the following setup:
A car driven by Arduino with B4R app, connected by SerialSoftware to ESP8266.
The ESP is used as Server in the lan and a B4A is trying to connect and establish Astream.
What I get is an error in the ESP and in the B4A on the lines of Astream init.
The codes, B4R ESP :
B4X:
Sub Server_newConnection(NewSocket As WiFiSocket)
Log("new connection")
Wstream.Initialize(NewSocket.Stream,"Wstream_NewData", "Wstream_Error")
Server.Listen
End Sub

B4A:
B4X:
Sub connect
    If sock.Connected Then
        Log("Connected to Car")
         Astream.Initialize(sock.InputStream, sock.OutputStream,"Astream")
        conn.Background = dr1
    Else
        Log("Failed to connect to Car")
        sock.Connect("192.168.0.160",54321,0)
         connect
    End If
End Sub

The error log:
** Activity (main) Pause, UserClosed = false **
** Service (starter) Create **
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
Failed to connect to Car
Failed to connect to Car
Failed to connect to Car
Connected to Car
Error occurred on line: 134 (Main)
java.net.SocketException: Socket is closed
at java.net.PlainSocketImpl.checkNotClosed(PlainSocketImpl.java:116)
at java.net.PlainSocketImpl.getInputStream(PlainSocketImpl.java:213)
at java.net.Socket.getInputStream(Socket.java:365)
at anywheresoftware.b4a.objects.SocketWrapper.getInputStream(SocketWrapper.java:220)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:703)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:337)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:247)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:134)
at derez.carwifi.main.afterFirstLayout(main.java:102)
at derez.carwifi.main.access$000(main.java:17)
at derez.carwifi.main$WaitForLayout.run(main.java:80)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
** Activity (main) Resume **
** Activity (main) Resume **

In the esp log I get:
new connection
Wstream Error

I guess the B4A fails because of the ESP's astream error but I don't understand why.
Another astream works fine with the other B4R that runs on the Arduino.

Note: the same ESP in another setup connects as client to a B4j server and Astream init is successful there.
 

derez

Expert
Licensed User
Longtime User
Solved:
I changed the "connect" sub to work in a timer every second:
B4X:
Sub contmr_tick
    If sock.Connected Then
        Log("Connected to Car")
         Astream.Initialize(sock.InputStream, sock.OutputStream,"Astream")
        conn.Background = dr1
        contmr.Enabled = False
    Else
        Log("Failed to connect to Car")
        sock.Connect("192.168.0.160",54321,0)
    End If
End Sub

I also changed the arduino not to response back to the ESP after getting a message.
 
Upvote 0

derez

Expert
Licensed User
Longtime User
ingo.tw wrote:
Can someone provide examples of it ? Very grateful
The code for Arduino (without the car driving subs):
B4X:
Sub Process_Globals
    Public Serial1 As Serial
    Private softserial As SoftwareSerial
    Private Astream As AsyncStreams
End Sub

Private Sub AppStart
   Serial1.Initialize(115200)
   Log("AppStart")
   softserial.Initialize(115200, 12,13)
   softserial.Listening = True
   Astream.Initialize(softserial.Stream,"Astream_NewData","Astream_Error")
End Sub

Sub Astream_NewData(Buffer() As Byte)
    Log(Buffer) ' here It gets the commands from the the Wemos which get them from phone
End Sub

Sub Astream_Error
    Log("Astream Error")
End Sub

The code for WeMos D1:
B4X:
Sub Process_Globals
   Public Serial1 As Serial
   Private Server As WiFiServerSocket
   Private softserial As SoftwareSerial
   Private Wstream, Rstream As AsyncStreams ' W for wifi connection, R for arduino softserial connection
   Private port As UInt = 54321
End Sub

Private Sub AppStart

   Serial1.Initialize(115200)
   Log("AppStart")

   Server.Initialize(port,"Server_NewConnection")
   Server.Listen
   Dim D1 As D1Pins
   softserial.Initialize(115200, D1.D6, D1.D7)
   Rstream.Initialize(softserial.Stream, "Rstream_newdata", Null)
End Sub

Sub Server_newConnection(NewSocket As WiFiSocket)
   Log("new connection")
   Wstream.Initialize(NewSocket.Stream,"Wstream_NewData", "Wstream_Error")
End Sub

Sub Wstream_NewData (Buffer() As Byte)
    Rstream.Write(Buffer)
    Log(Buffer)
End Sub

Sub Rstream_NewData (Buffer() As Byte)
    Log("car says: ", Buffer)
End Sub

Sub Wstream_Error
   Log("Wstream Error")
   Server.Listen
End Sub

Sub Rstream_Error
   Log("Rstream Error")
End Sub

The code for B4A:
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Private Client As Socket
    Private contmr, wtmr  As Timer
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Private fwd,bck,rt,lft,halt,conn, lsr As Label
    Private Astream As AsyncStreams
    Dim dr1 , dr2 As ColorDrawable
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    Client.Initialize("Client")
    dr1.Initialize(Colors.Green,7%x)
    dr2.Initialize(Colors.red,7%x)
    create_views
    contmr.Initialize("contmr",1000)
    wtmr.Initialize("wtmr",1000)
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub create_views
....   
End Sub

Sub conn_click
    contmr.Enabled = True
End Sub

Sub Client_Connected (Successful As Boolean)
    If Successful Then
        Log("Connected to Car")
        wtmr.Enabled = True
        conn.Background = dr1
        contmr.Enabled = False
    Else
        Log("Failed to connect to Car")
    End If
End Sub

Sub contmr_tick
    If Client.Connected = False Then
        Client.Connect("192.168.0.160",54321,1000)
    End If
End Sub

Sub AStream_NewData (Buffer() As Byte)
   Log("Received: " & Buffer(0))
End Sub

Sub AStream_Error
   Log("Error")
   conn.Background = dr2
   contmr.Enabled = True
End Sub

Sub btn_click
    Dim lb As Label = Sender
    Dim k As String = lb.Tag
    Log(k)
    Astream.Write(k.GetBytes("UTF8"))

End Sub

Sub lsr_click
    Astream.Write("5".GetBytes("UTF8"))
    Log(5)
End Sub

Sub wtmr_tick
    Astream.Initialize(Client.InputStream, Client.OutputStream,"Astream")
    wtmr.Enabled = False
End Sub

I removed the buttons creation sub to save space.
I could not use the Wemos to do the car driving because it does not have enough GPIO pins (I was left with only 4 after burning some...)
So I use the Arduino UNO to drive, the Wemos is used just as a WiFi data supplier and the data (commands) come from the phone.
The Wemos use pins 6 and 7 for the serial instead of the Rx & Tx because they don't work but the SoftSerial can work with any two pins.
 
Last edited:
Upvote 0

Cableguy

Expert
Licensed User
Longtime User
ingo.tw wrote:

I could not use the Wemos to do the car driving because it does not have enough GPIO pins (I was left with only 4 after burning some...)
I was asking myself why you didn't use just the WeMos! lol, time to buy another one? maybe a WeMos mini!
 
Upvote 0

sanjog shakya

Member
Licensed User
Longtime User
I have the following setup:
A car driven by Arduino with B4R app, connected by SerialSoftware to ESP8266.
The ESP is used as Server in the lan and a B4A is trying to connect and establish Astream.
Dear derez,
Can you share the circuit diagram how to connect Arduino with B4R app, connected by SerialSoftware to ESP8266.
Best Regards,
sanjog
 
Upvote 0

derez

Expert
Licensed User
Longtime User
Both boards have a definition in code to establish the serialsoftware connection, like this: softserial.Initialize(115200, D1.D6,D1.d7) you can use any two GPIO pins.
The first pin is Rx and the second Tx. You connect the Rx of each board to the Tx of the other, but since the Wemos operates on 3.3 volt you have to connect the Tx of the Arduino to the Rx of the Wemos through a level change - connect 10kOhm to ground, 5kOhm to the 10k, the other side of the 5k to arduino Tx. the point between the 5k and 10k - connect to Wemos Rx.
The line from Wemos Tx to arduino Rx can go directly because Arduino will identify 3.3 volt as digital True.
The other important point is to connect the grounds of both boards.
Power the wemos by a line from arduino's 5v to wemos Vin. (If another version of ESP - you might need to feed 3.3v .
 
Upvote 0

sanjog shakya

Member
Licensed User
Longtime User
Both boards have a definition in code to establish the serialsoftware connection, like this: softserial.Initialize(115200, D1.D6,D1.d7) you can use any two GPIO pins.
The first pin is Rx and the second Tx. You connect the Rx of each board to the Tx of the other, but since the Wemos operates on 3.3 volt you have to connect the Tx of the Arduino to the Rx of the Wemos through a level change - connect 10kOhm to ground, 5kOhm to the 10k, the other side of the 5k to arduino Tx. the point between the 5k and 10k - connect to Wemos Rx.
The line from Wemos Tx to arduino Rx can go directly because Arduino will identify 3.3 volt as digital True.
The other important point is to connect the grounds of both boards.
Power the wemos by a line from arduino's 5v to wemos Vin. (If another version of ESP - you might need to feed 3.3v .

Thank you derez.
But literally i m confused coz i m not a electronics guy :).It could be more clear if i have seen some schematic diagram or fritzing diagram :).Anyway but here in Nepal we dont have Wemos Saler so i got :
Wireless TXRX - ESP8266 (Serial Wireless)
wireless-txrx-esp8266-serial-wireless-module.jpg
so far.
Some info from online:
In terms of the form factor, it looks a lot like the nRF24L01 2.4G RF transceiver. This is a serial module with a built-in TCP/IP stack, so you can use it standalone but you will be likely limited. You need a FTDI to connect this module to your computer, and start communicating with it. FTDI is a common name for USB-to-TTL (or serial) converter.

Is this the same device as we use to communicate via Esp to Android?You have used Wemos as i dont have that how can i connect Esp to Android?
How do i program it through B4R?
Can you please guide me?

Correct me if i am wrong.
 
Last edited:
Upvote 0

derez

Expert
Licensed User
Longtime User
You can see and buy a FTDI here https://www.aliexpress.com/item/Fre...2286073399.html?spm=2114.13010608.0.59.n5zTVa
You cannot program this esp by Arduino and you need to connect it in a special way for programming and for use, search the net and you'll find.
Other ESP8266 cards, like WEMOS D1 or NodeMcu have a USB connection and can be programmed directly using the Arduino IDE or B4R IDE.
I advise you to get NodeMcu as it has more GPIO ports and USB (and only costs about 1$ more), leave the above ESP8266-01 for later when you are more experienced with the ESP.
After you know how to program the ESP with B4R IDE it will be easy to connect to Android device directly, even simpler than my above example.

NodeMcu:
upload_2016-9-6_21-55-47.png
 
Upvote 0

sanjog shakya

Member
Licensed User
Longtime User
You can see and buy a FTDI here https://www.aliexpress.com/item/Fre...2286073399.html?spm=2114.13010608.0.59.n5zTVa
You cannot program this esp by Arduino and you need to connect it in a special way for programming and for use, search the net and you'll find.
Other ESP8266 cards, like WEMOS D1 or NodeMcu have a USB connection and can be programmed directly using the Arduino IDE or B4R IDE.
I advise you to get NodeMcu as it has more GPIO ports and USB (and only costs about 1$ more), leave the above ESP8266-01 for later when you are more experienced with the ESP.
After you know how to program the ESP with B4R IDE it will be easy to connect to Android device directly, even simpler than my above example.

NodeMcu:
View attachment 47590

Thank u so much derez for your time.I will search NodeMCU dealer in Nepal.But here those new modules maynot be available.And its lil difficult to purchase Online.
Anyway thanks i will be in touch.
 
Upvote 0
Top