B4R Question Can't send more than one push message ESP8266

Åke Johansson Bravida

Member
Licensed User
I have tryed this code but I don't understand why I can't send more than one SendMessage?

When input #14 is low TDelay is started and after 40 sec. the TDelay_Tick Sub is executed and my message is sent to fcm.googleapis.com/fcm/send and I get this Log.

Tidsfördröjningen är aktivrad! = "delay activated"

stack: 316, buffer size:145
trying to connect to: fcm.googleapis.com port: 443 ssl: 1
connected: fcm.googleapis.com
HTTP/1.0 200 OK
Content-Type: application/json; charset=UTF-8
Date: Sat, 21 Dec 2019 21:13:45 GMT

Expires: Sat, 21 Dec 2019 21:13:45 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options:
nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alt-Svc: quic=":
443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma
=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000
Accept-Ranges: none
Vary: Accept-En
coding
{"message_id":1217586609119534674}
JobDone: general
Success: 1


Everything is ok but now is my Timer1 enabled and when Timer1_Tick Sub is executed my SendMessage is not sent to firebase? I got this Log.


stack: 316, buffer size:148
trying to connect to: fcm.googleapis.com port: 443 ssl: 1
JobDone: general
Success: 0


Why can't this message be sent to firebase? If I let the program run an hour or so I get the message 3-4 times but I expected this message every 5 minutes. And stop when input is going to high "1" when everything is stopped.

Is it not ok to have SendMessage in timer event?

What am I doing wrong?

Thanks for considering my requst.





B4X:
'Åke Artklo Willo kyltork. 2019-12-17
'Modifierad med ingångsfördröjning 2019-12-19.

#Region Project Attributes
   #AutoFlushLogs: True
   #CheckArrayBounds: True
   #StackBufferSize: 2500
#End Region
'        static const Byte D0   = 16;
'        static const Byte D1   = 5;
'        static const Byte D2   = 4;
'        static const Byte D3   = 0;
'        static const Byte D4   = 2;
'        static const Byte D5   = 14;
'        static const Byte D6   = 12;
'        static const Byte D7   = 13;
'        static const Byte D8   = 15;
'        static const Byte RX   = 3;
'        static const Byte TX   = 1;   
Sub Process_Globals
    Public Serial1 As Serial
    Private inP As D1Pins
    Private D5 As Pin
    Public inPState As Boolean = True
    Private TDummy As Timer
    Public Timer1 As Timer
    Public TDelay As Timer
    Public TOffDelay As Timer
    Public TDelay_Elapsed As Boolean = False
    Public Timer1_State As Boolean = False
    Public TDelay_State As Boolean = False
    Public TOffDelay_State As Boolean = False
    Private API_KEY() As Byte = "AAAA2S"
    Private wifi As ESP8266WiFi
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    If wifi.Connect2("router","password") Then 'change as needed
        Log("Connected to router.")
        Else
        Log("Failed to connect to router!!!")
        Return
    End If
    Log("AppStart")
    Timer1.Initialize("Timer1_Tick", 300000) ' Skickas var 5:e minut!!
    Timer1.Enabled = False
    TDelay.Initialize("TDelay_Tick", 40000) ' Fördröjning innan larm skickas.
    TDelay.Enabled = False
    TOffDelay.Initialize("TOffDelay_Tick", 40000) 'Fördröjning avstängning larm.
    TOffDelay.Enabled = False
    TDummy.Initialize("TDummy_Tick", 30000) 'Timer för att komma förbi timer stopp workaround.
    TDummy.Enabled = True
    D5.Initialize(inP.D5, D5.MODE_INPUT_PULLUP)
    D5.AddListener("inP_StateChanged")

    Log("send the android message when input #14 is aktivated.")
    'SendMessage("general", "This is the title", "This is the body")
    'SendMessage("general", "AppStart!!", "Sent the android message!!!")
End Sub

Sub JobDone (jr As JobResult)
    Log("JobDone: ", jr.JobName)
    Log("Success: ", jr.Success)
    If jr.JobName = "ios_general" Then
        'send the ios message
        SendMessage("ios_general", "This is the title", "This is the body")
    End If
End Sub

Private Sub SendMessage(Topic() As Byte, Title() As Byte, Body() As Byte)
    Dim bc As ByteConverter
    HttpJob.Initialize(bc.StringFromBytes(Topic))
    Dim buffer(200) As Byte 'must be large enough to hold the message payload
    Dim raf As RandomAccessFile
    raf.Initialize(buffer, True)
    WriteBytes(raf, "{""data"":{""title"":""")
    WriteBytes(raf, Title)
    WriteBytes(raf, """,""body"":""")
    WriteBytes(raf, Body)
    WriteBytes(raf, """}")
    'end of data
    WriteBytes(raf, ",""to"":""\/topics\/")
    WriteBytes(raf, Topic)
    WriteBytes(raf, """")
    WriteBytes(raf, ",""priority"": 10")
    If bc.StartsWith(Topic, "ios_") Then
        WriteBytes(raf, ",""notification"": {""title"": """)
        WriteBytes(raf, Title)
        WriteBytes(raf, """,""body"":""")
        WriteBytes(raf, Body)
        WriteBytes(raf, """, ""sound"": ""default""}")
    End If
    WriteBytes(raf, "}")
    HttpJob.AddHeader("Authorization", JoinBytes(Array("key=".GetBytes, API_KEY)))
    HttpJob.AddHeader("Content-Type", "application/json")
    Log("stack: ", StackBufferUsage, ", buffer size:", raf.CurrentPosition)
    HttpJob.Post("https://fcm.googleapis.com/fcm/send", bc.SubString2(buffer, 0, raf.CurrentPosition))
End Sub

Private Sub WriteBytes(raf As RandomAccessFile, Data() As Byte)
    raf.WriteBytes(Data, 0, Data.Length, raf.CurrentPosition)
End Sub


Sub inP_StateChanged (State As Boolean)
    Log("inP_StateChanged = ", State)
    If State = False Then 'Ingången aktiverad "LÅG"
        Log("Tidsfördröjningen är aktivrad!")
        TDelay.Enabled = True
        TOffDelay.Enabled = False
        Else
            'Ingången opåverkad "HÖG"
            If TDelay_Elapsed = True Then ' Tidsfördröjning har gått ut. Vi har en signal som är längre än TDelay är satt till.
                Log("Larmet är avstängt avstängning fördröjning är aktiverad!!")
                'SendMessage("general", "Willo Maskin SUMMALARM kyltork !", "Summalarm AVSTÄNGT kyltorken är NORMAL")
                TDelay_Elapsed = False
                Timer1.Enabled = False
                TOffDelay.Enabled = True
               
                Else 'Tidsfördröjningen har inte gått full tid så det är troligen felsignal stäng av signalfördröjningen.
                    Log("Tidsfördröjningen avstängd och inget larm skickas. 'Störning!'")
                    TDelay.Enabled = False
                End If
    End If
End Sub

Sub TDelay_Tick
    TOffDelay_State = False
    TDelay.Enabled = False
    TDelay_Elapsed = True
    Timer1.Enabled = True
    Log("Tidsfördröjningen har gått larm skickas!")
    TDelay_State=True
    SendMessage("general", "Willo Maskin summalarm 0:AKTIVT kyltork !!", "FEL! Kyltorken  L A R M A R  !!!")
End Sub

Sub Timer1_Tick
    Log("Timer1 fördröjningen mellan aktiva larm aktiverad!")
    Timer1_State=True
    SendMessage("general", "Willo Maskin summalarm 1:AKTIVT kyltork loop!", "FEL! Kyltorken  L A R M A R  !!!")
End Sub

Sub TOffDelay_Tick
    Log("TOffDelay fördröjningen aktivtlarm avstängt!")
    TOffDelay_State = True
    SendMessage("general", "Willo Maskin SUMMALARM kyltork off!", "Summalarm AVSTÄNGT kyltorken är NORMAL")
    Timer1_State = False
    TDelay_State = False
    TOffDelay.Enabled = False
End Sub

Sub TDummy_Tick
    Log(" ")
End Sub

code
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
I'm able to send many messages with code based on the example code:
B4X:
Sub Process_Globals
   Public Serial1 As Serial
   Private API_KEY() As Byte = "AAAAOkXbhq..."
   Private wifi As ESP8266WiFi
   Private timer As Timer
End Sub

Private Sub AppStart
   Serial1.Initialize(115200)
   If wifi.Connect2("TP-LINK_D577", "...") Then
       Log("Connected to router.")
   Else
       Log("Failed to connect to router.")
       Return
   End If
   Log("AppStart")
   'send the android message
   timer.Initialize("timer_Tick", 5000)
   timer.Enabled = True
End Sub

Sub Timer_Tick
   SendMessage("general", "This is the title", "This is the body")
End Sub

Sub JobDone (jr As JobResult)
   Log("JobDone: ", jr.JobName)
   Log("Success: ", jr.Success)
End Sub

'other code from: https://www.b4x.com/android/forum/threads/firebase-push-messages-fcm.81025/
 
Upvote 0

Åke Johansson Bravida

Member
Licensed User
Thank you for your replay.

So I tryed with 60 seconds delay on my timer and thats working fine but when i try with 90 seconds it stops to send messages.
Now I try with 70sec, and it's working most of the time but not always?
What might cause this strange behavior?
 
Upvote 0

Åke Johansson Bravida

Member
Licensed User
I tryed with 5 minutes but I get thiss response from the Log

Connected to router.
stack: 316, buffer size:148
trying to connect to: fcm.googleapis.com port: 443 ssl: 1
JobDone: general
Success: 0

I did what Erel said. :-(

No something else is wrong.
Any ideas?
 
Upvote 0

Åke Johansson Bravida

Member
Licensed User
THe first message is sent but not the second.

Connected to router.
Timer1 delay in between activ alarm activated!
stack: 316, buffer size:148
trying to connect to: www.bravida.se port: 443 ssl: 1
JobDone: general
Success: 0

so it's the same problem. Problem is when the time are 70 seconds or longer.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
It works properly with this code:
B4X:
Private Sub AppStart
   Serial1.Initialize(115200)
   Log("AppStart")
   timer.Initialize("timer_Tick", 100000)
   timer.Enabled = True
   Timer_Tick
End Sub

Sub Timer_Tick
   wifi.Disconnect
   If wifi.Connect2("TP-LINK_D577", "xxx") Then
       Log("Connected to router.")
   Else
       Log("Failed to connect to router.")
       Return
   End If
   SendMessage("general", "This is the title", "This is the body")
End Sub

I'm not sure why it happens. You can probably keep the network live by sending "ping" requests, though reconnecting each time seems to work properly.
 
Upvote 0

Åke Johansson Bravida

Member
Licensed User
Yes this code is running. Perfect, thank you for your replay this day.

This code solved the problem.

B4X:
 wifi.Disconnect
   If wifi.Connect2("TP-LINK_D577", "xxx") Then
       Log("Connected to router.")
   Else
       Log("Failed to connect to router.")
       Return
   End If

A special day for many people but I am working like usual.

I appreciate your fast response.
Thank you very much :):):)
 
Upvote 0
Top