47
FLYPORT GPRS Programmer's Guide Framework version 2.3 release 1.0

Flyport GPRS programmer's guide 2.3 rev1.0

Embed Size (px)

DESCRIPTION

Programmer's guide for Flyport GPRS module). More info and tutorials on wiki.openpicus.com

Citation preview

Page 1: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's Guide

Framework version 2.3release 1.0

Page 2: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

[this page has intentionally been left blank]

2

Page 3: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

ContentsFlyport GPRS.........................................................................................................................................5

Introduction.....................................................................................................................................5Bootloader ......................................................................................................................................6Pinout...............................................................................................................................................7

Hardware functions..............................................................................................................................9Digital Inputs and Outputs...............................................................................................................9

Digital I/Os Functions................................................................................................................10Remappable Pins...........................................................................................................................13

Remappable Pins Functions......................................................................................................14Analog Inputs.................................................................................................................................15

Analog Inputs Functions............................................................................................................16PWM..............................................................................................................................................17

PWM function...........................................................................................................................18Serial Communication (UART)........................................................................................................20

UART Functions.........................................................................................................................21I2C Communication Protocol.........................................................................................................23

I2C Basic Functions....................................................................................................................23Accessing memory registers of slave devices...........................................................................24

RTCC module..................................................................................................................................26RTCC APIs...................................................................................................................................26

GSM Task ............................................................................................................................................28Standard Mode..............................................................................................................................28

GSM APIs work-flow..................................................................................................................28GSM Events...............................................................................................................................31

Network Connection and GSM info...............................................................................................32Manage GSM network connection...........................................................................................32Read GSM Module IMEI............................................................................................................32Code Example............................................................................................................................33

Voice Call........................................................................................................................................33CALL APIs...................................................................................................................................34

SMS................................................................................................................................................34Introduction..............................................................................................................................34SMS APIs....................................................................................................................................35

Internal Flash File System..............................................................................................................35Features.....................................................................................................................................36File System APIs.........................................................................................................................36

Data Connections...........................................................................................................................37APN Configuration.....................................................................................................................37

Email - SMTP..................................................................................................................................37SMTP APIs..................................................................................................................................37

3

Page 4: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

SMTP Error Codes.....................................................................................................................38TCP Client.......................................................................................................................................39

TCP Socket.................................................................................................................................40TCP APIs.....................................................................................................................................40

HTTP Client.....................................................................................................................................41HTTP APIs..................................................................................................................................41

FTP Client.......................................................................................................................................42FTP Socket.................................................................................................................................43FTP APIs.....................................................................................................................................43

Power Saving..................................................................................................................................44Hibernate Mode........................................................................................................................44Sleep Mode...............................................................................................................................45

Low Level Mode.............................................................................................................................45Low Level Mode APIs................................................................................................................46

4

Page 5: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

Flyport GPRS

Introduction

Flyport is a programmable system-on-module embedding a Microchip PIC24FJ256 microcontroller and a GPRS transceiver. It has two 26 pin connector to communicate with external electronics and can be powered with 3.3 or 5V.

The microcontrollers runs the openPicus framework (based on FreeRTOS) that embeds the GPRS stack and the customer application developed using our free IDE.

Flyport can be programmed with user-written firmware to accomplish actions like controlling relays, reading digital and analog IOs, communicating with a UART, I2C or SPI buses, and so on.

The PIC24FJ256 is a 16 bit, 16 MIPS microcontroller with 256 KB flash memory and 16 KB of RAM.

Flyport offers several generic GSM services such as a SMS and voice Call and also data connection with HTML client, SMTP client to send email, TCP client, FTP client.

Each Flyport comes with a serial bootloader onboard, so no need for expansive programmers (a low cost miniUSB programmer is available and compatible with Nest expansion boards for Flyport).

5

Page 6: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Bootloader

Each Flyport module has a serial bootloader preloaded onboard.

QUESTION: What is a serial bootloader and why is it needed on an embedded device like Flyport?

To download a firmware to a microcontroller is usually needed a specific programmer. This is an external device which writes new firmware into the flash memory of the microcontroller and controls the boot and the reset of the device. The programmer is connected to the PC.

To save on this device Flyport has an internal serial bootloader to program the microcontroller using just a serial connection, for example our low cost miniUSB Programmer.

The bootloader is a small program that starts when the microcontroller boots and listens on the serial port for a special message. When it receives this special message (usually a string) it “understand” that the IDE wants to program the micro, so it reads the commands arriving on the serial port and writes them to the microcontroller memory using an RTSP – real time serial programming - technique.

QUESTION: The bootloader is located inside the program memory, and it writes inside the program memory. Can this be dangerous? What happens if the bootloader tries to “overwrite itself”?!

If the PC sends any instruction to write to a “dangerous” memory address, the bootloader stops writing, avoiding “killing” itself. The IDE gives feedback to the user, saying “the code can damage the bootloader, so it has not been written”.

QUESTION: The bootloader is another program resident inside the microcontroller. Will it slow down the micro? Will it reduce the available memory for the user firmware?

The bootloader runs for a short time only at the startup of the Flyport, so it doesn't slow Flyport down in any way. It uses just 1k of memory. So there is no real reduction of the available memory for your application.

NOTE: Flyport uses a customized version of the ds30 bootloader. An opensource and lightweight bootloader for PIC microcontrollers http://mrmackey.no-ip.org/elektronik/ds30loader/

6

Page 7: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

Pinout

JP1 (connector male 2*13 ways pitch 2.54mm pinheader: SAMTEC TSM-113-01-F-DV )

Pin Pin Name Description (default setting) 5V Tolerant Remappable

1 p1 GPIO (I2C bus - clock) Yes No

2 p2 GPIO (Digital Input) Yes Yes

3 p3 GPIO (I2C bus - data) Yes No

4 p4 GPIO (Digital Output) Yes Yes

5 p5 GPIO (Digital Input) Yes Yes

6 p6 GPIO (Digital Output) Yes Yes

7 p7 GPIO (Digital Input) Yes No

8 p8 GPIO (SPI bus – clock SCLK) Yes Yes

9 p9 GPIO (Digital Input) Yes Yes

10 p10 GPIO (SPI bus – output SDO) Yes Yes

11 p11 GPIO (Digital Input) Yes Yes

12 p12 GPIO (SPI bus – input SDI) Yes Yes

13 p13 UART RX input Yes Yes

14 p14 GPIO (SPI bus – chip select CS) Yes Yes

15 p15 UART TX output Yes Yes

16 p16 +5V POWER SUPPLY note 1 - -

17 p17 GPIO (Digital Output) No Yes

18 p18 ANALOG INPUT #4 note 2 No Yes

19 p19 GPIO (Digital Output) → Led OUT4 No Yes

20 p20 ANALOG INPUT #3 note 2 No Yes

21 p21 GPIO (Digital Output) → Led OUT5 No No

22 p22 GND GROUND - -

23 p23 ANALOG INPUT #1 note 2 No Yes

24 p24 +3,3V POWER SUPPLY note 1 - -

25 p25 ANALOG INPUT #2 note 2 No Yes

26 p26 RESET (active low) No No

7

Page 8: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

JP2 (connector male 2*13 ways pitch 2.54mm pinheader: SAMTEC TSM-113-01-F-DV )

Pin Pin Name Description (default setting) 5V Tolerant Remappable

1 p27 GPIO (Digital Input) No No

2 p28 GPIO (Digital Input) No No

3 p29 GPIO (Digital Input) No No

4 p30 GPIO (Digital Input) No No

5 p31 GPIO (Digital Input) No No

6 p32 GPIO (Digital Input) No No

7 p33 GPIO (Digital Input) No No

8 p34 GPIO (Digital Input) No No

9 - - -

10 - - -

11 - - -

12 - - -

13 - - -

14 - Headphone Output P - -

15 - Microphone Input - -

16 - Headphone Output P - -

17 - - -

18 - - -

19 - - -

20 - - -

21 - - -

22 - - -

23 - - -

24 - - -

25 - - -

26 - - -NOTE 1. Flyport can be powered at 5V or at 3,3V. If powered on pin 16 then the pin 24 is the output of the internal LDO. If powered at 3,3V on pin 24 then leave pin 16 not connected.NOTE 2. Flyport has a precise 2,048V voltage reference onboard for the internal 10 bits ADC. So this is the maximum value you can apply on Analog Input pins.NOTE 3. Pin 16,18,20,22,24,26 are directly compatible with the Microchip PICKIT connector.

8

Page 9: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

Hardware functionsThis chapter shows how to control the hardware of Flyport: the digital IOs, the analog inputs, how to create PWM and how communicate with other devices or peripherals.

QUESTION: Usually to control the hardware of an embedded device it is required to know specific registers and how change them. Is this true also for Flyport?

No, the openPicus Framework gives you a set of instructions to control the hardware of the Flyport without any knowledge about microcontroller hardware registers.

Digital Inputs and Outputs

Flyport provides lot of Digital Input/output pins to control devices such as Led, Relay, buttons and more.

Voltage level: The microcontroller works at 3.3V so digital pins are working at 3.3V level.

5V tolerant inputs: some input pins are 5V tolerant, check on the pinout table before connecting!

QUESTION: How are Flyport’s pins named?

When you are writing your application you can refer to the Flyport pin directly: pn, where n is a number that refers to the corresponding pin number on the Flyport connector.

Example:

#include "taskFlyport.h"

void FlyportTask()

{

IOInit(p5,out); //Initialize pin 5 as digital output

IOInit(p6,in); //Initialize pin 5 as digital input

while (1) { // MAIN LOOP }

}

9

Page 10: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Digital I/Os Functions

First of all initialize the pin as Digital Input or as Digital Output → IOInit(pin name, type);For example:

Set pin 6 Digital output → IOInit(p6, out);Set pin 5 Digital input → IOInit(p5,in);

How to change the state of a Digital Output → IOPut(pin name, value);

For example:IOPut(p6, on); //sets the pin to high voltage value (3,3V)IOPut(p6, off); //sets the pin to low voltage value (0V)IOPut(p6, toggle); //toggles the state of the pin (H to L or opposite)

The “on” keyword is associated to a high voltage level, so a “TRUE” logical state. In a similar way the “off” keyword is associated to a low voltage level, so a “FALSE” logical state.

Note: The keywords “on”, “off”, and “toggle” are case insensitive.

How to read the state of a Digital Input → IOGet(pin name);

For example:IOGet(p5); //will return the value of pin 5 : on(1) or off(0)

How to enable the internal pull-up or pull-down resistor of a Digital Input

pin 5 digital input with internal pull-up resistor → IOInit(p5, inup);pin 5 digital input with internal pull-down resistor → IOInit(p5, indown);

QUESTION: What is the use for pull-up and pull-down resistors in Flyport's input pins?

Pull-up and pull-down resistors are always used to avoid floating voltages on input pins. With a pull-up resistor we connect an input pin to a high voltage reference (3.3V), and with a pull-down resistor we connect the pin to a low voltage reference (ground). Of course you can always change the input value with another voltage source, or with a switch, as shown in the figure below:

10

Page 11: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

In the pull-down circuit of the figure, we can see that when the switch is opened (no other sources are connected), the input pin “reads” a low voltage value. If we close the switch (and connect a high voltage source), we change the what the pin “reads” to a high value.

In the pull-up case, we have a high value when the switch is open, and a low value when the switch is closed, because the internal reference is high and the external reference is low.

The convenience of using the internal pull-up/pull-down resistors is that they are inside the microcontroller, and you can change them without adding external components.

NOTE: Pay attention of the different pull-up/pull-down values on switch states!

QUESTION: How can we catch a pushbutton state change? Pressed or Released?Buttons need always internal pull-up (“inup”) or pull-down (“indown”) resistors enabled.

Input type Button pressed Button released

inup ON to OFF OFF to ON

indown OFF to ON ON to OFF

Check the state of a pushbutton → IOButtonState(pin name)Returns: pressed if the button has been pressed

released if the button has been not pressed or released

You don't have to keep track of the state of the pin, or of its logical value. The openPicus framework does this work for you and tells you if the button has been pressed or released.

11

Page 12: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Example:

if(IOButtonState (p5) == pressed){

// Code to execute when p5 is pressed...}else{

// Code to execute when p5 is not pressed...}

To know what kind of value you have to substitute instead of pressed in the above example, check the table above. In the case of an “inup” resistor substitute “OFF” (that is a low voltage level). In the case of an “indown” resistor substitute “ON” (that is a high voltage level).

A frequent problem related to buttons and switches is bouncing of the signal.

This problem is generated by mechanical issues with the internal contacts of buttons and switches but with a small amount of software, problems with bounce can be solved.

The IOButtonState has an integrated de-bounce feature, so you don't have to worry about this problem.

The results will be filtered with a 20ms filter:• if the input value changes in less than 20ms, the result will not be valid• if the input value remains the same longer than 20ms, the result will be valid

12

Page 13: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

Remappable Pins

A great feature of Flyport module is the possibility of remap the peripheral to almost any pin.

As you can see in the pinout table, almost each pin is remappable.

Pin remapping allows you to add more UARTs, PWMs, SPIs, TIMER and External interrupts.

For PWMs you can use the PWM dedicated functions (see PWM section). For the other peripheral the list below shows the functionalities you can associate to every pin.

QUESTION: What are the various assignable functionalities on Remappable pins? How are they named?

Output peripherals– UART1TX– UART1RTS (not enabled in default UART initialization)– UART2TX– UART2RTS (not enabled in default UART initialization)– UART3TX– UART3RTS (not enabled in default UART initialization)– SPICLKOUT (for SPI Master mode, Clock Output Signal)– SPI_OUT (Data Output Signal)– SPI_SS_OUT (for SPI Master mode, Slave Select Signal)

Input peripherals– UART1RX– UART1CTS (not enabled in default UART initialization)– UART2RX– UART2CTS (not enabled in default UART initialization)– UART3RX– UART3CTS (not enabled in default UART initialization)– EXT_INT2– EXT_INT3– EXT_INT4– SPICLKIN (for SPI Slave mode, Clock Input Signal)– SPI_IN (Data Input Signal)– SPI_SS (for SPI Slave mode, Slave Select Signal)– TIM_4_CLK

With the Flyport module pinstrip connector more expansions with different pinouts can be created just by using the remapping feature. As a result the layouts of Flyport expansion boards can simpler and easier to route on PCBs, breadboards or any prototyping board type.

The pin configuration depends on your specific application, so the “Hardware Architecture” should be decided first: which pins will be used as peripherals, and which pins will be “simple I/Os”

13

Page 14: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Remappable Pins Functions

To REMAP a pin you can simply use the IOInit function. The difference between the digital I/Os and PeripheralPinSelect assignment is done with different values of the second parameter:

IOInit ( p2, EXT_INT3 ); will associate the pin 2 of Flyport to the External Interrupt 3 functions.

IOInit ( p18, SPI_OUT); will associate the pin 18 of Flyport to the SPI2 data out functionality.

Note: Remapping is useful but you need to pay attention.If a pin is assigned to a peripheral, the IOGet and IOPut will not work properly. Secondly, after the assignment, a new function will be associated to a pin, and it must be used the related peripheral functions to set up the peripheral module.

For example UART2 and UART3 are not enabled by default to give more memory to the user application. If you need to use 3 UARTs in your application, you must enable these 3 UARTs using the Wizard inside the IDE. See the UART section for more information.

QUESTION: Can I use the remapping feature at runtime?

Yes, the openPicus Framework supports pin remapping at runtime. We suggest to plan a definitive pin mapping and don't change during the development. Remember that an error with remapping may cause hardware fault.

QUESTION: Can I use UART4 with Flyport GPRS?

No, since UART4 is used by GPRS module, it is available only for Flyport Wi-Fi and Flyport Ethernet.

14

Page 15: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

Analog Inputs

Flyport has several analog channels connected to the internal 10bit ADC of the microcontroller.

QUESTION: What is the relation between number and analog input voltage?

Flyport has a precise Voltage reference inside at 2,048V. This means that the max voltage on an analog input is 2,048V.

The ADC is 10 bit. So it means 2^10 = 1024 different values (0-min voltage to 1023-max voltage).Since the ADC uses the internal precise voltage reference of the module the single bit value is 2,048/1024=2mV

For example and Analog Read value of 1000 means:1000 * 0.002 V = 2V of voltage on the analog input

Note: Analog input pins may be used also as GPIO, but they are not 5V tolerant! Avoid to apply a voltage > 3.3V or you could damage the microcontroller!

QUESTION: How can I test this feature? Here is a simple connection of a potentiometer to test analog input 1:

As you can see from schematics, there is a resistor of 680 Ohm and a potentiometer of 1KOhm. This configuration is made to reduce the max voltage of the Analog input pin. In fact, when the potentiometer reaches its max value on the analog pin we have:

Va1_in = Vdd * (R1 / R1+R2) = 3.3 * (1000 * 1680) = 1,96V

This value is compatible with the voltage input range of analog inputs (max 2,048V)

15

Page 16: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Analog Inputs Functions

Read an Analog Input → ADCVal(channel);This function returns an int value (from 0 to 1023) related to the Analog channel (from 1 to 4) as reported on the pinout table.Parameters:channel: specify the ADC input channel (1 to 4)

Example:

int myADCValue; //Initialize the variable to get the value

myADCValue = ADCVal(1); //Returns the value of the Analog channel #1

16

Page 17: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

PWM

Flyport provides up to 9 PWMs using remappable pin function.

QUESTION: What is a PWM signal? PWM, Pulse Width Modulation, is a digital periodic signal. It is like a square wave, but the duty cycle is variable. The duty cycle is the ratio between the high level period duration and the low level period duration, often expressed in %.

A duty cycle of 100% is a signal that is always high, a duty cycle of 0% is always low, and 50% is a perfect square wave where the high and low durations are the same.

There are 2 main parameters of a PWM signal: the duty cycle discussed above, and the frequency of the signal, which represents the repetitions per second of our signal.

For example, a PWM with a frequency of 200Hz will have the period:

T = 1/f = 1/200 = 5ms

So every 5ms the period will be repeated. Using a PWM with 25% of duty there will be:

• Total period: 5ms• High duration: (5ms*25/100) = 1,25 ms• Low duration: 5ms – 1,25ms = 3,75 ms

QUESTION: How can I use PWM signals? Normally PWM signal is used to drive a Led or a DC motor. It's possible also to create “virtual” analog output signal. Note that PWM is not a DAC (digital to analog converter), but a simple way to generate an analog signal adding some R-C filtering. The R-C filter design is a relatively complex operation that depends on the frequency of the PWM and on the load at the output pin.

17

Page 18: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

PWM function

There are 4 basic PWM functions:

Initialize the pin as PWM → PWMInit(BYTE pwm, float freq, float dutyc);It is a mandatory to call the initialize function to setup the a PWM module Parameters:pwm: PWM id (from 1 up to 9)freq: frequency of the PWM signal in Hertzduty: duty cycle (from 0 up to 100, it is expressed in percentage)

Activate a PWM signal → PWMOn(Byte io, BYTE pwm);

Parameters:io: io pin to assign at pwm functionality (p1, p2, p3...)pwm: PWM id (from 1 up to 9)

Change Duty Cycle →PWMDuty(float duty, Byte pwm);This function can be used to change the pwm duty cycle “on the fly”.

Parameters:duty: the new duty cycle (from 0 up to 100, it is expressed in percentage)pwm: PWM id (from 1 up to 9)

Turn Off the PWM → PWMOff(BYTE pwm);This function can be used to turn off a PWM.

Parameters:pwm: PWM id (from 1 up to 9)

A simple application of PWM can be changing the brightness of aLED. In fact, by changing the PWM duty cycle we change the root mean square (RMS) voltage of the signal, so we can change the brightness of a LED with PWM.

Example:

PWMInit(1, 1000, 100); //Initialize PWM1 to work //at 1000 Hz, 100% of duty (always on)

PWMOn(p5, 1); //Turns on pwm1, and set it to pin5

PWMDuty(50, 1); //Change the duty at 50% (about half bright)

18

Page 19: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

PWMDuty(0,1); //Change the duty at 0% (off)

PWMOff(1);

A more complex example (to add on taskFlyport.c):

#include “taskFlyport.h”

void FlyportTask(){

const int maxBright = 37; //here we set max % of brightnessconst int minBright = 2; //and here the min %float bright = (float)maxBright;

PWMInit(1,1000,maxBright);PWMOn(p5, 1);

while(1){

for (bright = maxBright; bright > minBright; bright--){

PWMDuty(bright, 1);vTaskDelay(1); //used to slow down the effect

}for (bright = minBright; bright < maxBright; bright ++){

PWMDuty(bright, 1);vTaskDelay(1); //used to slow down the effect

}}

}

For more information about PWM and its application: http://en.wikipedia.org/wiki/Pulse-width_modulation

19

Page 20: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Serial Communication (UART)

The UART is a serial asynchronous communication module to communicate with an external device such as a GPS receiver.

You must know the baud rate of the signal or the UART will not be able to work properly.

Flyport has a UART input buffer of 256 characters that stores the incoming chars. You don't have to poll the UART buffer, but just check the number of received chars.

The size of the UART input buffer is customizable by the user, using the Wizard tool inside the IDE:

Warning: the maximum memory used by UART buffers should not exceed 6144. The Wizard tool will show the effects of UART buffer size on total memory available.

To perform testing on UART we suggest PC programs like “Putty”, “Termite” or the IDE Serial Monitor. Do not use Hyper Terminal because it does not support the DTR signal (that is used by miniUSB programmer as Reset signal).

20

Page 21: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

UART Functions

First of all you must initiate the UART at a specific baudrate. Then you must enable the UART.

Note: In the IDE wizard, there is the possibility to use the uart 1 as “GPRS debug on UART1”. In this case the UART1 module is initialized at 19200 baud and turned on at startup.

Initialize the UART → UARTInit(int port, long int baud);This is a mandatory function that initializes the module to work properly.This function is called in the Flyport Framework initialization, but it can be recalled to change the baudrate parameter at runtime.Parameters:port: The UART port to initialize (from 1 to 3)baud: Desired baudrate

Turn on the UART → UARTOn(int port);This function turns on the UART functionalities. It should be called only after UARTInit Parameters:port: the UART port to turn on

Turn Off the UART → UARTOff(int port);This function turns off the UART module functionalities. It should be called before UARTInit.Parameters:port: the UART port to turn off

Check the UART input buffer → UARTBufferSize(int port);This function returns an int number equal to how many chars have arrived and are stored inside the UART RX Buffer.Parameters:port: the UART portReturns:int N: number of chars inside the buffer

Read the UART input buffer → UARTRead(int port, char *towrite, int count);This function reads characters from the UART RX buffer and puts them in the char pointer “towrite”. It also returns the report of the operation.Parameters:port: the UART porttowrite: the char pointer to fill with the read characterscount: the number of characters to readReturns:int N: N > 0, N characters correctly read.

N < 0, N characters read, but buffer overflow detected.

21

Page 22: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Send a string to the UART → UARTWrite(int port, char *buffer);This function writes a specific string on the UART port.Parameters:port: the UART portbuffer the string to write (a NULL terminated char array)

Send a char to the UART → UARTWriteCh(int port, char chr);This function writes a specific string to the UART port.Parameters:port: the UART portchr the character to write

Flush the UART input buffer → UARTFlush(int port);This function clears the buffer of the specified UART port.Parameters:port: the UART port

22

Page 23: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

I2C Communication Protocol

I2C is a 2 wire serial communication widely used in embedded electronics to connect devices such as external memory and more.

Unlike the UART, I2C has a Master-Slave architecture, where the Master starts all the requests of communication. The baud rate is given by the Master, and the most used values are 100kb/s (low speed) and 400kb/s (high speed).

I2C bus needs pull-up resistors and dedicated open collector pins. This is the reason why the I2C pins are not remappable.

To use the I2C protocol has s a determined sequence of operations for starting, stopping, write, read and checking if the data was transmitted ok.

For more information see the link:http://en.wikipedia.org/wiki/I%C2%B2C

OpenPicus framework offers some functions to easily manage the I2C communication, using Flyport as a Master. In this way it’s possible to communicate with I2C slave devices and read/write their register. It’ possible to attach more than one device on the bus, since I2C uses addressing. The only issue is to check that any device connected on the bus must have a different address.

I2C Basic Functions

Initialize I2C → I2CInit(BYTE speed);This function initializes the I2C at the specified speed of communication.Parameters:speed: it can be HIGH_SPEED (400K) or LOW_SPEED (100K)

Send a Start condition → I2CStart();This function sends a start sequence on the I2C bus.Parameters:none

Send a Restart condition → I2CRestart();This function resends a start sequence on the I2C bus.Parameters:none

Send a Stop condition → I2CStop();This function sends a stop sequence on the I2C bus.Parameters:none

23

Page 24: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Write a byte on I2C → I2CWrite(BYTE data);This function writes a byte of data .Parameters:data: The byte data to be sentReturns:0: NACK condition detected1: ACK condition detected2: Write Collision detected3: Master Collision detected

Accessing memory registers of slave devices

The easier way to communicate with a I2C device, is using the ready-to-go functions offered by the OpenPicus Framework to read/write registers. Using the following functions, you don't need to know the details of the I2C communications, you are just requested to pass the device and the register(s) addresses and the commands will exchange the data with the slave device. The functions follows the standard way to read/write registers on I2C bus, if you experience any problems, always refer to slave device datasheet to check if some particular operation is required to communicate.Note on device addressing: in the following functions, with "device address" is intended the 7-bit I2C address of the device. You can find the default address and how to change it in the datasheet of each I2C device. The address will be correctly shifted and added with the read/write bit by the read/write functions

Read a single register → I2CReadReg( BYTE DeviceAddr, BYTE RegisterAddr, unsigned int rwDelay);

This function to read a byte of data from a specific device.Parameters:DeviceAddr: The byte address of slave deviceRegisterAddr: The byte address of memory register to readrwDelay: The delay (expressed in 10us) between write and read operations

performed. This delay is needed by some I2C devices (please see slave datasheet for further info)Returns:char of data read.

Reading multiple registers → I2CReadMulti( BYTE DeviceAddr, BYTE RegisterAddr, BYTE destination[], unsigned int numReg, unsigned int rwDelay);

This function to read a “numReg” amount of bytes starting from a specific address.Parameters:DeviceAddr: The byte address of slave deviceRegisterAddr: The byte address of memory register to readdestination: The byte array to store datanumReg: The amount of register to read.

24

Page 25: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

rwDelay: The delay (expressed in 10us) between write and read operations performed. This delay is needed by some I2C devices (please see slave datasheet for further info)

Returns:BOOL result of operation: TRUE → operation success, FALSE → operation failed

Write a single register → I2CWriteReg( BYTE DeviceAddr, BYTE RegisterAddr, BYTE valueToWrite);

This function writes a byte of data to specific device.Parameters:DeviceAddr: The byte address of slave deviceRegisterAddr: The byte address of memory register to writevalueToWrite: The new value to put inside memory registerReturns:None

Reading multiple registers → I2CWriteMulti( BYTE DeviceAddr, BYTE RegisterAddr, BYTE dataSource[], unsigned int numReg);

This function to read a byte of data from a specific device.Parameters:DeviceAddr: The byte address of slave deviceRegisterAddr: The byte address of memory register to writedestination: The byte array of data to writenumReg: The amount of register to write.

Returns:BOOL result of operation: TRUE → operation success, FALSE → operation failed

Note: more examples of I2C functions usage are available at wiki.openpicus.com

25

Page 26: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

RTCC module

RTCC – Real Time Clock Calendar – is a hardware clock module embedded on Flyport. It provides automatic clock counter and customizable interrupt driven alarm.

Using openPicus framework libraries it's possible to read and write values of RTCC date and time and set am alarm. Alarm event can be both assigned to a callback function, or read in a dedicated status function.

RTCC APIs

Initialize/Write RTCC module → void RTCCSet(struct tm* rtcc);This function sets the date/time and enables RTCC module.Parameters:rtcc: a pointer to a struct tm variable, containing the date and the time to set

Read RTCC module → void RTCCGet(struct tm* rtcc);This function reads the actual date/time from the RTCC and put it inside a struct pointerParameters:rtcc: a pointer to a struct tm variable to fill with data

Configure Alarm of RTCC module → void RTCCAlarmConf(struct tm* rtcc, int repeats, BYTE whenToRaise, void (*fptr)());

This function reads the actual date/time from the RTCC and put it inside a struct pointerParameters:rtcc: a pointer to a struct tm variable to fill with datarepeats: specifies how many times the alarm must be repeated:

REPEAT_NO alarm must not be repeated1 – 256 the number of times alarm must be repeatedREPEAT_INFINITE alarm must be repeated forever

whenToRaise: how often alarm should be raisedEVERY_HALF_SEC alarm is raised every half secondEVERY_SEC alarm is raised every secondEVERY_TEN_SEC alarm is raised every 10 secondsEVERY_MIN alarm is raised every minuteEVERY_TEN_MIN alarm is raised every 10 minutesEVERY_HOUR alarm is raised every hourEVERY_DAY alarm is raised every dayEVERY_WEEK alarm is raised every weekEVERY_MONTH alarm is raised every monthEVERY_YEAR alarm is raised every year

fptr: custom function to execute when alarm event is raised. Use NO_ALRM_EVENT to ignore.

26

Page 27: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

Reads Alarm status of RTCC module → BOOL RTCCAlarmStat();Returns the actual status of alarm event. This function can be polled continuously to get alarm trigger.Returns:BOOL status of alarm:

TRUE → Alarm was triggered. The function is automatically set to FALSE until next alarm.FALSE → No alarm event.

Enable/Disables Alarm of RTCC module → void RTCCAlarmSet(BYTE run);Activates or deactivates the alarmParameters:run:

TRUE → Alarm activated.FALSE → Alarm not activated.

27

Page 28: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

GSM Task OpenPicus framework integrates the stack with FreeRTOS operating system, to ease the management of any GSM/GPRS operation. APIs framework for GSM/GPRS has several functions to handle Voice Call, SMS, TCP, HTTP, FTP and SMTP services. Those APIs manage the communication with GPRS module, sends all the required AT commands, parses responses, and also manages asynchronous messages. In this way, developer doesn't need to have specific knowledge about AT commands usage, or bother about GSM module usage.

Only a minimum knowledge of the GSM services is needed, and also some knowledge of TCP/IP is requested for data connection services.

Flyport GPRS can be used in two different modes: Standard mode or Low Level mode.Using Standard mode all the AT commands are handled by GSMTask, instead in Low Level Mode the user should keep track of all the messages on GPRS dedicated serial port, specially all the asynchronous messages sent by GPRS Module for network events.

Standard Mode

In Standard mode, all the serial commands (AT commands) between PIC Microcontroller and GPRS Module are processed inside the “GSMTask”. In this way, user application can be independent from GSM commands execution, and “FlyportTask” must not be locked waiting for the end of UART (serial) operations.Another advantage of Standard mode is all the “Unsolicited messages” received from GPRS Module are analysed by GSMTask, and dedicated events are executed automatically to perform different actions. Unsolicited messages are asynchronous messages sent by GPRS module to inform master device (in our case microcontroller) of any kind of events. Such events could be incoming SMS, connection to network, data on TCP Socket, and so on...

IMPORTANT: Flyport can control GSM Module events only in Standard mode. If user forces Low Level Mode, GSM Events functions will NOT be executed. The message parsing and detecting is left to user firmware if Low Level mode is enabled!

GSM APIs work-flow

Since GSM module response to certain AT commands can be really slow (timeouts of up to 120 seconds are necessary), it is mandatory to provide framework APIs of a different structure respect Flyport Wi-Fi and Ethernet.

To permits GSM Task to handle incoming data, and execute Flyport Task requests APIs execution, all the UART data exchanges are handled using multitasking architecture. This means that all the functions provided does not response directly with values, but its execution is performed in background. This permits to create user applications that continue them operations while waiting for GPRS commands to finish.

28

Page 29: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

The generic work-flow of Flyport GPRS API functions is the following:• Inside Flyport Task the function GPRS_API_function is called• all necessary parameters are set, and the type of operation is communicated to GSM Task,

and Execution status is changed to “OP_EXECUTION”• Flyport Task continues, but (in background) GSM Task handles requested AT commands for

GPRS_API_function function execution• When GSM Task finishes GPRS_API_function execution, it sets Execution Status to the result

of operation.• Flyport Task is now free to analyse the results, and request another GPRS API function.

IMPORTANT: All the GSM/GPRS functions are NOT blocking (on the contrary of Flyport Wi-Fi and Ethernet), because GPRS functions may have a very large timeout (up to 120 seconds).

To have a feedback of GSM Task execution state, it is possible to use the following function:

LastExecStat () → returns last status of GSM Task Execution.Return:

the function returns one of the values explained on the following table:

Status Value Description

OP_SUCCESS 0 Last function executed correctly

OP_EXECUTION -1 Function still executing

OP_LL -2 Low Level mode is activate

OP_TIMEOUT 1 Timeout error: GPRS module has not answered within the required timeout for the operation

OP_SYNTAX_ERR 2 GPRS module reported a “syntax error” message

OP_CMS_ERR 3 GPRS module reported a CMS error

OP_CME_ERR 4 GPRS module reported a CME error

OP_NO_CARR_ERR 5 GPRS module reported NO CARRIER message

OP_SMTP_ERR 6 Error in sending the email

OP_FTP_ERR 7 Error message received in FTP operation

OP_HIB_ERR 8 GPRS module is turned off and cannot reply to commands

Using LastExecStat() function it is possible to develop Flyport Task firmware in a both blocking manner and non-blocking manner.Following are two basic examples of blocking and non-blocking code:

29

Page 30: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

TCP connection in blocking way:

TCP_SOCKET sock1;TCPClientOpen(&sock1, "www.google.com","80");

// Waiting for the command to be completedwhile(LastExecStat() == OP_EXECUTION){

vTaskDelay(1);}

// Check on success for the operationif(LastExecStat() == OP_SUCCESS)

UARTWrite(1, “Operation succeeded”);else

UARTWrite(1, “Operation NOT succeeded”);

TCP connection in non-blocking way:

TCP_SOCKET sock1;TCPClientOpen(&sock1, "www.google.com","80");while (1){

/* Here it can be executed code, for example reading sensors...instruction 1...instruction 2...…instruction n*/

// Inside the loop it can be checked periodically if the TCP// connection has succeeded, since GSM stack is independent // from my application...if(LastExecStat() == OP_SUCCESS)

UARTWrite(1, “Operation succeeded”);else

UARTWrite(1, “Operation NOT succeeded”);}

30

Page 31: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

GSM Events

All the provided events functions are stored inside the file “GSM_Events.c”. This permits the user to customize the response to each kind of asynchronous stimulus differently, for example if the event is an incoming call, or a network connection lost.

QUESTION: What kind of events are provided?

Following is a list of events provided by firmware, and their parameters:

OnRing (char* phoneNumber) – executed when a RING is received (for example for an Incoming Call). It provides the phoneNumber (if any) that excited the RING.

OnNoCarrier (char* phoneNumber) – executed when the NO CARRIER message is received. It could be excited from a hang up from the phone number who sent the call, or if a TCP connection was lost. OnBusy (char* phoneNumber) – excited if Flyport reaches BUSY signal on phone line.

OnSMSReceived (char* memtype, int index) – this event is a notification form new SMS received. It provides related storage memory type, and position index.

OnSMSSentReport (int msgreference, int msgreport) – if user sends a message with delivery report, this event will be executed when the delivery SMS from operator is received. It provides related message reference number, and delivery report value.

OnError (int error, int errorNumber) – Every kind of ERROR messages received during the execution of AT-commands with GSM module are notified to user, providing two different error numbers:

int error: Type of the error. Following are handled errors:1 - OP_TIMEOUT: no reply from GSM module2 - OP_SYNTAX_ERR: “ERROR” message → some parameters are not allowed3 - OP_CMS_ERR: “+CMS :...” message → error on SMS4 - OP_CME_ERR: “+CME :...” message → generic GSM error5 - OP_NO_CARR_ERR: “NO CARRIER” message → only if not expected as response6 - OP_SMTP_ERR: “+KSMTP ERROR : ...” message → SMTP error not expected7 - OP_FTP_ERR: “+KFTP ERROR : ...” message → FTP error not expected

int errorNumber: Number of the error (if provided)

31

Page 32: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

OnRegistration (BYTE Status) – event executed every time the connection to network (or registration) changes its status. It provides new value of connection status. Values can be:

0 - NO_REG → not registered1 - REG_SUCCESS → registered correctly on network2 - SEARCHING → searching for operator3 - REG_DENIED → registration on network denied4 - UNKOWN → unknown status5 - ROAMING → registered in roaming mode

Those functions are called inside “GSM Task”, and can be customized to perform actions. By the way, there are limitation applied to this structure: all the operation executed inside those functions MUST NOT call other GSM Functions. Also their execution should be as faster as possible, to permits GSM task to perform its actions in less time.

So, for example, if a user would like to Hang up any incoming call on the first “OnRing” event, the code inside the function should set a variable visible from FlyportTask, and call the related hang up function ( CALLHangUp() ) from user task.

Network Connection and GSM info

Manage GSM network connection

Framework supports a function to manually retrieve network connection status of GSM module.

BYTE LastConnStatus() → In addition to OnRegistration event, user can read last connection status using this function. Values returned by this function are the same of the OnRegistration event parameter:

0 - NO_REG → not registered1 - REG_SUCCESS → registered correctly on network2 - SEARCHING → searching for operator3 - REG_DENIED → registration on network denied4 - UNKOWN → unknown status5 - ROAMING → registered in roaming mode

Read GSM Module IMEI

IMEI number (international mobile station equipment identity) is a unique number to identify each different GSM module. Reading this number, every Flyport GPRS will have a unique ID number not related to phone number.

char* GSMGetIMEI() → returns the string containing IMEI number. Its maximum size is 16 chars.

32

Page 33: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

Code Example

Following is a code example to use above functions inside FlyportTask. Using this example, user application starts network connection at startup and waits for registration completed.During the wait of registration, onboard LED blinks to provide a feedback to user. Once connected, it turns ON.

Also messages of welcome, and IMEI are printed on UART1 (the default UART used for generic debug of applications).

#include "taskFlyport.h"

void FlyportTask(){

UARTWrite(1,"Flyport Task Started!\r\n");

// wait for registration success while(LastConnStatus() != REG_SUCCESS) { vTaskDelay(20); IOPut(p21, toggle); }

// Connected! UARTWrite(1, "Flyport connected to GSM network!\r\n"); IOPut(p21, on); // Print IMEI number on UART1: UARTWrite(1, "IMEI: "); UARTWrite(1, GSMGetIMEI()); UARTWrite(1, "\r\n"); while(1) { }}

Voice Call

Flyport GPRS can perform voice call, detect Incoming calls and hang up.

NOTE: External circuitry is needed to connect microphone and headphones at GSM module.

33

Page 34: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Microphone input and headphone output are provided on JP2 connector; more info are available on SAGEMCOM website for further reference.

CALL APIs

CALLVoiceStart (char* phoneNumber) → Starts a call to provided phone number. Please, remember to add area code if needed by your phone operator.

CallHangUp () → hangs up call in progress (if any)

char* LastCallID () → returns the string of phone number of call partner. It should be a number of up to 30 characters.

BYTE LastCallStat() → provide last known call status. Values returned:CALL_READY – ready to receive or start a callCALL_IN_PROG – voice call is in progressCALL_BUSY – busy notification received on last call

SMS

Introduction

Flyport GPRS can send, receive and delete SMS form SIM and Module internal memory. To handle all the parameters of a SMS the following structure is included inside the framework:

SMS information variables:• Memory Type (SIM or Internal Memory)• Index (position on memory)• Text (up to 160 chars)• Sender (sender ID / Phone number)• Time / Date• Report Value• Message Reference

Every time a SMS operation is executed (like read, write, etc...) the SMS data struct is overwritten. This is done to reduce memory occupation on Flyport module. For example, every time a SMS is received, the index and memory type is overwritten.

To access to the above parameters, the following functions are available from Flyport Task

char* LastSmsSender () → returns char* to the string containing phone number of last received SMS sender.

34

Page 35: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

char* LastSmsText () → returns char* to the string containing text content of last SMS read / sent.

BYTE LastSmsMemType () → returns SM_MEM if SIM memory is used, ME_MEM if internal module memory is used.

int LastSmsIndex () → returns position index of last sms

struct tm LastSmsTime () → provides information about sms date and time

int LastSmsMsgRef () → returns message reference number of SMS sent

int LastSmsRepValue () → returns report value of SMS sent

SMS APIs

Following are explained functions to handle SMS functionalities.

SMSRead (int indexMsg, BYTE memType) → reads SMS content on provided index and memory type, and fills the SMS data structure. Once finished, all the parameters will be accessible using the functions explained above.

SMSDelete (int indexMsg, BYTE memType) → deletes the SMS at provided index and memory type.

SMSSend (char* phoneNumber, char* text, BOOL ack) → Start the SMS sending process. This function overwrites SMS data structure parameters.Parameters:

phoneNumber – destination phone number

text – content of text message. It must be a char[] of max 160 chars, or above chars will be ignored.

ack – delivery report acknowledge with SMS from mobile operator:FALSE to ignore SMS delivery feedback service.TRUE if user want to have delivery feedback with a SMS (note that additional costs could be applied by mobile operator).

Internal Flash File System

GSM module can store files in its internal Flash Memory. Since it is a non-volatile memory storage, this means that all data written inside the files will be available also after Flyport GPRS is turned off.

35

Page 36: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Features

This file storage can be freely used by user application. It is also used by openPicus framework to exchange files with remote FTP Servers. All files downloaded from a FTP are stored inside module flash memory, and all files to be uploaded to FTP server should be written of internal flash memory before to perform data exchange process.

User can create, read, modify and delete files stored using the following functions

File System APIs

FSWrite (char* filename, BYTE* dataBuffer, unsigned int dataSize) → Writes data on a file. If files exists, this function overrides all data.Parameters:

fileName – char[] with name of file to writedataBuffer – BYTE[] with data to writedataSize – amount of data to write

FSRead (char* filename, BYTE* dataBuffer, unsigned int dataSize) → Reads data from a file.Parameters:

fileName – char[] with name of file to readdataBuffer – BYTE[] with data to fill with data (Please, remember to use '&' operator)dataSize – amount of data to read

FSDelete (char* filename) → Deletes a file from memory.Parameters:

fileName – char[] with name of file to be deleted

FSSize (char* filename, int* dataSize) → Writes data on a file. If files exists, this function overrides all data.Parameters:

fileName – char[] with name of filedataSize – int number of data size of file (Please, remember to use the '&' operator)

FSAppend (char* filename, BYTE* dataBuffer, unsigned int dataSize) → Writes data on a file at the end of the file. If files does not exist, this function creates it.Parameters:

fileName – char[] with name of file to writedataBuffer – BYTE[] with data to writedataSize – amount of data to write

36

Page 37: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

Data Connections

To perform TCP/IP based connections, mobile operator APN parameters must be configured on Flyport GPRS.Pay attention: every mobile operator provides their own settings. So different SIM card could need different setting of APN parameters.

APN Configuration

The function provided by framework to setup APN parameters is:

APNConfig(char* apn, char* login, char* passw, char* ip, char* dns1, char* dns2) → Configures GSM module APN.Parameters:

apn – host name of APN mobile operatorlogin – user name of mobile operator loginpassw – password used for mobile operator loginip – static IP address, if provided by mobile operator. Please use “DYNAMIC” for dynamic IP assignmentdns1 – IP address of primary DNS Server. Please use “DYNAMIC” for dynamic IP assignmentdsn2 – IP address of secondary DNS Server. Please use “DYNAMIC” for dynamic IP assignment

NOTE: To set APN parameters is mandatory for any TCP/IP based operation (TCP, HTTP, SMTP and FTP). Please be sure to configure them properly before use TCP/IP based functions.

Email - SMTP

Flyport GPRS can send emails using data connection. Despite that, it is mandatory to be sure to use a SMTP service that do not require SSL security connections. Make sure to use a SMTP port that allows to send email without SSL (for example lavabit.com with outgoing mail server port 25).

Emails sent by Flyport GPRS can have multiple recipients: up to 2 different “To” destination addresses, and up to 2 “Cc” copy destination.

SMTP APIs

Every SMTP Email sending has a session_id provided by the SMTPEmailSend function. To retrieve last session id number it can be used the following function:

int LastSMTPSessionId() → returns last session id

SMTPParamsSet(char* smtpDomain, int smtpPort, char* senderEmail, char* smtpLogin, char* smtpPassw) → Sets SMTP Server parameters. If a parameter is

37

Page 38: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

not requested, please use the NOT_REQUESTED value.Parameters

smtpDomain – name of the SMTP server provider domainsmtpPort – SMTP port to be usedsenderEmail – email address that Flyport should usesmtpLogin – user name of SMTP loginsmtpPassw – password of SMTP login

SMTPParamsClear() → Clears SMTP parameters

SMTPEmailTo(char* toDest1, char* toDest2, char* ccDest1, char* ccDest2) → Sets destination recipients. To ignore destination, please use SMTP_NO_DEST value.Parameters

toDest1 – address of first email destinationtoDest2 – address of second email destinationccDest1 – address of first copy destinationccDest2 – address of second copy destination

SMTPEmailSend(char* subject, char* text) → send the email with provided subject and body text content.Parameters

subject – char[] containing subject of the email. Max 255 chars can be used.text – char[] containing body text of email.

SMTP Error Codes

Here is a table of possible SMTP error code and them meaning:

Error Meaning

3000 Invalid SMTP server name.

3001 Invalid address identification

3002 Invalid configuration. Parameter(s) is missing.

3003 Invalid data size - with KSMTPUL.

3004 SMTP session ID is not available.

3010 The login or the password got an invalid value.

3011 Invalid authentication method.

3012 Invalid mail sender

3020 Invalid receivers of the mail TO1.

3021 Invalid receivers of the mail TO2.

3022 Invalid receivers of the mail CC1.

3023 Invalid receivers of the mail CC2.

3040 The SMTP transfer failed due to connection (GSM or GPRS) fails.

38

Page 39: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

Error Meaning

3041 The SMTP transfer failed due to TCP connection troubles.

3042 The SMTP transfer failed due to server TCP connection error.

3043 The SMTP download failed due to Request time out.

3044 The SMTP transfer failed due to SMTP protocol error.

3045 The SMTP transfer failed due to DTR drop.

3049 The SMTP transfer download failed due to internal error.

3050 The SMTP transfer failed due to SMTP server trouble

3051 The SMTP transfer failed due to internal memory not available

3052 SMTP connection time out

3053 SMTP Raw Data upload to Module time out

3054 DNS Server address error or failed to resolve the host address

3055 SMTP client need Hardware flow control

TCP Client

TCP, Transmission Control Protocol, is a packet oriented protocol. It can be used to transmit and receive packets of data through the network between server and client.

• To use this kind of transmission, server and client should establish a connection. Since the connection between server and client consumes network resources (exchanging protocol service packets), it should be closed after the transmission is finished.

• In every TCP connection there is a Server and a Client, and Flyport GPRS can play only Client role.

• The TCP/IP transmission is “full-duplex” capable, and all the packets sent arrive in source order and “at most once”.

• By using acknowledgement, timeouts and checksums, the TCP protocol can check the integrity of every packet and know if a packet is arrived at the destination.

• At every host, multiple connections can be opened with the using of different ports, which we will call the “TCP_SOCKETs”.

39

Page 40: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

TCP Socket

Every TCP Connection is identified by its TCP_SOCKET. In Flyport GPRS a TCP_SOCKET variable is a bit different to TCP_SOCKET of Flyport Wi-Fi and Flyport Ethernet. Following is the parameters available on a TCP_SOCKET variable:

• number → a number provided by GPRS module to identify the various sockets created• status → last connection status known. Possible values are:

◦ 0 - SOCK_NOT_DEF – socket not defined yet on GSM module◦ 1 - SOCK_NOT_USED – socket not used yet by any TCP connection◦ 2 - SOCK_OPENING – socket connection is opening◦ 3 - SOCK_CONNECT – socket is connected to TCP Server◦ 4 - SOCK_CLOSING – socket is closing◦ 5 - SOCK_CLOSED – socket is closed

• rxLen → how many data available on GPRS module TCP receive buffer

Those values can be updated using the TCPStatus function, that will be explained later.

TCP APIs

TCPClientOpen(TCP_SOCKET* sock, char* tcpaddr, char* tcpport) → opens a socket inside GPRS module, and starts the connection with TCP Server.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parametertcpaddr – char[] with IP address or host name of TCP Servertcpport – char [] with port of TCP Server

TCPClientClose(TCP_SOCKET* sock) → closes connection to TCP Server, and deletes the socket from GPRS module.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parameter

TCPStatus(TCP_SOCKET* sock) → updates the values of TCP_SOCKET struct.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parameter

TCPWrite(TCP_SOCKET* sock, char* writech , int wlen) → writes data contained inside provided buffer to Server.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parameterwritech – buffer with data to send to TCP Serverwlen – amount of data to send

TCPRxFlush(TCP_SOCKET* sock) → flushes all data incoming to TCP RX buffer of GPRS

40

Page 41: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

module.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parameter

TCPRead(TCP_SOCKET* , char* readch , int rlen) → read data from TCP RX buffer of GPRS module and puts it to provided buffer.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parameterreadch – buffer to fill with data to read from TCP RX buffer of GPRS module.rlen – max amount of data to read

HTTP Client

HTTP Client library permits to easily perform GET and POST requests to HTTP Server. Basically a HTTP request is a particular TCP Connection. HTTP Client Requests data must be sent following a specific protocol. Using the provided functions, user does not have to bother on request header data preparation, reducing the possibilities of errors.

HTTP Client uses TCP_SOCKET structures, and its functions are similar to TCP Client functions. Also on HTTP libraries user can update TCP_SOCKET parameters using HTTPStatus function.For more info about TCP_SOCKET variable, please read the TCP Socket chapter.

HTTP APIs

HTTPOpen(TCP_SOCKET* sock, char* httphost, char* httpport) → opens a socket inside GPRS module, and starts the connection with HTTP Server.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parameterhttphost – char[] with IP address or host name of HTTP Serverhttpport – char [] with port of HTTP Server

HTTPClose(TCP_SOCKET* sock) → closes connection to HTTP Server, and deletes the socket from GPRS module.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parameter

HTTPStatus(TCP_SOCKET* sock) → updates the values of TCP_SOCKET struct.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parameter

HTTPRequest(TCP_SOCKET* sock, BYTE type, char* reqUrl, char*

41

Page 42: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

data2snd, char* param) → sends HTTP Request with provided parameters and data.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parametertype – type of the request. Values can be chosen between HTTP_GET or HTTP_POSTreqUrl – char[] containing URL of the requestdata2snd – char[] containing the string of data to send with HTTP Requestparam – char[] of additional parameters. Them will be inserted instead of default “Content-Length” and “Content-Type” values, or to permits user to add other specific values. If not needed, please use the value HTTP_NO_PARAM

HTTPReadData(TCP_SOCKET* sock, char* dataBuffer, int datalen) → read data from TCP RX buffer of GPRS module and puts it to provided buffer.Parameters:

sock – tcp socket variable to use. NOTE: remember to use the “&” operator with this parameterdataBuffer – buffer to fill with data to read from TCP RX buffer of GPRS module.datalen – max amount of data to read

FTP Client

FTP Client (file transfer protocol) can handle the file exchange between Flyport and PC. Big files can't be handled due to the limited Flyport memory resources.

Flyport can only be the Client, so other devices have to provide the FTP server service.

Basically, an FTP connection is a special set of instructions that use TCP protocol. With those commands the file and directories handles, user login, logout, etc. can be controlled.

Pay attention: Mobile service providers can impose limitations to the use of FTP protocol.You may experience problems using this type of operations if your operator block your TCP Connections at certain ports.

Generally FTP Servers uses port 21. If your Flyport GPRS cannot reach FTP server at this port, you should try with others (for example 25), but you need to control FTP Server parameters (or ask to FTP Server admin to do it).

Since Flyport GPRS uses FTP Passive Mode commands, this means that two TCP Sockets are used: one socket is used to perform commands exchange (call it “Cmd Socket”), and another for data transfer (call it “Data Socket”). Using Flyport GPRS, user do not need to handle two different connections, since them are automatically used by GPRS module.

FTP passive mode starts with only one TCP connection, using “Cmd Socket”. Once connected, FTP Client device (in this case Flyport module) executes login to FTP Server and asks it to enter in passive mode, and provide info about the “Data Socket”. Then FTP Server reply with info about IP address and port to be used and data transfer can be started.This mode of operation is the most used, and also the safer on server side. Anyway, if your mobile

42

Page 43: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

operator applies firewall (or limitations) to the ports used by Data socket, you will mostly fail on file transfer.Again, be sure to set used FTP Server with ports supported by your mobile operator, or ask to FTP Server admin or to your mobile operator to provide you more information on your connection limitations.

FTP Socket

To perform FTP File exchange a FTP_SOCKET variable is used. In Flyport GPRS a FTP_SOCKET variable is a bit different from FTP_SOCKET of Flyport Wi-Fi and Flyport Ethernet. Following is the parameters available on a FTP_SOCKET variable:

• number → a number provided by GPRS module to identify the various sockets created (only one at time can be used with Flyport GPRS)

• ftpError → last FTP error code received (if any).

FTP APIs

FTP functions integrated on current release of openpicus framework, uses GPRS Flash file system as file storage of FTP protocol. So, you can exchange (upload / download) file from FTP Server to GPRS module internal flash, and from GPRS module internal flash to FTP Server.

Here is a list of functions available:

FTPConfig(FTP_SOCKET* ftpSocket, char* serverName, char* login, char* password, WORD portNumber) → sets FTP Server configuration. This function MUST BE USED always before the execution of the other functions, since every FTP Operations closes connections and deletes sockets inside GPRS module.Parameters:

ftpSocket – ftp socket variable to use. NOTE: remember to use the “&” operator with this parameterserverName – char[] containing IP address or Host Name of FTP Server. NOTE: max 255 chars are acceptedlogin – char[] containing username to execute login on FTP Server. NOTE: max 255 chars are acceptedpassword – char[] containing password to execute login on FTP Server. NOTE: max 255 chars are acceptedportNumber – WORD of port of FTP Server to execute connection. NOTE: This port must be accepted by your mobile operator

FTPReceive(FTP_SOCKET* sock, char* flashFilename, char* serverPath, char* serverFilename) → Receives a file from FTP Server, and puts it inside GPRS Module.Parameters:

ftpSocket – ftp socket variable to use. NOTE: remember to use the “&” operator with this parameterflashFilename – char[] containing name of file to be used to store file on GPRS internal flashserverPath – char[] containing directory path to be usedserverFilename – char[] containing name of file stored on FTP Server to download

FTPSend(FTP_SOCKET* sock, char* flashFilename, char* serverPath, char*

43

Page 44: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

serverFilename, BOOL appendMode) → Sends a file from GPRS module to FTP Server. Can overwrite or append file content.Parameters:

ftpSocket – ftp socket variable to use. NOTE: remember to use the “&” operator with this parameterflashFilename – char[] containing name of file to be used to store file on GPRS internal flashserverPath – char[] containing directory path to be usedserverFilename – char[] containing name of file stored on FTP Server to uploadappendMode – TRUE to append data on existing file, FALSE to overwrite its content

FTPDelete(FTP_SOCKET* sock, char* serverPath, char* serverFilename) → Deletes a file from FTP Server.Parameters:

ftpSocket – ftp socket variable to use. NOTE: remember to use the “&” operator with this parameterserverPath – char[] containing directory path to be usedserverFilename – char[] containing name of file stored on FTP Server to be deleted.

Power Saving

Flyport GPRS can take advantage of two type of Power Saving mode of operation: • Turn OFF GPRS Module only (Hibernation)• Turn OFF GPRS Module and put in Sleep state microcontroller (Sleep)

Hibernation permits to use all the Hardware features of Flyport module, but all connectivity functions with GPRS module will be ignored. Using sleep mode only external interrupts and RTCC can wake up microcontroller.

Hibernate Mode

This is not the maximum power saving mode, but PIC is still powered and working.

The functions described in “Controlling the FLYPORT hardware” chapter, and “RTCC peripheral module” can be used without any kind of warning as they are only PIC dependant.

To Activate Hibernate Mode → GSMHibernate();This function activates the Hibernate mode, so turn OFF GPRS Module and disconnects it from GSM Network.

To Deactivate the Hibernate Mode → GSMOn();This function turns ON GPRS Module and initializes it to start connection to GSM Network.

44

Page 45: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

Sleep Mode

This is the more efficient available power saving working mode. Since it locks almost all the power of the microcontroller, only external events can wake up FLYPORT from this state.

The external events that can wake up FLYPORT are 2:• RTCC alarm• External Interrupts (up to 3 differents)

Both of the above events launch special Interrupt Service Routines (ISRs) that permit the microcontroller to wake up from a sleep condition. It is not important what the ISR related functions do, the important point is that they are activated from external events(the RTCC alarm can be seen as an external event since it uses a secondary oscillator that is independent from the microcontroller).

To Activate Sleep Mode → GSMSleep();This function activates the Sleep mode, so activates the Hibernate mode and stops microcontroller working.

To Deactivate Sleep ModeOnly RTCC and external interrupts can deactivate the sleep mode.

Low Level Mode

Low Level mode was integrated to permits user to self manage AT commands between PIC microcontroller and GPRS Module. Adding this flexibility, openPicus Framework must be sure to interacts with GPRS module at certain settings condition. So, EVERY TIME user uses Low Level mode, and returns to Standard mode, GPRS module is reset and again initialized. So, any GSM/GPRS operation data will be loose (for example TCP sockets, or call in progress). Be carefully using this mode, but most of it, be sure you can reset and init again GPRS module before to enable again Standard mode.

Similar to the other UART of the openPicus Framework, using Low Level mode user can take advantage of a buffered GSM dedicated UART of 1512 BYTEs, and a smart Interrupt service routine to fill the buffer automatically at every byte of data received.Almost all the functions developed for UART peripherals are available to communicate with GPRS module in Low Level mode.

In addition to UART communication functions, Low Level mode permits user to execute Resets, POKs, and handle extended UART signals provided by hardware connections between PIC microcontroller and GSM module on Flyport GPRS system-on-module circuitry.

45

Page 46: Flyport GPRS programmer's guide 2.3   rev1.0

FLYPORT GPRS Programmer's guide (rev 1.0) www.openpicus.com

Low Level Mode APIs

Low Level mode functions are described above:

LLModeEnable() → Switches the framework Low Level mode operation. NOTE: in this mode, unsolicited messages and events are not handled by framework!

STDModeEnable() → Switches the framework to Standard. Note: when this functions is called, a Hilo reset is performed, so any data / voice connection is lost

LLFlush() → Flushes GPRS module dedicated UART buffer data. NOTE: Works only in Low Level mode!

LLBufferSize() → Gets GPRS module dedicated UART buffer size. NOTE: Works only in Low Level mode! If used in Standard mode, will return -1

LLRead(char *buffer , int count) → Reads data from GPRS dedicated UART buffer and fills provided buffer. NOTE: Works only in Low Level mode! If used in Standard mode, will return -1Parameters:

buffer – char [] to fill with data readcount – amount of chars to be read

Return:int – amount of data actually read from buffer.

LLWrite(char *buffer, int count) → Writes data to GPRS dedicated UART. NOTE: Works only in Low Level mode! If used in Standard mode, no operation will be performed.This function is similar to Standard mode functions (not blocking function), and user firmware will be not locked waiting for end of operation;Parameters:

buffer – char [] with data to be writtencount – amount of chars to be written

LLWriteCh(char chr) → Writes a single char to GPRS dedicated UART. NOTE: Works only in Low Level mode! If used in Standard mode, no operation will be performed.This function is similar to Standard mode functions (not blocking function), and user firmware will be not locked waiting for end of operation;Parameters:

chr – char with data to be written

LLReset() → Performs a Reset of GPRS module. NOTE: Works only in Low Level mode! If used in Standard mode, no operation will be performed.

LLDtr(BOOL onoff) → Changes DTR signal of GPRS module dedicated UART interface. NOTE: Works only in Low Level mode! If used in Standard mode, no operation will be performed.Parameters:

onoff – BOOL value of the state to set

LLDcd() → Reads DCD signal state of GPRS module dedicated UART internace. NOTE: Works only in Low Level mode! If used in Standard mode, FALSE value will be returned.Returns:

46

Page 47: Flyport GPRS programmer's guide 2.3   rev1.0

www.openpicus.com FLYPORT GPRS Programmer's guide (rev 1.0)

BOOL – value of DCD signal.

LLDsr() → Reads DSR signal state of GPRS module dedicated UART internace. NOTE: Works only in Low Level mode! If used in Standard mode, FALSE value will be returned.Returns:

BOOL – value of DSR signal.

LLPok() → Performs a POK of GPRS module. NOTE: Works only in Low Level mode! If used in Standard mode, no operation will be performed.

47