TCP Socket in Photon

I am new to Photon so excuse my ignorance. I am trying to setup (and open) a TCP socket file descriptor(fd) that i can then use as a global variable to communicate with (in the callback functions).

I have tried declaring the fd in a startup function then using it in my callbacks as an extern. If i do this, it compiles but the program crashes as soon as the callback is started. I am worried that the variable is being destroyed when the startup function finishes.

However if i declare the file descriptor in the main file then use it as an extern, the compiler says it cant find it when it is referenced in the callbacks.

Can anyone help me. I am not sure if this is the correct approach?

Are you declaring the variable in function scope (i.e. as an auto) ? If so, then your approach is flawed, as the file descriptor is indeed destroyed as the PC moves out of function scope. If you are declaring the file descriptor in file scope then there is nothing fundamentally wrong with your approach, however, in Photon it can sometimes be difficult to tell the order of callbacks, and perhaps the callback that initializes the file descriptor (i.e. does the open()) is called after a callback that tries to use the file descriptor.

Thanks rgallen

I had declared the fd in file scope. But the program still crashes - very strange. I dont think it could be the order if the callbacks as the setup function is pre-realise, but the user functions are only triggered by buttons.

I started again, with a new project and now works fine!?!

Check for the success of opening the file descriptor. If not successful the return with Pt_CONTINUE then there won’t be any problems. Atleast the program won’t crash

fp = fopen(…);
return( Pt_CONTINUE);

The above statements ensure that ur application doesn’t crash