#include "at.h"

#include <zephyr.h>
#include <stdio.h>
#include <string.h>
//#include <zephyr.h>
#include <nrf_socket.h>
#include <net/socket.h>


int at_exec(char * at_command, int at_command_strlen) 
{
	int  at_sock;
	int  bytes_sent;
	int  bytes_received;
	char buf[2];
	int ret = 0;

	at_sock = socket(AF_LTE, 0, NPROTO_AT);
	if (at_sock < 0)
	{
		printk("[%s:%d] ERROR: AT commands socket error.\n", __func__, __LINE__);
                return -1;
	}

	bytes_sent = send(at_sock, at_command, at_command_strlen, 0);
	
	if (bytes_sent < 0)
	{
		close(at_sock);
		return -1;
	}
		
	do
	{
		bytes_received = recv(at_sock, buf, 2, 0);
	} while (bytes_received == 0);
	
	if (memcmp(buf, "OK", 2) != 0)
		ret = -1;
	
	close(at_sock);	
	return ret;
}

/*
	out_reply_str - an allocated string of length out_reply_str_len
*/
int at_exec_reply(char * at_command, int at_command_strlen, char * out_reply_str, int out_reply_str_len) 
{
	int  at_sock;
	int  bytes_sent;
	int  bytes_received;
	int ret = 0;

	at_sock = socket(AF_LTE, 0, NPROTO_AT);
	if (at_sock < 0)
	{
		printk("[%s:%d] ERROR: AT commands socket error.\n", __func__, __LINE__);
		return -1;
	}

	bytes_sent = send(at_sock, at_command, at_command_strlen, 0);
	
	if (bytes_sent < 0)
	{
		close(at_sock);
		return -1;
	}
		
	do
	{
		bytes_received = recv(at_sock, out_reply_str, out_reply_str_len, 0);
	} while (bytes_received == 0);
	ret = bytes_received;
	
	close(at_sock);	
	return ret;
}


