Socket v2 example
Socket_v2_example
#include <io>
#include <read>
#include <float>
#include <string>
#include <core>
#include <write>
#include <define>
#include <socket>
new socketRx[500]; // Array
forward public callback (sk);
public callback (sk)
{
switch(sk)
{
case Socket_data_received: // Socket data received callback event
{
ReadSocket(); // Go to ReadSocket() function
}
case Socket_closed: // Socket closed callback event
{
write_buf(RS232, 15, "Socket closed\r\n"); // Print text through RS232
}
}
return 0;
}
ReadSocket() // ReadSocket() function
{
socket(READ, socketRx); // Read socket buffer into socketRx array
if(strcmp(socketRx, "Hello", false, 5)==0) // Compare received message with "Hello" string
{ // If match do...
}
write_buf(RS232, 17, "Socket received: "); // Print text through RS232
write_buf(RS232, strlen(socketRx), socketRx); // Print sokcetRx buffer
write_buf(RS232, 2, "\r\n");
}
main()
{
Init(RS232, 9600, WORDLENGTH_8, STOPBITS_1, PARITY_NONE); // Init RS232, Baud rate: 9600, Word length: 8bit, Stop bit: 1, Parity: none
Delay(10000); // Delay 10 sec.
Connect_to_socket(); // Go to Connect_to_socket() function
while(1)
{
Delay(2000); // Delay 30 sec.
Socket_send("Ping"); // Send message through socket using function
}
}
Socket_send(text[200]){
new stat = 0;
while(stat == 0){
stat = socket(SEND, strlen(text), text); // Send text through socket
write_buf(RS232, 9, "Sending: ");
write_buf(RS232, strlen(text), text);
write_buf(RS232, 2, "\r\n");
if(stat != 1){ // if get error and message did't send
Check_socket(); // Go to function Check_socket();
Delay(1000); // Delay 1 sec.
}
}
}
Connect_to_socket(){
new PDP_active = 0;
new Socket_connected = 0;
while(PDP_active == 0){
PDP_active = get_val(Sensor_SignalPDPActive);
if(PDP_active == 0){
write_buf(RS232, 21, "Waiting PDP context\r\n"); // Print text through RS232
Delay(10000); // Delay 10 sec.
}
}
while(Socket_connected == 0){
Socket_connected = socket(CREATE_UDP, "domain.com", 1234); // Connect to socket, port number: 1234
if(Socket_connected != CONNECTED){
Delay(5000); // Delay 5 sec.
}
}
write_buf(RS232, 18, "Socket connected\r\n"); // Print text through RS232
}
Check_socket(){
new stat = 0;
stat = socket(STATUS);
if((stat == NO_INTERNET) || (stat == SOCKET_SHUT) || (stat == SOCKET_NOT_CREATED) || (stat == NO_SOCKET) ){
Connect_to_socket();
Delay(1000);
}
}