Showing posts with label Theory. Show all posts
Showing posts with label Theory. Show all posts

Tuesday, January 19, 2010

What an idea!

Yesterday i talked with an old friends! He helped me about finding a way to code "something". He is damn formal and accademic (and effective developers too), and i was so suprised on how two minds can works in sync.
So we started to chill around a lil project, which maybe we are gonna to develop...
The main was about "how to define an algorhythm as an XML documents". I guess we found a (maybe one of tons) solution an it is possible in the next days im gonna posting something more. It will be about BNF about a "certain" arguments, which will be translate as a XML-Scheme.
That scheme will be the data structure to work and interact with a web-based tool..
Nothing more, stay tuned..

Tuesday, November 3, 2009

Bluetooth Device Discovery in c language HOW TO

Today i wanna show a simple how to about bluetooth programming.
I will start witha brief theory follow by a full commented c source compile under linux.

This two functions convert a string address in a bdaddr_t (a defined structure which is a bluetooth device address) and viceversa
str2ba (const char * str , bdaddr_t * ba)
ba2str (const bdaddr_t * ba , char * str)
We also need to know about local bluetooth adapter, this functions will be useful:
int hci_get_route (bdaddr_t * addr)
Return the device id of the given bdaddr_t, you can pass NULL so it returns the first available device.
If you know the device's address you want to use you can pass it to this function
int hci_devid (const char * addr)
finally you can open resources to use the device you choose with
int hci_open_dev (int adapter_id)
Now you need to send an inquiry signal to receive information about the devices to respond.
You can do this by calling
int hci_inquiry (int adapter_id, int len, int max_rsp,
 const uint8_t * lap , inquiry_info ** devs , long flags
)
  • adapter_id = the adapter you choose before
  • len = inquiry time, the standard is about 8 * 1.24 (so len = 8)
  • max_rsp = maximum devices response (usually 255)
  • flags = usually IREQ CACHE FLUSH, if you pass 0 then previous inquiry info may be returned
  • lap = determine the type of inquiry, if you don't care give it NULL.
Be careful: devs parameter should be sized enough to store a max of max_rsp inquiry_info struct...
Sounds like:
(inquiry_info *)malloc (max_rsp * sizeof (inquiry_info));
And finally you can get devices friendly name, follow this how-to
  1. cycle hci_inquiry return step to check for the devices found
  2. look for bdaddr_t field in the devices list stored by hci_inquiry, converted by ba2str
  3. store enough memory to convert string address to string name
  4. get the name with:
    int hci_read_remote_name (int hci_sock, const bdaddr_t * addr,
     int len, char * name, int timeout)

And here the code:
/**
 * bdd_main.c
 *
 * This is a sample about how to discovery bluetooth device
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>

int main (int argc, char ** argv)
{
 inquiry_info * devices = NULL; // This struct will store the found devices
 int max_rsp, num_rsp; // max devices to find, devices found
 int adapter_id, sock, len, flags; // use to hci_inquiry and hci_open_dev, returned by hci_open_dev, 1.24 * len sec inquiry time, flags chache or flush
 int i;
 char addr[19] = { 0 }; // this is a middle to find out friendly name
 char name[248] = { 0 }; // this is to store friendly name

 /* OPEN A LOCAL BLUETOOTH ADAPTER */
 adapter_id = hci_get_route(NULL);
 sock = hci_open_dev(adapter_id);
 if(adapter_id < 0 || sock < 0)
 {
  fprintf(stderr, "Error code %d: %s\n", errno, strerror(errno));
  exit(1);
 }

 /* INQURY PROCESS */
 len = 8; // 10.24 sec lasts
 max_rsp = 255; // max of 255 devices to discover
 flags = IREQ_CACHE_FLUSH; // no use previous inquiry data
 devices = (inquiry_info *)malloc(max_rsp * sizeof(inquiry_info)); // malloc for devices

 num_rsp = hci_inquiry(adapter_id, len, max_rsp, NULL, &devices, flags); // inquiry
 if(num_rsp < 0)
 {
  fprintf(stderr, "Error code %d: %s\n", errno, strerror(errno));
  exit(1);
 }

 /* FRIENDLY NAME */
 for(i = 0; i < num_rsp; i++)
 {
  ba2str(&(devices+i)->bdaddr, addr); // convert bdaddr to a string
  memset(name, 0, sizeof(name)); // memset to store friendly name
  if(0 != hci_read_remote_name(sock, &(devices+i)->bdaddr, sizeof(name), name, 0)) // store in name the first sizeof(name) byte of the friendly name of the given addr.
  {
   // this mean the friendly name was not found
   strcpy(name, "[unknow]");
  }

  printf("%s %s\n", addr, name);
 }

 /* ENDING ROUTINES */
 free(devices);
 close(sock);

 return 0;
}

Do not forget to compile linking bluetooth lib XP...

Tuesday, October 13, 2009

c Kernighan & Ritchie exercise

Lately im into c programming, really newbie, so im reading Kernighan & Ritchie famous book.
Here a funny exercise that reverse an input line string:

"Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time."

i change the params as you can see..


#include <stdio.h>

#define MAXLEN 30

int getline(char s[], int lim);
void reverse(char s[], char r[], int len);

int main()
{
int len;
char line[MAXLEN];
char reversed[MAXLEN];

len = 0;

while((len = getline(line, MAXLEN)) > 0)
{
reverse(line, reversed, len);
printf("\nReversed = %s\n\n", reversed);
}

return 0;
}

int getline(char s[],int lim)
{
int c, i;
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}

void reverse(char s[], char r[], int len)
{
int i;

for(i = 0; i < len; i++)
r[i] = 0;

for(i = 0; i < len; i++)
{
/* -2 will strip \n in the original string (-1 the original end of string */
r[i] = s[len-i-2];
}
r[len] = '\0';
}

Tuesday, September 1, 2009

PHP RESTful WebService

Lately im working on a restful php webservice.
In its concepts RESTful is quite easy, but it is still not really understand by most of web programmers.

So if you are interested, first of all you should start to study what behind REST, so its architecture. Good resources are of course wikipedia and Roy Thomas Fielding's dissertation which start the most of works.

Then you may try to develop, or study already coded RESTful web service, the most comes from ruby and python programming languages. Im quite sure to be blind, but in the end i really didn't find goods PHP resources about RESTful (genuine RESTful i mean!) from surfing the web.

The really best i found is an article signed by Gareth Jones: Building a RESTful Web application with PHP and it's starting point lornajane.

A really good book (which i found such likes a REST bible) is RESTful Web Service, written by Leonard Richardson and Sam Ruby.

I know it's a lot of things, this is the RESTful price to pay!

But it's good, trust me people!

Tuesday, January 13, 2009

Backus-Naur Form

Backus-Naur form, is a way to describe grammar for programming languages, communication protocols, instruction set and to represent part of natural language too. It express free context grammar.
A BNF consist of a set of derivation rules, made of symbols. Every Symbol is expressed as a rule like:
<symbol> ::= expression
an expression could be another symbol or a choice of symbols separated by a vertical bar. On the right side a symbol could be a terminal symbol or a non-terminal symbol. A terminal symbol is a symbol which never appears on the left side. When you find a non-terminal symbol on the right side you have to exchange it with its expression, at the end of the chain you are going to find a terminal symbol you can use :).
Starting from the first definition to the terminals symbol definition you could "write" everything could be expressed by that BNF.

See also:
BNF on wiki
PHP source [you can find the EBNF in the source]

In the next post im going to tell you how i write an xsd (XML Scheme) about XML syntax in order to transform it into graph by a XSLT.
Enjoy!

UPDATE:
At the begin, the acronym BNF meant Backus Normal Form, but later decided to use Naur instead of Normal in honour of Peter Naur a member of the Algol committee.
The most "popular" variant of BNF is absolutely EBNF (Extended Backus Naur Form which introduce optional repeatable (group) of symbols.

UPDATE:
Some examples in order to understand how BNF works.

In italian language, the structure of an affermative sentence in simple present sounds (also) like:
Subject + verbs + subject
We define subject as: Article + noun
In english sounds the same, so a sentence in that way could be: "The child eats candies".
Well, let's try to derive a BNF that express that simple rule

<Affermative Sentence> ::= <Subject> <Verbs> <Subject>
<Verbs> ::= 'all the simple present verb these are all terminal symbols!'
<Subect> ::= <Article> <Nouns>
<Article> ::= The | A | An
<Nouns> ::= 'all the nouns, these are all terminal symbols!'

If you start from the root <Affermative Sentence> and substitute element's with it's definition, in the end you should get an affermative simple present sentence. Of course, we should extend the definition in order to explain when to use "The" instead of "A" or "An", but this BNF is just to let you understand how it works.
Here you can find EBNF definition on wiki, it's a very good entry, so check it out!

An other more complex example:
Now we are going to discover the power of BNF syntax. We want to write rules for a string which built a SQL insert query. A query for a link table:
Table 1 -> link table <- Table 2 (N:N)
This will be the form:
List of comma separated ids ended by ';'; every list are follow by an id and ':'. The ids before ':' comes from table 1, the comma separated id from table 2
Strings like:
1:3,4,5;33:2,31,13;4:77;
OR
245:23;
And so on.

<Query Block> ::= <Table id> <Table Separator> [<Single Table List>] <Closer Table List> | <Query Block>
<Single Table List> ::= <Table id> <Separator> | <Single Table List>
<Closer Table List> ::= <Table id> <Closer>
<Table id> ::= <Digit> | <Table id>
<Digit> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0'
<Table Separator> ::= ':'
<Separator> ::= ','
<Closer> ::= ';'

sentence inside square brakets mean the sentence is optional!
In the next day im going to post another example.
Have a nice Day!

Tuesday, October 7, 2008

Rectangles

Objective: A function allow to draw a rectangle, so we want to supply top-left corner coordinates, width and height. These variables must be retrive by click-drag-relase mouse.

The most easy way consists by click and drag the mouse in bottom-right direction. Retrive the 4 variables will be easy as follow:

  • x coordinate: first mouse click x coordinate;
  • y coordinate: first mouse click y coordinate;
  • width: mouse relase - x coordinate;
  • height: mouse relase - y coordinate.

Well these easy calculations doesn't work in the follow other instances:

  1. Mouse direction is to top-right (negative height);
  2. Mouse direction is top-left (both widht and height negatives);
  3. Mouse direction is bottom-left (width negative).

It is easy to get real width and height, we only need to take measurements as absolute value; find out the top-left corner coordinates too.

If a size is less then zero, it means that its coordinate will be the same as the mouse coordinate at the relase point.



width = mouse_end_x - mouse_start_x
height = mouse_end_y - mouse_start_y
IF ( width < 0 ) THEN rect_x = mouse_end_x ELSE rect_x = mouse_start_x
IF ( height < 0 ) THEN rect_y = mouse_end_y ELSE rect_y = mouse_start_y
rectangle ( rect_x, rect_y, |width|, |height| )