I use GSM module Telit GL865 in UART communication with STM32F7 MCU and softwares STM32CubeMX, Keil.
When I send AT commands over UART to GSM module as below, I get an IP address by the internal stack of the GSM module and ping it successfully:
AT
AT&K0
AT#SCFG=3,1,300,600,300,10
AT+CGDCONT=1,"IP","mgbs","0.0.0.0",0,0
AT+CGSN
AT#ICMP=2
AT#GPPPCFG="000.000.000.000",25,1
AT#GPPPCFGEXT=0
ATDT*99#
CONNECT
However, when I start a PPPoS session, I cannot ping the IP which was successfully established over PPP.
The IP, gateway and netmask addresses that are established over PPP stack are as follows:
IP = 5.26.61.173
Gateway = 192.168.202.0
Netmask = 255.255.255.255
The first problematic thing I viewed is the Netmask address; however, LwIP PPPoS establishes this.
Secondly, after the establishment above, MCU and GSM module starts to send periodic data to each other as "~y " with length 49 and 53 respectively.
That means my debugging of printf( ) cannot show me all of the periodic data.
Thirdly, the most important, when I ping the IP of GSM above, the periodic data "~y " with length 68, is sent much more in time between MCU and GSM, means that pinging triggers the communication between GSM and MCU but no response back.
I use interrupt based UART transceiving which starts to fill the received buffer and put it into pppos_input_tcpip(ppp, recBuffer, recIndex) unless new data comes in 10ms.
The main thread, and the timer interrupt is as follows:
/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "cmsis_os.h"
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include "string.h"
#include "main.h"
#include "stm32f7xx_hal.h"
#include "cmsis_os.h"
#include "lwip.h"
#include "usart.h"
#include "gpio.h"
#include <stdio.h>
#include "string.h"
#include <time.h>
#include "lwip/opt.h"
#include "lwip/sys.h"
#include "lwip/timeouts.h"
#include "lwip/debug.h"
#include "lwip/stats.h"
#include "lwip/init.h"
#include "lwip/tcpip.h"
#include "lwip/netif.h"
#include "lwip/api.h"
#include "lwip/tcp.h"
#include "lwip/udp.h"
#include "lwip/dns.h"
#include "lwip/dhcp.h"
#include "lwip/autoip.h"
#include "lwip/etharp.h"
#include "netif/ethernet.h"
#include "lwip/apps/netbiosns.h"
#include "lwip/apps/httpd.h"
#include "lwip/sio.h"
//#include "ppp/ppp.h"
//#include "netif/ppp/pppapi.h"
//#include "netif/ppp/pppos.h"
#include "pppapi.h"
#include <lwip/sockets.h>
#include "usart.h"
#include "test.h"
#define RX_SIZE 4096
/* USER CODE END Includes */
/* Variables -----------------------------------------------------------------*/
osThreadId defaultTaskHandle;
/* USER CODE BEGIN Variables */
uint8_t lcpBuffer[RX_SIZE];
uint8_t lcpBufferIndex, quantityOfPackages = 0;
uint8_t pppBuffer[4096];
uint32_t sysTickCounter = 0;
uint8_t sendData[50] = " \n";
uint8_t recData, recDataOlder, recDataOlder2,recDataOlder3,recDataOlder4,recDataOlder5,recDataOlder6;
uint8_t receivedValue,connected,called = 0;
uint32_t recIndex = 0;
uint8_t recBuffer[RX_SIZE];
uint8_t sent, send, connect, connectionStatus, endOfLcpNegotiation, NCPNegotiation = 0;
ppp_pcb *ppp;
struct netif ppp_netif;
u8_t sio_idx = 0;
sio_fd_t ppp_sio;
uint8_t ATconnected,lcpCame,length = 0;
uint8_t lcpStartIndex, lcpStopIndex, lcpStartOld, lcpStart, lcpStop, dataReceived, timeOut, fillThePPPBuffer, gsmInitEnd, sendLCP, sendNCP, socketOpened, socketBind, socketOpen = 0;
uint32_t pppBufferIndex = 0;
ip4_addr_t addr;
int socketStatus;
int socket_fd,accept_fd;
int addr_size,sent_data; char data_buffer[80];
struct sockaddr_in sa,ra,isa;
uint32_t runTimeCnt = 0;
void StartDefaultTask(void const * argument);
extern void MX_LWIP_Init(void);
void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */
//PPP function
static void status_cb(ppp_pcb *pcb, int err_code, void *ctx) {
struct netif *pppif = ppp_netif(pcb);
called = 1;
switch(err_code) {
case PPPERR_NONE: {
connectionStatus = 1;
printf("status_cb: Connected\n");
printf(" our_ipaddr = %s\r\n", ipaddr_ntoa(&pppif->ip_addr));
printf(" gatewayaddr = %s\r\n", ipaddr_ntoa(&pppif->gw));
printf(" netmask = %s\r\n", ipaddr_ntoa(&pppif->netmask));
break;
}
case PPPERR_PARAM: {
connectionStatus = 2;
printf("status_cb: Invalid parameter\r\n");
break;
}
case PPPERR_OPEN: {
connectionStatus = 3;
printf("status_cb: Unable to open PPP session\r\n");
break;
}
case PPPERR_DEVICE: {
connectionStatus = 4;
printf("status_cb: Invalid I/O device for PPP\r\n");
break;
}
case PPPERR_ALLOC: {
connectionStatus = 5;
printf("status_cb: Unable to allocate resources\r\n");
break;
}
case PPPERR_USER: {
connectionStatus = 6;
ppp_free(pcb);
printf("status_cb: User interrupt\r\n");
break;
}
case PPPERR_CONNECT: {
connectionStatus = 7;
printf("status_cb: Connection lost\r\n");
break;
}
case PPPERR_AUTHFAIL: {
connectionStatus = 8;
printf("status_cb: Failed authentication challenge\r\n");
break;
}
case PPPERR_PROTOCOL: {
connectionStatus = 9;
printf("status_cb: Failed to meet protocol\r\n");
break;
}
case PPPERR_PEERDEAD: {
connectionStatus = 10;
printf("status_cb: Connection timeout\r\n");
break;
}
case PPPERR_IDLETIMEOUT: {
connectionStatus = 11;
printf("status_cb: Idle Timeout\r\n");
break;
}
case PPPERR_CONNECTTIME: {
connectionStatus = 12;
printf("status_cb: Max connect time reached\r\n");
break;
}
case PPPERR_LOOPBACK: {
connectionStatus = 13;
printf("status_cb: Loopback detected\r\n");
break;
}
default: {
connectionStatus = 14;
printf("status_cb: Unknown error code %d\r\n", err_code);
break;
}
}
}
//PPP function
static u32_t output_cb(ppp_pcb *pcb, u8_t *data, u32_t len, void *ctx){
printf("sent: %s with length: %d\r\n",data,len);
return HAL_UART_Transmit_IT(&huart1, data, len);
}
/* Init FreeRTOS */
void MX_FREERTOS_Init(void) {
/* Create the thread(s) */
/* definition and creation of defaultTask */
osThreadDef(defaultTask, StartDefaultTask, osPriorityNormal, 0, 1024);
defaultTaskHandle = osThreadCreate(osThread(defaultTask), NULL);
}
/* StartDefaultTask function */
void StartDefaultTask(void const * argument)
{
/* init code for LWIP */
MX_LWIP_Init();
/* USER CODE BEGIN StartDefaultTask */
//SysTick_Config(SystemCoreClock/1000);
HAL_UART_Receive_IT(&huart1, &recData, 1);
// Start of AT commands
HAL_Delay(1000);
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT\r\n", strlen("AT\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT&K0\r\n", strlen("AT&K0\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#SCFG=3,1,300,600,300,10\r\n", strlen("AT#SCFG=3,1,300,600,300,10\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#SLED=2,2,2\r\n", strlen("AT#SLED=2,2,2\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#SLEDSAV\r\n", strlen("AT#SLEDSAV\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT+CGDCONT=1,\"IP\",\"mgbs\",\"0.0.0.0\",0,0\r\n", strlen("AT+CGDCONT=1,\"IP\",\"mgbs\",\"0.0.0.0\",0,0\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT+CGSN\r\n", strlen("AT+CGSN\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#ICMP=2\r\n", strlen("AT#ICMP=2\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT+CSQ\r\n", strlen("AT+CSQ\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT+CCLK?\r\n", strlen("AT+CCLK?\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#SGACT?\r\n", strlen("AT#SGACT?\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#SGACT=1,0\r\n", strlen("AT#SGACT=1,0\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#SGACT=1,1\r\n", strlen("AT#SGACT=1,1\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#SGACT?\r\n", strlen("AT#SGACT?\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#FRWL=1,\"10.0.1.1\",\"255.255.0.0\"\r\n", strlen("AT#FRWL=1,\"10.0.1.1\",\"255.255.0.0\"\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#GPPPCFG=\"000.000.000.000\",25,1\r\n", strlen("AT#GPPPCFG=\"000.000.000.000\",25,1\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#GPPPCFGEXT=0\r\n", strlen("AT#GPPPCFGEXT=0\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"AT#GAUTH=0\r\n", strlen("AT#GAUTH=0\r\n"));
HAL_Delay(1000);
memset(recBuffer, 0, sizeof(recBuffer));
recIndex = 0;
HAL_UART_Transmit_IT(&huart1, (uint8_t*)"ATDT*99***1#\r\n", strlen("ATDT*99***1#\r\n"));
//End of AT commands
//Start PPP
ppp = pppapi_pppos_create(&ppp_netif, output_cb, status_cb, NULL);
if (ppp == NULL) {
printf("Error init pppos");
return;
}
pppapi_set_default(ppp);
ppp_set_auth(ppp, PPPAUTHTYPE_NONE, "", "");
pppapi_listen(ppp);
for(;;)
{
//if GSM is initialized, give data to ppp if stops coming after 10ms,
//send flag is set by systick(10ms) and gsmInitEnd is set after LCP session starts
if(gsmInitEnd){
if(send){
send = 0;
pppos_input_tcpip(ppp, recBuffer, recIndex);
printf("received: %s with length: %d\r\n", recBuffer, recIndex);
recIndex = 0;
runTimeCnt++;
memset(recBuffer, 0, sizeof(recBuffer));
}
}
}
}
// UART rx callback, called over 1 data received
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle)
{
if (UartHandle->Instance == USART1)
{
//callback reset
HAL_UART_Receive_IT(&huart1, &recData, 1);
//receive buffer overflow check
if(recIndex >= RX_SIZE){
recIndex = 0;
}
//3 variables below are externed to send data if stops coming to
//buffer after 10ms with Systick interrupt later than GSM initialization
dataReceived = 1;
sysTickCounter = 0;
send = 0;
//LCP packets start with 0x7E, that means the end of GSM initialization.
if(recData == 0x7E)
{
if(gsmInitEnd == 0){
recIndex = 0;
memset(recBuffer, 0, sizeof(recBuffer));
}
gsmInitEnd = 1;
}
recBuffer[recIndex++] = recData;
}
}
Systick Handler that checks the RX buffer and sets the send flag to send the data to ppp if data stops coming after 10ms:
void SysTick_Handler(void)
{
if(dataReceived){
sysTickCounter++;
if (sysTickCounter >= 10)
{
send = 1;
dataReceived = 0;
sysTickCounter = 0;
}
}
osSystickHandler();
}
Data communication between GSM and STM32 seems OK to me(!) and triggered with ping request; however, no ping response..
In my opinion, problem may be about the connection between ppp_netif and ppp_netif(ppp), netmask or ping implementation of the LwIP stack...
The answer is activating outgoing and incoming ICMP checksum options of STM32CubeMX...So, activating LWIP_ICMP module is insufficient by itself to response ping requests..
If you enable the software checksums for PPPOS, Ethernet breaks because STM32 is doing them in HW on Ethernet - GRRR
Related
I am having issues with my code for an ESP32 Wroom.
I am trying to use both cores on the esp to speed up and create an efficient process for the device; one core checks for a change/response from a website page. and the other changes the led patterns according to the response received.
Core 0 (getting response) should be constantly updating a string called "payload" with the latest received information form the website. this is happening whilst the other core is displaying a pattern until it receives a change in "payload"; and changes accordingly.
the issue i am having is that the esp after uploading and first time starting prints the following message every 1-2 seconds:
rst:0x8 (TG1WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:8896
load:0x40080400,len:5816
entry 0x400806ac
This is also printed in some of the messages:
Guru Meditation Error: Core 0 panic'ed (Double exception)
I am new to ESP32's and have not much experience with Arduino, does anybody know what I am doing wrong or ways of achieving the same aim avoiding the current issues. Thanks in advance.
Here is the code for my project.
TaskHandle_t Task1;
#include <WiFi.h>
#include <Wire.h>
#include <HTTPClient.h>
#include "FastLED.h"
#define NUM_LEDS 50
#define PIN 27
uint8_t hue[NUM_LEDS];
CRGBArray<NUM_LEDS> leds;
const char* ssid = "Username";
const char* password = "Password";
const char* serverName = "https://example.com/page.php";
String apiKeyValue = "tPmAT5Ab3j7F9";
String payload;
void codeForTask1( void * parameter )
{
for (;;)
{
if(WiFi.status() == WL_CONNECTED)
{
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Prepare your HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue;
// Send HTTP POST request
int httpResponseCode = http.GET();
if (httpResponseCode>0)
{
payload = http.getString();
}
}
delay(1000);
}
}
void setup()
{
Serial.begin(115200);
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED) {
delay(500);
}
FastLED.addLeds<NEOPIXEL, PIN>(leds, NUM_LEDS);
for (int i = 0; i < NUM_LEDS; i++)
{
hue[i] = 255 / NUM_LEDS * i;
}
xTaskCreatePinnedToCore(
&codeForTask1,
"led1Task",
2000,
NULL,
1,
&Task1,
0);
delay(500); // needed to start-up task1
}
void loop()
{
String payload2 = payload;
if(payload2.indexOf("rainbow") >= 0)
{
while(payload2.indexOf("rainbow") >= 0)
{
for(int i=0; i<NUM_LEDS; i++)
{
leds[i] = CHSV(hue[i]++, 255, 255);
}
delay(100);
FastLED.show();
}
Serial.print(payload2 + " || Rainbow \n");
}
else if(payload2.indexOf("worm") >= 0)
{
for(int i=0; i<NUM_LEDS; i++)
{
for(int e=0; e<=1; e++)
{
if(e == 0){
leds[i] = CRGB(255, 255, 255);
leds[i+2] = CRGB(255, 255, 255);
leds[i+4] = CRGB(255, 255, 255);
leds[i+6] = CRGB(255, 255, 255);
FastLED.show();
}else{
leds[i] = CRGB(0, 0, 0);
leds[i+2] = CRGB(0, 0, 0);
FastLED.show();
}
delay(100);
}
}
Serial.print(payload2 + " || Worm \n");
}
else if(payload2.indexOf("ant") >= 0)
{
for(int i=0; i<NUM_LEDS; i++) // loop
{
for(int e=0; e<=1; e++)
{
if(e == 0)
{
leds[i] = CRGB(255, 255, 255);
leds[i+1] = CRGB(255, 255, 255);
leds[i+2] = CRGB(0, 0, 0);
leds[i+4] = CRGB(255, 255, 255);
leds[i+5] = CRGB(255, 255, 255);
leds[i+3] = CRGB(0, 0, 0);
FastLED.show();
}
else
{
leds[i] = CRGB(0, 0, 0);
leds[i+1] = CRGB(0, 0, 0);
FastLED.show();
}
delay(50);
}
}
Serial.print(payload2 + " || Ant \n");
}
else if(payload.indexOf("off") >= 0)
{
Serial.print(payload2 + " || Off \n" );
}
else if(!payload2.isEmpty())
{
String dab = payload;
String hexstring = dab;
long number = (long) strtol( &hexstring[0], NULL, 16 );
int r = number >> 16;
int g = number >> 8 & 0xFF;
int b = number & 0xFF;
for(int i=0; i<NUM_LEDS; i++){
leds[i] = CRGB(r, g, b);
}
FastLED.show(); // start new rgb led strip assignment/patterns
Serial.print(payload2 + " || CUSTOM COLOR \n");
}
delay(1000);
Serial.print("Task 1: Done \n");
}
I am running a simple web server (static IP) based on the default web server example, which is occasionally interrupted by an external input (eg. RFID reader) which sends data as a client to another server in the local network and starting the server again. the device runs as intended for a few days but then stops responding to pin inputs, accessing the server page seems to get it back on line (not sure about this) otherwise I am forced to manually reset when this happens.
Could using Serial Print(used during the debugging stage) without connecting a serial monitor be the issue?
test code:
/*
This program will decode the wiegand data from a HID RFID Reader (or, theoretically,
any other device that outputs weigand data).
The Wiegand interface has two data lines, DATA0 and DATA1. These lines are normally held
high at 5V. When a 0 is sent, DATA0 drops to 0V for a few us. When a 1 is sent, DATA1 drops
to 0V for a few us. There is usually a few ms between the pulses.
Your reader should have at least 4 connections (some readers have more). Connect the Red wire
to 5V. Connect the black to ground. Connect the green wire (DATA0) to Digital Pin 2 (INT0).
Connect the white wire (DATA1) to Digital Pin 3 (INT1). That's it!
Operation is simple - each of the data lines are connected to hardware interrupt lines. When
one drops low, an interrupt routine is called and some bits are flipped. After some time of
of not receiving any bits, the Arduino will decode the data.
*/
#include <Ethernet.h>
#include <SPI.h>
#include <EEPROM.h>
#define MAX_BITS 100 // max number of bits
#define WEIGAND_WAIT_TIME 3000 // time to wait for another weigand pulse.
unsigned char databits[MAX_BITS]; // stores all of the data bits
unsigned char bitCount; // number of bits currently captured
unsigned char flagDone; // goes low when data is currently being captured
unsigned int weigand_counter; // countdown until we assume there are no more bits
unsigned long facilityCode = 0; // decoded facility code
unsigned long cardCode = 0; // decoded card code
byte tr = 0; //testing trigger
byte ship[4]; //Home Center IP
byte wsip[4]; //Web Server IP
int scene[100]; //scene ID storage
//byte ptr = 0; //log pointer
byte ld = 0; //latest updated log
byte bc[20]; //Wiegand bitCount log
unsigned long wd[20]; //Wiegand data log
String readString1; //IP buffer
String tempstr = "{\r\n\"value\":\"";
String PostData = "{\r\n\"value\":\"1\"\r\n}"; //JSON data to send
// interrupt that happens when INTO goes low (0 bit)-2
void ISR_INT0()
{
Serial.print("0"); // uncomment this line to display raw binary
bitCount++;
flagDone = 0;
weigand_counter = WEIGAND_WAIT_TIME;
tr = 1;
}
// interrupt that happens when INT1 goes low (1 bit)
void ISR_INT1()
{
Serial.print("1"); // uncomment this line to display raw binary
if(bitCount<MAX_BITS)
databits[bitCount] = 1;
bitCount++;
flagDone = 0;
weigand_counter = WEIGAND_WAIT_TIME;
}
byte mac[] = { 0x00, 0xAB, 0xCB, 0xCD, 0xDE, 0x05 };
// byte ip[] = {192,168,4,101};
IPAddress ip(192, 168, 5, 211);
// byte gateway[] = {192,168,4,254};
// byte gateway[] = {192, 168, 5, 1};
// byte subnet[] = {255, 255, 255, 0};
// IPAddress server(192,168,4,100);
IPAddress sh(192, 168, 5, 65);
EthernetServer server(80); //server port arduino server will use
EthernetClient client;
char cnt1 = 0, cnt2 = 0;
void setup()
{
//pinMode(13, OUTPUT); // LED
pinMode(2, INPUT_PULLUP); // DATA0 (INT0)
pinMode(3, INPUT_PULLUP); // DATA1 (INT1)
Serial.begin(9600);
Serial.println("BioLite Net");
attachInterrupt(0, ISR_INT0, FALLING);
attachInterrupt(1, ISR_INT1, FALLING);
// binds the ISR functions to the falling edge of INTO and INT1
EEPROM.get(15, wsip);
IPAddress ip(wsip[0], wsip[1], wsip[2], wsip[3]);
net();
delay(10);
server.begin();
Serial.print(F("Web server is at "));
Serial.println(ip);
// Serial.print(F("server is at "));
// Serial.println(Ethernet.localIP());
EEPROM.get(10, ship);
IPAddress sh(ship[0], ship[1], ship[2], ship[3]);
Serial.print(F("Home Center is at "));
Serial.println(sh);
Serial.println(F("stored scenes are :"));
EEPROM.get(20, scene);
for (byte i = 0; i < 10 ; i++)
{
for (byte j = 0; j < 10 ; j++)
{
Serial.print((10 * i) + j);
Serial.print(" : ");
Serial.print(scene[(10 * i) + j]);
Serial.print(" ; ");
}
Serial.println();
}
EEPROM.get(310, bc);
EEPROM.get(330, wd);
EEPROM.get(305, ld);
byte temp = ld;
Serial.println(temp);
for (byte i = 0; i < 10 ; i++)
{
for (byte j = 0; j < 2 ; j++)
{
Serial.print(bc[temp]);
Serial.print(" : ");
Serial.print(wd[temp], BIN);
Serial.print(" ; ");
if (temp == 0)
temp = 20;
temp--;
}
Serial.println();
}
Serial.println();
/* temp = 19;
for (byte i = 0; i < 10 ; i++)
{
for (byte j = 0; j < 2 ; j++)
{
Serial.print(bc[temp]);
Serial.print(" : ");
Serial.print(wd[temp], BIN);
Serial.print(" ; ");
temp--;
if (temp < 0)
temp = 19;
}
Serial.println();
}*/
weigand_counter = WEIGAND_WAIT_TIME;
}
void loop()
{
// This waits to make sure that there have been no more data pulses before processing data
if (!flagDone) {
if (--weigand_counter == 0)
flagDone = 1;
}
// if we have bits and we the weigand counter went out
if (bitCount > 0 && flagDone) {
//if (tr == 1) {
tr == 0; delay(3000);
unsigned char i;
Serial.println();
if(bitCount>255) bitCount=255;
EEPROM.get(305, ld);
EEPROM.get(310, bc);
EEPROM.get(330, wd);
ld++;
if (ld > 19)
ld = 0;
Serial.println(ld);
// ptr += 5;
// ld = (ptr - 310) / 5;
bc[ld] = bitCount;
wd[ld] = 0;
for (i = 0; i < bitCount; i++)
{
Serial.print(databits[i]);
wd[ld] <<= 1;
wd[ld] |= databits[i];
}
EEPROM.put(305, ld);
EEPROM.put(310, bc);
EEPROM.put(330, wd);
Serial.println();
Serial.print("Read ");
Serial.print(bitCount);
Serial.print(" bits. ");
// we will decode the bits differently depending on how many bits we have
// see www.pagemac.com/azure/data_formats.php for mor info
if (bitCount == 35)
{
// 35 bit HID Corporate 1000 format
// facility code = bits 2 to 14
for (i = 2; i < 14; i++)
{
facilityCode <<= 1;
facilityCode |= databits[i];
}
// card code = bits 15 to 34
for (i = 14; i < 34; i++)
{
cardCode <<= 1;
cardCode |= databits[i];
}
printBits();
}
else if (bitCount == 37)
{
// HID 37 bit format H10304
// facility code = bits 2 to 17
for (i = 1; i < 17; i++)
{
facilityCode <<= 1;
facilityCode |= databits[i];
}
// card code = bits 18 to 36
for (i = 17; i < 36; i++)
{
cardCode <<= 1;
cardCode |= databits[i];
}
printBits();
}
else if (bitCount == 34)
{
// HID 34 bit format N1002
// facility code = bits 2 to 17
for (i = 1; i < 17; i++)
{
facilityCode <<= 1;
facilityCode |= databits[i];
}
// card code = bits 18 to 33
for (i = 17; i < 33; i++)
{
cardCode <<= 1;
cardCode |= databits[i];
}
printBits();
}
else if (bitCount == 26)
{
// standard 26 bit format H10301
// facility code = bits 2 to 9
for (i = 1; i < 9; i++)
{
facilityCode <<= 1;
facilityCode |= databits[i];
}
// card code = bits 10 to 25
for (i = 9; i < 25; i++)
{
cardCode <<= 1;
cardCode |= databits[i];
}
printBits();
}
else if (bitCount == 11)
{
// older Magstripe 11 bit format
// facility code = bits 6 to 9
for (i = 5; i < 9; i++)
{
facilityCode <<= 1;
facilityCode |= databits[i];
}
// card code = bits 1 to 5
for (i = 0; i < 5; i++)
{
cardCode <<= 1;
cardCode |= databits[i];
}
printBits();
}
else {
// you can add other formats if you want!
Serial.println("Unable to decode.");
}
EEPROM.get(10, ship);
IPAddress sh(ship[0], ship[1], ship[2], ship[3]);
EEPROM.get(20, scene);
String tempstr = "{\r\n\"value\":\"";
String PostData = "{\r\n\"value\":\"1\",\"invokeScenes\":true\r\n}"; //JSON data to send
tempstr = tempstr + cardCode;
PostData = tempstr + "\",\"invokeScenes\":true\r\n}";
if (client.connect(sh, 80)) {
client.print("GET /api/sceneControl?id=");
client.print(scene[cardCode]);
client.println("&action=start HTTP/1.1");
auth(sh);
Serial.print("Scene ");
Serial.print(scene[cardCode]);
Serial.println(" treggered");
/* }
if (Ethernet.begin(mac) == 0) {
Serial.println(F("Failed to configure Ethernet using DHCP"));
delay(3000);
Ethernet.begin(mac, ip);
if (Ethernet.localIP() != ip)
{
Serial.println(F("Failed to configure Ethernet using static IP"));
for (;;)
;
}
}
if (!client.connected())client.stop();
delay(1);
if (client.connect(sh, 80)) {*/
client.println("PUT /api/globalVariables/UID HTTP/1.1");
auth(sh);
Serial.print(cardCode);
Serial.println(" registered");
}
//if (!client.connected())client.stop();
while (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
//while (true);
}
// cleanup and get ready for the next card
bitCount = 0;
facilityCode = 0;
cardCode = 0;
for (i = 0; i < MAX_BITS; i++)
{
databits[i] = 0;
}
delay(10);
net();
delay(10);
server.begin();
}
// Create a client connection
EthernetClient nclient = server.available();
if (nclient) {
Serial.println(F("new client"));
while (nclient.connected()) {
if (nclient.available()) {
/* char c = client.read();
Serial.write(c);
//read char by char HTTP request
if (readString1.length() < 100) {
//store characters to string
readString1 += c;
}*/
readString1 = nclient.readStringUntil('\n');
Serial.println(readString1);
//if HTTP request has ended– 0x0D is Carriage Return \n ASCII
// if (c == 0x0D) {
nclient.println("HTTP/1.1 200 OK"); //send new page
nclient.println("Content-Type: text/html");
nclient.println();
nclient.println(F("<HTML>"));
nclient.println(F("<HEAD>"));
nclient.println(F("<TITLE> Wegand to Home Center Configurator</TITLE>"));
nclient.println(F("</HEAD>"));
nclient.println(F("<BODY style=\"background-color:#F0F0FF; text-align: center;\">"));
nclient.println(F("<br>"));
nclient.println(F("<H1 style=\"color:LimeGreen;\">Wegand<span style=\"color:Teal;\">2</span><span style=\"color:Blue;\">HC</span></H1>"));
// client.println(F("<hr>"));
nclient.println(F("<br>"));
//nclient.println(F("<a style=\"color:SteelBlue;background-color:White;padding: 5px;\" href=\"/?TEST\"\">TEST</a><br /><br />"));
nclient.println(F("<form id=\"txt_form\" name=\"frmText\">"));
nclient.println(F("<H2 style=\"color:Crimson;\"><b>Configurator</b></H2>"));
nclient.println(F("<label style=\"color:DodgerBlue;\" for=\"code\">code : <input type=\"password\" id=\"code\" size=\"4\" maxlength=\"4\" value=\"0000\" /></label><br /><br />"));
nclient.println(F("<label style=\"color:DodgerBlue;\" for=\"hcip\">Home Center IP : <input type=\"text\" id=\"hcip\" size=\"15\" minlength=\"15\" maxlength=\"15\" value=\""));
if (ship[0] < 10)
{
nclient.print("00");
}
else if (ship[0] < 100)
{
nclient.print("0");
}
nclient.print(ship[0]);
nclient.print(F("."));
if (ship[1] < 10)
{
nclient.print("00");
}
else if (ship[1] < 100)
{
nclient.print("0");
}
nclient.print(ship[1]);
nclient.print(F("."));
if (ship[2] < 10)
{
nclient.print("00");
}
else if (ship[2] < 100)
{
nclient.print("0");
}
nclient.print(ship[2]);
nclient.print(F("."));
if (ship[3] < 10)
{
nclient.print("00");
}
else if (ship[3] < 100)
{
nclient.print("0");
}
nclient.print(ship[3]);
nclient.println(F("\" required></label><br /><br />"));
nclient.println(F("<label style=\"color:DodgerBlue;\" for=\"sip\">Web Server IP : <input type=\"text\" id=\"sip\" size=\"15\" minlength=\"15\" maxlength=\"15\" value=\""));
if (wsip[0] < 10)
{
nclient.print("00");
}
else if (wsip[0] < 100)
{
nclient.print("0");
}
nclient.print(wsip[0]);
nclient.print(F("."));
if (wsip[1] < 10)
{
nclient.print("00");
}
else if (wsip[1] < 100)
{
nclient.print("0");
}
nclient.print(wsip[1]);
nclient.print(F("."));
if (wsip[2] < 10)
{
nclient.print("00");
}
else if (wsip[2] < 100)
{
nclient.print("0");
}
nclient.print(wsip[2]);
nclient.print(F("."));
if (wsip[3] < 10)
{
nclient.print("00");
}
else if (wsip[3] < 100)
{
nclient.print("0");
}
nclient.print(wsip[3]);
nclient.println(F("\" readonly></label><br /><br />"));
nclient.println(F("<label style=\"color:DodgerBlue;\" for=\"uid\">User ID : <input type=\"text\" id=\"uid\" size=\"2\" maxlength=\"2\" autocomplete=\"on\" value=\"00\" /></label><br /><br />"));
nclient.println(F("<label style=\"color:DodgerBlue;\" for=\"sid\">Scene ID : <input type=\"text\" id=\"sid\" size=\"4\" maxlength=\"4\" autocomplete=\"on\" value=\"0000\" /></label><br /><br />"));
nclient.println(F("<a style=\"color:SteelBlue;background-color:White;padding: 5px;\" href=\"\" onclick=\"this.href='/?'+document.getElementById('code').value+document.getElementById('uid').value+document.getElementById('sid').value+document.getElementById('hcip').value+document.getElementById('sip').value\" >EDIT</a>"));
nclient.println(F("</form>"));
nclient.println(F("</BODY>"));
nclient.println(F("</HTML>"));
delay(10);
//stopping client
nclient.stop();
Serial.println(F("client disconnected"));
if (readString1.indexOf("?1729") == 5 && readString1.indexOf("HTTP/1.1") == 47) //checks code
{
Serial.println(F("pwd match"));
// readString1.toCharArray(url, 25);
Serial.println(readString1);
byte ad = readString1.substring(10, 12).toInt();
Serial.println(ad);
if (ad > 0 && ad < 100) {
scene[ad] = readString1.substring(12, 16).toInt();
Serial.println(scene[ad]);
}
else
Serial.println(F("invalid UID"));
byte p = 16;
for (byte i = 0; i < 4; i++) {
ship[i] = readString1.substring(p, p + 3).toInt();
p = p + 4;
}
p--;
for (byte i = 0; i < 4; i++) {
wsip[i] = readString1.substring(p, p + 3).toInt();
p = p + 4;
}
EEPROM.put(10, ship);
EEPROM.put(15, wsip);
EEPROM.put(20, scene);
delay(1500);
EEPROM.get(10, ship);
EEPROM.get(15, wsip);
EEPROM.get(20, scene);
//digitalWrite(5, HIGH);
//delay(1500);
//digitalWrite(5, LOW);
Serial.println(F("Edited"));
}
//clearing string for next read
readString1 = "";
// }
}
}
}
switch (Ethernet.maintain())
{
case 1:
//renewed fail
Serial.println(F("Error: renewed fail"));
break;
case 2:
//renewed success
Serial.println(F("Renewed success"));
//print your local IP address:
Serial.print(F("server is at "));
Serial.println(Ethernet.localIP());
break;
case 3:
//rebind fail
Serial.println(F("Error: rebind fail"));
break;
case 4:
//rebind success
Serial.println(F("Rebind success"));
//print your local IP address:
Serial.print(F("server is at "));
Serial.println(Ethernet.localIP());
break;
default:
//nothing happened
break;
}
}
void printBits()
{
// I really hope you can figure out what this function does
Serial.println();
Serial.print("FC = ");
Serial.print(facilityCode);
Serial.print(", CC = ");
Serial.println(cardCode);
}
void net()
{
if (Ethernet.begin(mac) == 0) {
Serial.println(F("Failed to configure Ethernet using DHCP"));
// if (Ethernet.hardwareStatus() == EthernetNoHardware) {
// Serial.println(F("Ethernet shield was not found. Sorry, can't run without hardware. :("));
// } else if (Ethernet.linkStatus() == LinkOFF) {
// Serial.println(F("Ethernet cable is not connected."));
// } else {
// Serial.println(F("No idea why"));
// }
delay(3000);
Ethernet.begin(mac, ip);
if (Ethernet.localIP() != ip)
{
Serial.println(F("Failed to configure Ethernet using static IP"));
for (;;)
;
}
}
Serial.print(F("server is at "));
Serial.println(Ethernet.localIP());
ip = Ethernet.localIP();
for (byte i = 0; i < 4; i++) {
wsip[i] = ip[i];
}
EEPROM.put(15, wsip);
}
void auth(IPAddress sh)
{
Serial.println(sh);
client.print("Host: ");
client.println(sh);
client.println("Authorization: Basic YmVuc2U6Qmlnc"); //need to insert base 64 user:password
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);
}
I use Ethernet shield (W5100) and RC522 on my Arduino Uno. It works 1 or 2 hours (sometimes 15 minutes - sometimes 2 days) After this random time, it stops working. I mean stop with, RC-522 module don't read cards, and ethernet shield can't connect server. When i unplug power (1.5A - 12 V power suply) and re-plug it, it starts working successfully.
I need to this system works forever... This system reads mifare card, and sends to the server, after that it checks reply, and if the reply is "1", it triggers relay. (relay is 5V simple relay)
Some people said "Change your adaptor", and i changed it, nothing changed.
Some people said " use 10 microfarad capasitor between rst and gnd pin" and nothing changed.
and some people said, "this is arduino dude, it is for just studend give up and use stm32", and i didn't apply this suggestion yet. I want to know why this happens.
#include <SPI.h>
#include <Ethernet.h>
#include <MFRC522.h>
//Mac address of ethernet shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEA };
//My Network info, i use static ip
byte ip[] = { 172, 16, 64, 78 };
byte gateway[] = { 172, 16, 64, 1 };
byte myserver[] = { 172, 16, 64, 46 };
byte subnet[] = { 255, 255, 255, 0 };
String CardInfo = "";
EthernetClient client;
String GateNo = "0";
String DeviceNo = "100";
String Answer = "";
MFRC522 mfrc522;
byte Key[] = { 0xff,0xff,0xff,0xff,0xff,0xff };
MFRC522::MIFARE_Key key;
void setup(){
//Disabling SD Card
pinMode(4,OUTPUT);
digitalWrite(4,HIGH);
Ethernet.begin(mac, ip, subnet, gateway);
KeyCreate();
mfrc522.PCD_Init(2, 8);
mfrc522.PCD_DumpVersionToSerial();
}
void sendGET()
{
//I used this line to guarantee the disconnect from server
client.stop();
Answer = "";
if (client.connect(myserver, 81)) {
client.println("GET /AccessCheck/CardNo=" + CardInfo + "&GateNo=" + GateNo + "&DeviceNo=" + DeviceNo + " HTTP/1.0");
client.println("Authorization: Basic xxxxxxxxxxxx");
client.println();
}
else {
//Ethernet.begin(mac, ip, subnet, gateway);
return;
}
int connectLoop = 0;
while(client.connected())
{
while(client.available())
{
char c = client.read();
Answer = Answer + c;
connectLoop = 0;
}
delay(1);
connectLoop++;
if(connectLoop > 5000)
{
client.stop();
return;
}
}
client.stop();
}
//This function disables eth and enable rc522 (and reverse)
void Switch(int i)
{
switch (i)
{
case 0:
digitalWrite(10, HIGH);
digitalWrite(2, LOW);
break;
case 1:
digitalWrite(2, HIGH);
digitalWrite(10, LOW);
break;
}
}
void AccessControl()
{
int AnswerLength = Answer.length();
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);
if(Answer[AnswerLength-1] == 49)
{
digitalWrite(5, LOW);
delay(100);
digitalWrite(5, HIGH);
}
pinMode(5, INPUT);
pinMode(6, INPUT);
delay(1000);
}
void ReadCard()
{
byte len = 18;
MFRC522::StatusCode status;
byte MyBuffer[18];
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 10, &key, &(mfrc522.uid));
status = mfrc522.MIFARE_Read(10, MyBuffer, &len);
int counter = 0;
//This line is check for turkish character
if(MyBuffer[0] == 221)
{
CardInfo = "X";
for (int i = 1; i < 16; i++)
{
if (MyBuffer[i] != 32)
{
CardInfo = CardInfo + (char)MyBuffer[i];
}
}
}
else
{
CardInfo = "";
for (int i = 0; i < 16; i++)
{
if (MyBuffer[i] != 32)
{
CardInfo = CardInfo + (char)MyBuffer[i];
}
}
}
mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
return;
}
void KeyCreate()
{
for (int i = 0; i < 6; i++)
{
key.keyByte[i] = Key[i];
}
}
void loop(){
Switch(0);
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
ReadCard();
Switch(1);
sendGET();
AccessControl();
}
}
I expect it runs without freezing
Actual result is ethernet shield freezes after a while
I am using watchdog in some script . This functionality could reset auomatically your arduino if you dont reset the watchdog during the lapse.
you execute wdt_enable() in the setup() and wd_reset() at the beginning of the loop
time before watchdog firing argument of wdt_enable()
-------------------------------------------------------
15mS WDTO_15MS
30mS WDTO_30MS
60mS WDTO_60MS
120mS WDTO_120MS
250mS WDTO_250MS
500mS WDTO_500MS
1S WDTO_1S
2S WDTO_2S
4S WDTO_4S
8S WDTO_8S
example of use:
#include <avr/wdt.h>
void setup()
{
wdt_enable(WDTO_4S); // enable the watchdog
// will fire after 4s without reset
}
void loop(){
wdt_reset(); // resets the watchdog timer count
:
:
// if program hangs more than 4s, launch the reset of arduino
}
I'm writing a code for extraction of peer credential by the server process connected through ipc using domain sockets to the client process. There is no error in the code but while running it I don't get the euid and gid of the peer process.
Code for server process is:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
//#include<ucred.h>
#define SCM_CREDENTIALS
# define UNIX_PATH_MAX 100
int getpeereid(int connection_fd,uid_t euid,gid_t gid)
{
struct ucred cred;
socklen_t len = sizeof(cred);
if (getsockopt(connection_fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) < 0)
return (-1);
euid =cred.uid;
gid = cred.gid;
//int passcred=1;
//setsockopt(connection_fd,SOL_SOCKET,SO_PASSCRED,(void *)&passcred,sizeof(passcred));
printf("effective user id", euid);
printf("effective group id",gid);
return 0;
}
int connection_handler(int connection_fd)
{
int nbytes;
char buffer[1024];
char msg[256];
//while(cont=recv(connection_fd,buffer,sizeof(buffer),0)>0)
//{
//write(1,buffer,cont)
nbytes = read(connection_fd, buffer, 256);
buffer[nbytes] = 0;
printf("MESSAGE FROM CLIENT: %s\n", buffer);
printf("enter the message");
scanf("%s",msg);
nbytes = snprintf(buffer, 256,msg);
write(connection_fd, buffer, nbytes);
//}
close(connection_fd);
return 0;
}
int main(void)
{
struct sockaddr_un address;
int socket_fd, connection_fd,res;
socklen_t address_length;
pid_t child;
uid_t eid;
gid_t gid;
socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(socket_fd < 0)
{
printf("socket() failed\n");
return 1;
}
printf("socket created\n");
unlink("./demo_socket");
/* start with a clean address structure */
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path, UNIX_PATH_MAX, "./demo_socket");
if(bind(socket_fd,
(struct sockaddr *) &address,
sizeof(struct sockaddr_un)) != 0)
{
printf("bind() failed\n");
return 1;
}
if(listen(socket_fd, 5) != 0)
{
printf("listen() failed\n");
return 1;
}
while((connection_fd = accept(socket_fd,
(struct sockaddr *) &address,
&address_length)) > -1)
{
// get the credentials
res=getpeereid(connection_fd,geteuid(),getgid());
if (res==0)
{
//if(res==0)
//{
child = fork();
if(child == 0)
{
/* now inside newly created connection handling process */
return connection_handler(connection_fd);
}
}
/* still inside server process */
close(connection_fd);
//}
}
close(socket_fd);
unlink("./demo_socket");
return 0;
}
the code for client
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>
#define UNIX_PATH_MAX 100
int connection_handler(int socket_fd)
{
int nbytes;
char buffer[1024];
char mesg[256];
printf("enter the message");
scanf("%s",mesg);
//printf("message is %s",mesg);
nbytes = snprintf(buffer, 256,mesg);
//fgets(buffer,256,mesg);
//i=atoi(mesg);
write(socket_fd,buffer,nbytes);
//send(socket_fd,mesg,sizeof(mesg),0);
}
//nbytes = read(socket_fd, buffer, 256);
//buffer[nbytes] = 0;
//printf("MESSAGE FROM SERVER: %s\n", buffer);
//}
int main(void)
{
struct sockaddr_un address;
int socket_fd, nbytes,i;
pid_t child;
char buffer[256];
//char mesg[100];
socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(socket_fd < 0)
{
printf("socket() failed\n");
return 1;
}
printf("socket created\n");
/* start with a clean address structure */
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path, UNIX_PATH_MAX, "./demo_socket");
if(connect(socket_fd,
(struct sockaddr *) &address,
sizeof(struct sockaddr_un)) != 0)
{
printf("connect() failed\n");
return 1;
}
child=fork();
while(child==0)
{
return connection_handler(socket_fd);
//printf("connection established\n");
//printf("enter the message");
//scanf("%s",mesg);
//printf("message is %s",mesg);
//bytes = snprintf(buffer, 256,mesg);
//fgets(buffer,256,mesg);
//i=atoi(mesg);
//write(socket_fd,buffer,nbytes);
//send(socket_fd,mesg,sizeof(mesg),0);
}
nbytes = read(socket_fd, buffer, 256);
buffer[nbytes] = 0;
printf("MESSAGE FROM SERVER: %s\n", buffer);
close(socket_fd);
return 0;
}
See http://www.thomasstover.com/uds.html for good overview.
If the server is Linux, the main problem is missing _GNU_SOURCE. Full patch below, it has a few minor changes just to get rid of gcc -Wall -Werror -pedantic -std=c99 errors and warnings.
--- server.c.orig 2014-12-06 13:23:09.138472871 +0200
+++ server.c 2014-12-06 13:21:31.962475754 +0200
## -1,3 +1,4 ##
+#define _GNU_SOURCE
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
## -5,7 +6,6 ##
#include <unistd.h>
#include <string.h>
//#include<ucred.h>
-#define SCM_CREDENTIALS
# define UNIX_PATH_MAX 100
int getpeereid(int connection_fd,uid_t euid,gid_t gid)
## -20,8 +20,8 ##
//int passcred=1;
//setsockopt(connection_fd,SOL_SOCKET,SO_PASSCRED,(void *)&passcred,sizeof(passcred));
-printf("effective user id", euid);
-printf("effective group id",gid);
+printf("effective user id %d", euid);
+printf("effective group id %d",gid);
return 0;
}
## -40,7 +40,7 ##
printf("MESSAGE FROM CLIENT: %s\n", buffer);
printf("enter the message");
scanf("%s",msg);
-nbytes = snprintf(buffer, 256,msg);
+nbytes = snprintf(buffer, 256, "%s", msg);
write(connection_fd, buffer, nbytes);
//}
close(connection_fd);
## -54,8 +54,6 ##
int socket_fd, connection_fd,res;
socklen_t address_length;
pid_t child;
-uid_t eid;
-gid_t gid;
socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(socket_fd < 0)
I want get json from my website. I am trying send POST request for authentication and after it i want to send GET request for getting json, but i can't do it, because it gives me en error 401 unauthorized (cookies doesn't saved) . How can i keep session with Arduino ,ethernet shield and WebClien?
Source:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
//Change to your server domain
char serverName[] = "bh.quickle.me";
// change to your server's port
int serverPort = 80;
// change to the page on that server
char pageName[] = "/users/sign_in";
char sensorPage[] = "/api/v1/sensors";
EthernetClient client;
int totalCount = 0;
// insure params is big enough to hold your variables
char params[68];
// set this to the number of milliseconds delay
// this is 30 seconds
#define delayMillis 30000UL
unsigned long thisMillis = 0;
unsigned long lastMillis = 0;
void setup() {
Serial.begin(9600);
// disable SD SPI
pinMode(4,OUTPUT);
digitalWrite(4,HIGH);
pinMode(7,OUTPUT);
digitalWrite(7,HIGH);
Serial.print(F("Starting ethernet..."));
if(!Ethernet.begin(mac)) Serial.println(F("failed"));
else Serial.println(Ethernet.localIP());
delay(2000);
Serial.println(F("Ready"));
sprintf(params,"{\"user\": {\"email\": \"EgorkZe#gmail.com\",\"password\": \"1234asdf\"}}");
postPage(serverName,serverPort,pageName,params);
}
void loop()
{
thisMillis = millis();
if(thisMillis - lastMillis > delayMillis)
{
lastMillis = thisMillis;
getPage(serverName, serverPort, sensorPage);
}
}
byte postPage(char* domainBuffer,int thisPort,char* page,char* thisData)
{
int inChar;
char outBuf[64];
Serial.print(F("connecting..."));
if(client.connect(domainBuffer,thisPort))
{
Serial.println(F("connected"));
// send the header
sprintf(outBuf,"POST %s HTTP/1.1",page);
client.println(outBuf);
sprintf(outBuf,"Host: %s",domainBuffer);
client.println(outBuf);
client.println(F("Connection: close\r\nContent-Type: application/json"));
sprintf(outBuf,"Content-Length: %u\r\n",strlen(thisData));
client.println(outBuf);
// send the body (variables)
client.print(thisData);
}
else
{
Serial.println(F("failed"));
return 0;
}
int connectLoop = 0;
while(client.connected())
{
while(client.available())
{
inChar = client.read();
Serial.write(inChar);
connectLoop = 0;
}
delay(1);
connectLoop++;
if(connectLoop > 10000)
{
Serial.println();
Serial.println(F("Timeout"));
client.stop();
}
}
Serial.println();
Serial.println(F("disconnecting."));
client.stop();
return 1;
}
byte getPage(char* domainBuffer, int thisPort, char* page)
{
int inChar;
char outBuf[128];
Serial.print(F("connecting..."));
if(client.connect(domainBuffer,thisPort))
{
Serial.println(F("connected"));
sprintf(outBuf,"GET %s HTTP/1.1",page);
client.println(outBuf);
sprintf(outBuf,"Host: %s",serverName);
client.println(outBuf);
client.println(F("Connection: close\r\n"));
}
else
{
Serial.println(F("failed"));
return 0;
}
// connectLoop controls the hardware fail timeout
int connectLoop = 0;
while(client.connected())
{
while(client.available())
{
inChar = client.read();
Serial.write(inChar);
// set connectLoop to zero if a packet arrives
connectLoop = 0;
}
connectLoop++;
// if more than 10000 milliseconds since the last packet
if(connectLoop > 10000)
{
// then close the connection from this end.
Serial.println();
Serial.println(F("Timeout"));
client.stop();
}
// this is a delay for the connectLoop timing
delay(1);
}
Serial.println();
Serial.println(F("disconnecting."));
// close client end
client.stop();
return 1;
}
To begin, yes, the Arduino Ethernet is capable to store and send back cookies.
You have to catch the cookies from the authentication request and send them back in the header of the second HTTP request (the GET one).
Have a look at informations about RFC HTTP Protocol
You can also look at :
http://en.wikipedia.org/wiki/HTTP_cookie#Setting_a_cookie