Skip to content

Instantly share code, notes, and snippets.

@iomz
Created April 16, 2013 05:57
Show Gist options
  • Save iomz/5393685 to your computer and use it in GitHub Desktop.
Save iomz/5393685 to your computer and use it in GitHub Desktop.
Read card ID (IDm) by Pasori reader and send it by socket communication
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "config.h"
#include "libpafe.h"
#define RAW_ID_SIZE 8
#define ID_SIZE RAW_ID_SIZE*2
void error(const char *msg)
{
perror(msg);
exit(0);
}
char * mydump(uint8 * p)
{
int i;
char * id = (char *)malloc(ID_SIZE*sizeof(char));
for (i = 0; i != RAW_ID_SIZE; i++) {
sprintf(id+i*2,"%02X", p[i]);
}
return id;
}
int main(int argc, char ** argv)
{
pasori * p;
char * last_id = (char *)malloc(ID_SIZE*sizeof(char));
char * current_id, * man_id;
p = pasori_open();
if (!p) {
printf("error\n");
exit(-1);
}
/* Socket section */
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
if (argc < 3) {
fprintf(stderr,"Usage: %s hostname port\n", argv[0]);
exit(0);
}
/* Socket section end */
for(;;) {
felica * f;
pasori_init(p);
f = felica_polling(p, FELICA_POLLING_ANY, 0, 0);
if (!f) continue;
current_id = (char *)mydump(f->IDm);
man_id = (char *)mydump(f->PMm);
// Iff haven't read this, sleep 1 sec
if(strncmp(last_id, current_id, ID_SIZE)!=0) sleep(1);
// printf("%s: %s\n\a", current_id, man_id);
printf("%s\n", current_id);
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
fprintf(stderr,"ERROR connecting, retrying in 2 seconds...\n");
sleep(2);
continue;
}
n = write(sockfd,current_id,strlen(current_id));
if (n < 0) error("ERROR writing to socket");
strcpy(last_id, current_id);
close(sockfd);
free(f);
sleep(5);
}
pasori_close(p);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment