

(* @NESTEDCOMMENTS := 'Yes' *)
(* @PATH := '\/MQTT_UDP' *)
(* @OBJECTFLAGS := '0, 8' *)
(* @SYMFILEFLAGS := '2048' *)
FUNCTION MQ_SEND_REAL : BOOL
VAR_INPUT
	MQ		:	MQTT_UDP;
	topic	:	STRING;
	data	:	REAL;
END_VAR
VAR
END_VAR
(* @END_DECLARATION := '0' *)

	MQ( topic:= topic,  data := REAL_TO_STRING( data ) );
	MQ_SEND_REAL := TRUE; (* TODO success *)
	RETURN;
END_FUNCTION


(* @NESTEDCOMMENTS := 'Yes' *)
(* @PATH := '\/MQTT_UDP' *)
(* @OBJECTFLAGS := '0, 8' *)
(* @SYMFILEFLAGS := '2048' *)
FUNCTION MQTT_SEND : BOOL

VAR_INPUT
	socket				:	DINT;

	topic 				:	STRING;
	data 				:	STRING;

	sock_adr_out		:	SOCKADDRESS;
END_VAR

VAR
	tlen				:	DINT;
	dlen 				:	DINT;
	total 				: 	DINT;
	PT 					:	POINTER TO BYTE;
	buf					:	ARRAY[0..128] OF BYTE;

	bindex 				: 	DINT;

END_VAR
(* @END_DECLARATION := '0' *)

	tlen := LEN(topic);
	dlen :=LEN(data);

	total := tlen + dlen + 2 + 2; (* max packet size *)

	IF total >= 127 THEN
		MQTT_SEND := FALSE;
		RETURN;
	END_IF

	buf[0] := 16#30;
	buf[1] := DINT_TO_BYTE( total - 2 ) AND 16#7F;

	buf[2] := SHR( DINT_TO_BYTE( tlen ), 8 ) AND 16#FF;
	buf[3] := DINT_TO_BYTE( tlen ) AND 16#FF;

	bindex := 4;

	PT := ADR( topic );
	WHILE tlen > 0 DO
		tlen := tlen - 1;

		buf[bindex] := PT^;

		PT := PT + 1;
		bindex := bindex + 1;
	END_WHILE

	PT := ADR( data );
	WHILE dlen > 0 DO
		dlen := dlen - 1;

		buf[bindex] := PT^;

		PT := PT + 1;
		bindex := bindex + 1;
	END_WHILE

	SysSockSendTo( socket, ADR( buf[0] ), total, 0, ADR( sock_adr_out ), SIZEOF( sock_adr_out ) );

	MQTT_SEND := TRUE;

END_FUNCTION


(* @NESTEDCOMMENTS := 'Yes' *)
(* @PATH := '\/MQTT_UDP' *)
(* @OBJECTFLAGS := '0, 8' *)
(* @SYMFILEFLAGS := '2048' *)
FUNCTION_BLOCK MQTT_UDP

VAR_INPUT
	topic 				:	STRING;
	data 				:	STRING;
END_VAR

VAR_OUTPUT
END_VAR

VAR
	socket			:	DINT := SOCKET_INVALID;
	wOutPort		:	INT := 1883;
	m_SAddress		:	SOCKADDRESS;

END_VAR
(* @END_DECLARATION := '0' *)

	IF socket = SOCKET_INVALID THEN
		SysSockClose( socket );
		socket := SysSockCreate( SOCKET_AF_INET, SOCKET_DGRAM, SOCKET_IPPROTO_UDP );

		m_SAddress.sin_family	:= SOCKET_AF_INET;
		m_SAddress.sin_port	:= SysSockHtons( wOutPort );
		m_SAddress.sin_addr	:= 16#FFFFFFFF; (* broadcast *)
	END_IF

	MQTT_SEND( socket, topic, data, m_SAddress );

END_FUNCTION_BLOCK
