Flyport GPRS programmer's guide 2.3   rev1.0
Upcoming SlideShare
Loading in...5
×
 

Flyport GPRS programmer's guide 2.3 rev1.0

on

  • 934 views

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

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

Statistics

Views

Total Views
934
Views on SlideShare
934
Embed Views
0

Actions

Likes
0
Downloads
41
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Flyport GPRS programmer's guide 2.3   rev1.0 Flyport GPRS programmer's guide 2.3 rev1.0 Document Transcript

  • FLYPORT GPRS Programmers GuideFramework version 2.3release 1.0
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.com[this page has intentionally been left blank]2
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)ContentsFlyport GPRS.........................................................................................................................................5Introduction.....................................................................................................................................5Bootloader ......................................................................................................................................6Pinout...............................................................................................................................................7Hardware functions..............................................................................................................................9Digital Inputs and Outputs...............................................................................................................9Digital I/Os Functions................................................................................................................10Remappable Pins...........................................................................................................................13Remappable Pins Functions......................................................................................................14Analog Inputs.................................................................................................................................15Analog Inputs Functions............................................................................................................16PWM..............................................................................................................................................17PWM function...........................................................................................................................18Serial Communication (UART)........................................................................................................20UART Functions.........................................................................................................................21I2C Communication Protocol.........................................................................................................23I2C Basic Functions....................................................................................................................23Accessing memory registers of slave devices...........................................................................24RTCC module..................................................................................................................................26RTCC APIs...................................................................................................................................26GSM Task ............................................................................................................................................28Standard Mode..............................................................................................................................28GSM APIs work-flow..................................................................................................................28GSM Events...............................................................................................................................31Network Connection and GSM info...............................................................................................32Manage GSM network connection...........................................................................................32Read GSM Module IMEI............................................................................................................32Code Example............................................................................................................................33Voice Call........................................................................................................................................33CALL APIs...................................................................................................................................34SMS................................................................................................................................................34Introduction..............................................................................................................................34SMS APIs....................................................................................................................................35Internal Flash File System..............................................................................................................35Features.....................................................................................................................................36File System APIs.........................................................................................................................36Data Connections...........................................................................................................................37APN Configuration.....................................................................................................................37Email - SMTP..................................................................................................................................37SMTP APIs..................................................................................................................................373
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comSMTP Error Codes.....................................................................................................................38TCP Client.......................................................................................................................................39TCP Socket.................................................................................................................................40TCP APIs.....................................................................................................................................40HTTP Client.....................................................................................................................................41HTTP APIs..................................................................................................................................41FTP Client.......................................................................................................................................42FTP Socket.................................................................................................................................43FTP APIs.....................................................................................................................................43Power Saving..................................................................................................................................44Hibernate Mode........................................................................................................................44Sleep Mode...............................................................................................................................45Low Level Mode.............................................................................................................................45Low Level Mode APIs................................................................................................................464
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)Flyport GPRSIntroductionFlyport is a programmable system-on-module embedding a Microchip PIC24FJ256 microcontroller and aGPRS transceiver. It has two 26 pin connector to communicate with external electronics and can be poweredwith 3.3 or 5V.The microcontrollers runs the openPicus framework (based on FreeRTOS) that embeds the GPRS stack andthe customer application developed using our free IDE.Flyport can be programmed with user-written firmware to accomplish actions like controlling relays, readingdigital 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 HTMLclient, 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 costminiUSB programmer is available and compatible with Nest expansion boards for Flyport).5
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comBootloaderEach 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 anexternal device which writes new firmware into the flash memory of the microcontroller and controlsthe 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 usingjust 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 theserial 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 theserial port and writes them to the microcontroller memory using an RTSP – real time serialprogramming - technique.QUESTION: The bootloader is located inside the program memory, and it writes inside the programmemory. 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 stopswriting, avoiding “killing” itself. The IDE gives feedback to the user, saying “the code can damage thebootloader, so it has not been written”.QUESTION: The bootloader is another program resident inside the microcontroller. Will it slowdown 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 doesnt slow Flyportdown in any way. It uses just 1k of memory. So there is no real reduction of the available memory foryour application.NOTE: Flyport uses a customized version of the ds30 bootloader. An opensource and lightweightbootloader for PIC microcontrollers http://mrmackey.no-ip.org/elektronik/ds30loader/6
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)PinoutJP1 (connector male 2*13 ways pitch 2.54mm pinheader: SAMTEC TSM-113-01-F-DV )Pin Pin Name Description (default setting) 5V Tolerant Remappable1 p1 GPIO (I2C bus - clock) Yes No2 p2 GPIO (Digital Input) Yes Yes3 p3 GPIO (I2C bus - data) Yes No4 p4 GPIO (Digital Output) Yes Yes5 p5 GPIO (Digital Input) Yes Yes6 p6 GPIO (Digital Output) Yes Yes7 p7 GPIO (Digital Input) Yes No8 p8 GPIO (SPI bus – clock SCLK) Yes Yes9 p9 GPIO (Digital Input) Yes Yes10 p10 GPIO (SPI bus – output SDO) Yes Yes11 p11 GPIO (Digital Input) Yes Yes12 p12 GPIO (SPI bus – input SDI) Yes Yes13 p13 UART RX input Yes Yes14 p14 GPIO (SPI bus – chip select CS) Yes Yes15 p15 UART TX output Yes Yes16 p16 +5V POWER SUPPLY note 1- -17 p17 GPIO (Digital Output) No Yes18 p18 ANALOG INPUT #4 note 2No Yes19 p19 GPIO (Digital Output) → Led OUT4 No Yes20 p20 ANALOG INPUT #3 note 2No Yes21 p21 GPIO (Digital Output) → Led OUT5 No No22 p22 GND GROUND - -23 p23 ANALOG INPUT #1 note 2No Yes24 p24 +3,3V POWER SUPPLY note 1- -25 p25 ANALOG INPUT #2 note 2No Yes26 p26 RESET (active low) No No7
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comJP2 (connector male 2*13 ways pitch 2.54mm pinheader: SAMTEC TSM-113-01-F-DV )Pin Pin Name Description (default setting) 5V Tolerant Remappable1 p27 GPIO (Digital Input) No No2 p28 GPIO (Digital Input) No No3 p29 GPIO (Digital Input) No No4 p30 GPIO (Digital Input) No No5 p31 GPIO (Digital Input) No No6 p32 GPIO (Digital Input) No No7 p33 GPIO (Digital Input) No No8 p34 GPIO (Digital Input) No No9 - - -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 internalLDO. 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 maximumvalue 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
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)Hardware functionsThis chapter shows how to control the hardware of Flyport: the digital IOs, the analog inputs, how to createPWM and how communicate with other devices or peripherals.QUESTION: Usually to control the hardware of an embedded device it is required to know specific registersand 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 withoutany knowledge about microcontroller hardware registers.Digital Inputs and OutputsFlyport provides lot of Digital Input/output pins to control devices such as Led, Relay, buttons andmore.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 anumber 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 outputIOInit(p6,in); //Initialize pin 5 as digital inputwhile (1){// MAIN LOOP}}9
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comDigital I/Os FunctionsFirst 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 Inputpin 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 Flyports 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 resistorwe connect the pin to a low voltage reference (ground). Of course you can always change the inputvalue with another voltage source, or with a switch, as shown in the figure below:10
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)In the pull-down circuit of the figure, we can see that when the switch is opened (no other sourcesare connected), the input pin “reads” a low voltage value. If we close the switch (and connect a highvoltage 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 isclosed, 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 themicrocontroller, 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 releasedinup ON to OFF OFF to ONindown OFF to ON ON to OFFCheck the state of a pushbutton → IOButtonState(pin name)Returns: pressed if the button has been pressedreleased if the button has been not pressed or releasedYou dont have to keep track of the state of the pin, or of its logical value. The openPicus frameworkdoes this work for you and tells you if the button has been pressed or released.11
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comExample: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, checkthe table above. In the case of an “inup” resistor substitute “OFF” (that is a low voltage level). In thecase 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 switchesbut with a small amount of software, problems with bounce can be solved.The IOButtonState has an integrated de-bounce feature, so you dont have to worry about thisproblem.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 valid12
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)Remappable PinsA 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 peripheralthe list below shows the functionalities you can associate to every pin.QUESTION: What are the various assignable functionalities on Remappable pins? How are theynamed?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_CLKWith the Flyport module pinstrip connector more expansions with different pinouts can be createdjust by using the remapping feature. As a result the layouts of Flyport expansion boards can simplerand easier to route on PCBs, breadboards or any prototyping board type.The pin configuration depends on your specific application, so the “Hardware Architecture” shouldbe decided first: which pins will be used as peripherals, and which pins will be “simple I/Os”13
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comRemappable Pins FunctionsTo REMAP a pin you can simply use the IOInit function. The difference between the digital I/Os andPeripheralPinSelect 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, theIOGet and IOPut will not work properly. Secondly, after the assignment, a new function will beassociated to a pin, and it must be used the related peripheral functions to set up the peripheralmodule.For example UART2 and UART3 are not enabled by default to give more memory to the userapplication. If you need to use 3 UARTs in your application, you must enable these 3 UARTs using theWizard 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 dont change during the development. Rememberthat 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
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)Analog InputsFlyport 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 ananalog 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 is2,048/1024=2mVFor example and Analog Read value of 1000 means:1000 * 0.002 V = 2V of voltage on the analog inputNote: Analog input pins may be used also as GPIO, but they are not 5V tolerant! Avoid to apply avoltage > 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. Thisconfiguration is made to reduce the max voltage of the Analog input pin. In fact, when thepotentiometer reaches its max value on the analog pin we have:Va1_in = Vdd * (R1 / R1+R2) = 3.3 * (1000 * 1680) = 1,96VThis value is compatible with the voltage input range of analog inputs (max 2,048V)15
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comAnalog Inputs FunctionsRead an Analog Input → ADCVal(channel);This function returns an int value (from 0 to 1023) related to the Analog channel (from 1 to 4) asreported on the pinout table.Parameters:channel:specify the ADC input channel (1 to 4)Example:int myADCValue; //Initialize the variable to get the valuemyADCValue = ADCVal(1); //Returns the value of the Analog channel #116
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)PWMFlyport 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 cycleis variable. The duty cycle is the ratio between the high level period duration and the low level periodduration, 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 aperfect 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 ofthe 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 = 5msSo 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 msQUESTION: How can I use PWM signals?Normally PWM signal is used to drive a Led or a DC motor. Its possible also to create “virtual” analogoutput signal. Note that PWM is not a DAC (digital to analog converter), but a simple way to generatean analog signal adding some R-C filtering. The R-C filter design is a relatively complex operation thatdepends on the frequency of the PWM and on the load at the output pin.17
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comPWM functionThere 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 moduleParameters: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 PWMduty cycle we change the root mean square (RMS) voltage of the signal, so we can change thebrightness 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 pin5PWMDuty(50, 1); //Change the duty at 50% (about half bright)18
  • www.openpicus.com FLYPORT GPRS Programmers 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_modulation19
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comSerial Communication (UART)The UART is a serial asynchronous communication module to communicate with an external devicesuch 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 dont have topoll 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 willshow 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 miniUSBprogrammer as Reset signal).20
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)UART FunctionsFirst 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 thiscase 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 thebaudrate parameter at runtime.Parameters:port: The UART port to initialize (from 1 to 3)baud: Desired baudrateTurn on the UART → UARTOn(int port);This function turns on the UART functionalities. It should be called only after UARTInitParameters:port: the UART port to turn onTurn 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 offCheck the UART input buffer → UARTBufferSize(int port);This function returns an int number equal to how many chars have arrived and are stored inside theUART RX Buffer.Parameters:port: the UART portReturns:int N: number of chars inside the bufferRead the UART input buffer → UARTRead(int port, char *towrite, intcount);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
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comSend 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 writeFlush the UART input buffer → UARTFlush(int port);This function clears the buffer of the specified UART port.Parameters:port: the UART port22
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)I2C Communication ProtocolI2C is a 2 wire serial communication widely used in embedded electronics to connect devices such asexternal memory and more.Unlike the UART, I2C has a Master-Slave architecture, where the Master starts all the requests ofcommunication. The baud rate is given by the Master, and the most used values are 100kb/s (lowspeed) and 400kb/s (high speed).I2C bus needs pull-up resistors and dedicated open collector pins. This is the reason why the I2C pinsare not remappable.To use the I2C protocol has s a determined sequence of operations for starting, stopping, write, readand checking if the data was transmitted ok.For more information see the link:http://en.wikipedia.org/wiki/I%C2%B2COpenPicus framework offers some functions to easily manage the I2C communication, using Flyportas a Master. In this way it’s possible to communicate with I2C slave devices and read/write theirregister. It’ possible to attach more than one device on the bus, since I2C uses addressing. The onlyissue is to check that any device connected on the bus must have a different address.I2C Basic FunctionsInitialize 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:noneSend a Restart condition → I2CRestart();This function resends a start sequence on the I2C bus.Parameters:noneSend a Stop condition → I2CStop();This function sends a stop sequence on the I2C bus.Parameters:none23
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comWrite 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 detectedAccessing memory registers of slave devicesThe easier way to communicate with a I2C device, is using the ready-to-go functions offered by theOpenPicus Framework to read/write registers. Using the following functions, you dont need to knowthe 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 thestandard way to read/write registers on I2C bus, if you experience any problems, always refer to slavedevice 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 I2Caddress of the device. You can find the default address and how to change it in the datasheet of eachI2C device. The address will be correctly shifted and added with the read/write bit by the read/writefunctionsRead 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 operationsperformed. This delay is needed by some I2C devices (please see slavedatasheet 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
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)rwDelay: The delay (expressed in 10us) between write and read operationsperformed. This delay is needed by some I2C devices (please see slave datasheetfor further info)Returns:BOOL result of operation: TRUE → operation success, FALSE → operation failedWrite 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:NoneReading 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 failedNote: more examples of I2C functions usage are available at wiki.openpicus.com25
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comRTCC moduleRTCC – Real Time Clock Calendar – is a hardware clock module embedded on Flyport. It providesautomatic clock counter and customizable interrupt driven alarm.Using openPicus framework libraries its possible to read and write values of RTCC date and time andset am alarm. Alarm event can be both assigned to a callback function, or read in a dedicated statusfunction.RTCC APIsInitialize/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 setRead 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 dataConfigure 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 foreverwhenToRaise: 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 yearfptr: custom function to execute when alarm event is raised. Use NO_ALRM_EVENT to ignore.26
  • www.openpicus.com FLYPORT GPRS Programmers 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 alarmtrigger.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
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comGSM TaskOpenPicus framework integrates the stack with FreeRTOS operating system, to ease the management of anyGSM/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 therequired AT commands, parses responses, and also manages asynchronous messages. In this way, developerdoesnt 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 requestedfor 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 usershould keep track of all the messages on GPRS dedicated serial port, specially all the asynchronous messagessent by GPRS Module for network events.Standard ModeIn Standard mode, all the serial commands (AT commands) between PIC Microcontroller and GPRSModule are processed inside the “GSMTask”. In this way, user application can be independent fromGSM 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 Moduleare analysed by GSMTask, and dedicated events are executed automatically to perform differentactions. Unsolicited messages are asynchronous messages sent by GPRS module to inform masterdevice (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 LowLevel Mode, GSM Events functions will NOT be executed. The message parsing and detecting is leftto user firmware if Low Level mode is enabled!GSM APIs work-flowSince GSM module response to certain AT commands can be really slow (timeouts of up to 120seconds are necessary), it is mandatory to provide framework APIs of a different structure respectFlyport Wi-Fi and Ethernet.To permits GSM Task to handle incoming data, and execute Flyport Task requests APIs execution, allthe UART data exchanges are handled using multitasking architecture. This means that all thefunctions provided does not response directly with values, but its execution is performed inbackground. This permits to create user applications that continue them operations while waiting forGPRS commands to finish.28
  • www.openpicus.com FLYPORT GPRS Programmers 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 forGPRS_API_function function execution• When GSM Task finishes GPRS_API_function execution, it sets Execution Status to the resultof 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 andEthernet), 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 DescriptionOP_SUCCESS 0 Last function executed correctlyOP_EXECUTION -1 Function still executingOP_LL -2 Low Level mode is activateOP_TIMEOUT 1 Timeout error: GPRS module has notanswered within the required timeout forthe operationOP_SYNTAX_ERR 2 GPRS module reported a “syntax error”messageOP_CMS_ERR 3 GPRS module reported a CMS errorOP_CME_ERR 4 GPRS module reported a CME errorOP_NO_CARR_ERR 5 GPRS module reported NO CARRIERmessageOP_SMTP_ERR 6 Error in sending the emailOP_FTP_ERR 7 Error message received in FTP operationOP_HIB_ERR 8 GPRS module is turned off and cannotreply to commandsUsing LastExecStat() function it is possible to develop Flyport Task firmware in a both blockingmanner and non-blocking manner.Following are two basic examples of blocking and non-blocking code:29
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comTCP 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”);elseUARTWrite(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”);elseUARTWrite(1, “Operation NOT succeeded”);}30
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)GSM EventsAll the provided events functions are stored inside the file “GSM_Events.c”. This permits the user tocustomize the response to each kind of asynchronous stimulus differently, for example if the event isan 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 foran Incoming Call). It provides the phoneNumber (if any) that excited the RING.OnNoCarrier (char* phoneNumber) – executed when the NO CARRIER message isreceived. It could be excited from a hang up from the phone number who sent the call, or if aTCP connection was lost.OnBusy (char* phoneNumber) – excited if Flyport reaches BUSY signal on phoneline.OnSMSReceived (char* memtype, int index) – this event is a notificationform new SMS received. It provides related storage memory type, and position index.OnSMSSentReport (int msgreference, int msgreport) – if user sends amessage with delivery report, this event will be executed when the delivery SMS fromoperator is received. It provides related message reference number, and delivery reportvalue.OnError (int error, int errorNumber) – Every kind of ERROR messagesreceived 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 notallowed3 - 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 asresponse6 - OP_SMTP_ERR: “+KSMTP ERROR : ...” message → SMTP error notexpected7 - OP_FTP_ERR: “+KFTP ERROR : ...” message → FTP error not expectedint errorNumber: Number of the error (if provided)31
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comOnRegistration (BYTE Status) – event executed every time the connection tonetwork (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 modeThose functions are called inside “GSM Task”, and can be customized to perform actions. Bythe way, there are limitation applied to this structure: all the operation executed insidethose functions MUST NOT call other GSM Functions. Also their execution should be asfaster 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 callthe related hang up function ( CALLHangUp() ) from user task.Network Connection and GSM infoManage GSM network connectionFramework supports a function to manually retrieve network connection status of GSM module.BYTE LastConnStatus() → In addition to OnRegistration event, user can read last connectionstatus 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 modeRead GSM Module IMEIIMEI number (international mobile station equipment identity) is a unique number to identify eachdifferent GSM module. Reading this number, every Flyport GPRS will have a unique ID number notrelated to phone number.char* GSMGetIMEI() → returns the string containing IMEI number. Its maximum size is 16chars.32
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)Code ExampleFollowing is a code example to use above functions inside FlyportTask. Using this example, userapplication 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, itturns ON.Also messages of welcome, and IMEI are printed on UART1 (the default UART used for generic debugof applications).#include "taskFlyport.h"void FlyportTask(){UARTWrite(1,"Flyport Task Started!rn");// wait for registration successwhile(LastConnStatus() != REG_SUCCESS){vTaskDelay(20);IOPut(p21, toggle);}// Connected!UARTWrite(1, "Flyport connected to GSM network!rn");IOPut(p21, on);// Print IMEI number on UART1:UARTWrite(1, "IMEI: ");UARTWrite(1, GSMGetIMEI());UARTWrite(1, "rn");while(1){}}Voice CallFlyport 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
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comMicrophone input and headphone output are provided on JP2 connector; more info are available onSAGEMCOM website for further reference.CALL APIsCALLVoiceStart (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 anumber 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 callSMSIntroductionFlyport 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 ReferenceEvery 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 isreceived, the index and memory type is overwritten.To access to the above parameters, the following functions are available from Flyport Taskchar* LastSmsSender () → returns char* to the string containing phone number of lastreceived SMS sender.34
  • www.openpicus.com FLYPORT GPRS Programmers 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 internalmodule memory is used.int LastSmsIndex () → returns position index of last smsstruct tm LastSmsTime () → provides information about sms date and timeint LastSmsMsgRef () → returns message reference number of SMS sentint LastSmsRepValue () → returns report value of SMS sentSMS APIsFollowing are explained functions to handle SMS functionalities.SMSRead (int indexMsg, BYTE memType) → reads SMS content on provided index andmemory type, and fills the SMS data structure. Once finished, all the parameters will be accessibleusing the functions explained above.SMSDelete (int indexMsg, BYTE memType) → deletes the SMS at provided index andmemory type.SMSSend (char* phoneNumber, char* text, BOOL ack) → Start the SMS sendingprocess. This function overwrites SMS data structure parameters.Parameters:phoneNumber – destination phone numbertext – content of text message. It must be a char[] of max 160 chars, or above chars will beignored.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 costscould be applied by mobile operator).Internal Flash File SystemGSM 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
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comFeaturesThis file storage can be freely used by user application. It is also used by openPicus framework toexchange files with remote FTP Servers. All files downloaded from a FTP are stored inside moduleflash memory, and all files to be uploaded to FTP server should be written of internal flash memorybefore to perform data exchange process.User can create, read, modify and delete files stored using the following functionsFile System APIsFSWrite (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 writeFSRead (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 readFSDelete (char* filename) → Deletes a file from memory.Parameters:fileName – char[] with name of file to be deletedFSSize (char* filename, int* dataSize) → Writes data on a file. If files exists, thisfunction 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 write36
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)Data ConnectionsTo perform TCP/IP based connections, mobile operator APN parameters must be configured onFlyport GPRS.Pay attention: every mobile operator provides their own settings. So different SIM card could needdifferent setting of APN parameters.APN ConfigurationThe 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 IPassignmentdns1 – IP address of primary DNS Server. Please use “DYNAMIC” for dynamic IP assignmentdsn2 – IP address of secondary DNS Server. Please use “DYNAMIC” for dynamic IPassignmentNOTE: To set APN parameters is mandatory for any TCP/IP based operation (TCP, HTTP, SMTP andFTP). Please be sure to configure them properly before use TCP/IP based functions.Email - SMTPFlyport GPRS can send emails using data connection. Despite that, it is mandatory to be sure to use aSMTP service that do not require SSL security connections. Make sure to use a SMTP port that allowsto 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” destinationaddresses, and up to 2 “Cc” copy destination.SMTP APIsEvery SMTP Email sending has a session_id provided by the SMTPEmailSend function. To retrieve lastsession id number it can be used the following function:int LastSMTPSessionId() → returns last session idSMTPParamsSet(char* smtpDomain, int smtpPort, char* senderEmail,char* smtpLogin, char* smtpPassw) → Sets SMTP Server parameters. If a parameter is37
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comnot requested, please use the NOT_REQUESTED value.ParameterssmtpDomain – 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 loginSMTPParamsClear() → Clears SMTP parametersSMTPEmailTo(char* toDest1, char* toDest2, char* ccDest1, char*ccDest2) → Sets destination recipients. To ignore destination, please use SMTP_NO_DEST value.ParameterstoDest1 – address of first email destinationtoDest2 – address of second email destinationccDest1 – address of first copy destinationccDest2 – address of second copy destinationSMTPEmailSend(char* subject, char* text) → send the email with provided subjectand body text content.Parameterssubject – char[] containing subject of the email. Max 255 chars can be used.text – char[] containing body text of email.SMTP Error CodesHere is a table of possible SMTP error code and them meaning:Error Meaning3000 Invalid SMTP server name.3001 Invalid address identification3002 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 sender3020 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
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)Error Meaning3041 The SMTP transfer failed due to TCPconnection troubles.3042 The SMTP transfer failed due to server TCPconnection error.3043 The SMTP download failed due to Requesttime out.3044 The SMTP transfer failed due to SMTP protocolerror.3045 The SMTP transfer failed due to DTR drop.3049 The SMTP transfer download failed due tointernal error.3050 The SMTP transfer failed due to SMTP servertrouble3051 The SMTP transfer failed due to internalmemory not available3052 SMTP connection time out3053 SMTP Raw Data upload to Module time out3054 DNS Server address error or failed to resolvethe host address3055 SMTP client need Hardware flow controlTCP ClientTCP, Transmission Control Protocol, is a packet oriented protocol. It can be used to transmit andreceive packets of data through the network between server and client.• To use this kind of transmission, server and client should establish a connection. Since theconnection between server and client consumes network resources (exchanging protocolservice 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 Clientrole.• The TCP/IP transmission is “full-duplex” capable, and all the packets sent arrive in sourceorder and “at most once”.• By using acknowledgement, timeouts and checksums, the TCP protocol can check theintegrity 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, whichwe will call the “TCP_SOCKETs”.39
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comTCP SocketEvery TCP Connection is identified by its TCP_SOCKET. In Flyport GPRS a TCP_SOCKET variable is abit 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 bufferThose values can be updated using the TCPStatus function, that will be explained later.TCP APIsTCPClientOpen(TCP_SOCKET* sock, char* tcpaddr, char* tcpport) → opens asocket inside GPRS module, and starts the connection with TCP Server.Parameters:sock – tcp socket variable to use. NOTE: remember to use the “&” operator with thisparametertcpaddr – char[] with IP address or host name of TCP Servertcpport – char [] with port of TCP ServerTCPClientClose(TCP_SOCKET* sock) → closes connection to TCP Server, and deletes thesocket from GPRS module.Parameters:sock – tcp socket variable to use. NOTE: remember to use the “&” operator with thisparameterTCPStatus(TCP_SOCKET* sock) → updates the values of TCP_SOCKET struct.Parameters:sock – tcp socket variable to use. NOTE: remember to use the “&” operator with thisparameterTCPWrite(TCP_SOCKET* sock, char* writech , int wlen) → writes datacontained inside provided buffer to Server.Parameters:sock – tcp socket variable to use. NOTE: remember to use the “&” operator with thisparameterwritech – buffer with data to send to TCP Serverwlen – amount of data to sendTCPRxFlush(TCP_SOCKET* sock) → flushes all data incoming to TCP RX buffer of GPRS40
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)module.Parameters:sock – tcp socket variable to use. NOTE: remember to use the “&” operator with thisparameterTCPRead(TCP_SOCKET* , char* readch , int rlen) → read data from TCP RX bufferof GPRS module and puts it to provided buffer.Parameters:sock – tcp socket variable to use. NOTE: remember to use the “&” operator with thisparameterreadch – buffer to fill with data to read from TCP RX buffer of GPRS module.rlen – max amount of data to readHTTP ClientHTTP Client library permits to easily perform GET and POST requests to HTTP Server. Basically a HTTPrequest is a particular TCP Connection. HTTP Client Requests data must be sent following a specificprotocol. Using the provided functions, user does not have to bother on request header datapreparation, reducing the possibilities of errors.HTTP Client uses TCP_SOCKET structures, and its functions are similar to TCP Client functions. Also onHTTP libraries user can update TCP_SOCKET parameters using HTTPStatus function.For more info about TCP_SOCKET variable, please read the TCP Socket chapter.HTTP APIsHTTPOpen(TCP_SOCKET* sock, char* httphost, char* httpport) → opens asocket inside GPRS module, and starts the connection with HTTP Server.Parameters:sock – tcp socket variable to use. NOTE: remember to use the “&” operator with thisparameterhttphost – char[] with IP address or host name of HTTP Serverhttpport – char [] with port of HTTP ServerHTTPClose(TCP_SOCKET* sock) → closes connection to HTTP Server, and deletes the socketfrom GPRS module.Parameters:sock – tcp socket variable to use. NOTE: remember to use the “&” operator with thisparameterHTTPStatus(TCP_SOCKET* sock) → updates the values of TCP_SOCKET struct.Parameters:sock – tcp socket variable to use. NOTE: remember to use the “&” operator with thisparameterHTTPRequest(TCP_SOCKET* sock, BYTE type, char* reqUrl, char*41
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comdata2snd, char* param) → sends HTTP Request with provided parameters and data.Parameters:sock – tcp socket variable to use. NOTE: remember to use the “&” operator with thisparametertype – 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 notneeded, please use the value HTTP_NO_PARAMHTTPReadData(TCP_SOCKET* sock, char* dataBuffer, int datalen) → readdata 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 thisparameterdataBuffer – buffer to fill with data to read from TCP RX buffer of GPRS module.datalen – max amount of data to readFTP ClientFTP Client (file transfer protocol) can handle the file exchange between Flyport and PC. Big files cantbe 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 thosecommands 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 TCPConnections at certain ports.Generally FTP Servers uses port 21. If your Flyport GPRS cannot reach FTP server at this port, youshould try with others (for example 25), but you need to control FTP Server parameters (or ask to FTPServer 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 datatransfer (call it “Data Socket”). Using Flyport GPRS, user do not need to handle two differentconnections, since them are automatically used by GPRS module.FTP passive mode starts with only one TCP connection, using “Cmd Socket”. Once connected, FTPClient device (in this case Flyport module) executes login to FTP Server and asks it to enter in passivemode, and provide info about the “Data Socket”. Then FTP Server reply with info about IP addressand 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 mobile42
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)operator applies firewall (or limitations) to the ports used by Data socket, you will mostly fail on filetransfer.Again, be sure to set used FTP Server with ports supported by your mobile operator, or ask to FTPServer admin or to your mobile operator to provide you more information on your connectionlimitations.FTP SocketTo perform FTP File exchange a FTP_SOCKET variable is used. In Flyport GPRS a FTP_SOCKETvariable 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 (onlyone at time can be used with Flyport GPRS)• ftpError → last FTP error code received (if any).FTP APIsFTP functions integrated on current release of openpicus framework, uses GPRS Flash file system asfile storage of FTP protocol. So, you can exchange (upload / download) file from FTP Server to GPRSmodule 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 alwaysbefore the execution of the other functions, since every FTP Operations closes connections and deletessockets 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 areacceptedlogin – char[] containing username to execute login on FTP Server. NOTE: max 255 chars areacceptedpassword – char[] containing password to execute login on FTP Server. NOTE: max 255 chars areacceptedportNumber – WORD of port of FTP Server to execute connection. NOTE: This port must be acceptedby your mobile operatorFTPReceive(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 downloadFTPSend(FTP_SOCKET* sock, char* flashFilename, char* serverPath, char*43
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comserverFilename, BOOL appendMode) → Sends a file from GPRS module to FTP Server. Canoverwrite 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 contentFTPDelete(FTP_SOCKET* sock, char* serverPath, char* serverFilename) → Deletesa 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 SavingFlyport 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 functionswith GPRS module will be ignored. Using sleep mode only external interrupts and RTCC can wake upmicrocontroller.Hibernate ModeThis 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 peripheralmodule” 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 GSMNetwork.To Deactivate the Hibernate Mode → GSMOn();This function turns ON GPRS Module and initializes it to start connection to GSM Network.44
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)Sleep ModeThis is the more efficient available power saving working mode. Since it locks almost all the power ofthe 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 themicrocontroller to wake up from a sleep condition. It is not important what the ISR related functionsdo, the important point is that they are activated from external events(the RTCC alarm can be seen asan 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 microcontrollerworking.To Deactivate Sleep ModeOnly RTCC and external interrupts can deactivate the sleep mode.Low Level ModeLow Level mode was integrated to permits user to self manage AT commands between PICmicrocontroller and GPRS Module.Adding this flexibility, openPicus Framework must be sure to interacts with GPRS module at certainsettings condition. So, EVERY TIME user uses Low Level mode, and returns to Standard mode, GPRSmodule is reset and again initialized. So, any GSM/GPRS operation data will be loose (for example TCPsockets, or call in progress).Be carefully using this mode, but most of it, be sure you can reset and init again GPRS module beforeto enable again Standard mode.Similar to the other UART of the openPicus Framework, using Low Level mode user can takeadvantage of a buffered GSM dedicated UART of 1512 BYTEs, and a smart Interrupt service routine tofill the buffer automatically at every byte of data received.Almost all the functions developed for UART peripherals are available to communicate with GPRSmodule 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 microcontrollerand GSM module on Flyport GPRS system-on-module circuitry.45
  • FLYPORT GPRS Programmers guide (rev 1.0) www.openpicus.comLow Level Mode APIsLow 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, aHilo reset is performed, so any data / voice connection is lostLLFlush() → Flushes GPRS module dedicated UART buffer data. NOTE: Works only in Low Levelmode!LLBufferSize() → Gets GPRS module dedicated UART buffer size. NOTE: Works only in LowLevel mode! If used in Standard mode, will return -1LLRead(char *buffer , int count) → Reads data from GPRS dedicated UART buffer andfills 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 readReturn:int – amount of data actually read from buffer.LLWrite(char *buffer, int count) → Writes data to GPRS dedicated UART. NOTE: Worksonly 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 benot locked waiting for end of operation;Parameters:buffer – char [] with data to be writtencount – amount of chars to be writtenLLWriteCh(char chr) → Writes a single char to GPRS dedicated UART. NOTE: Works only inLow 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 benot locked waiting for end of operation;Parameters:chr – char with data to be writtenLLReset() → Performs a Reset of GPRS module. NOTE: Works only in Low Level mode! If used inStandard 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 setLLDcd() → Reads DCD signal state of GPRS module dedicated UART internace. NOTE: Works only inLow Level mode! If used in Standard mode, FALSE value will be returned.Returns:46
  • www.openpicus.com FLYPORT GPRS Programmers guide (rev 1.0)BOOL – value of DCD signal.LLDsr() → Reads DSR signal state of GPRS module dedicated UART internace. NOTE: Works only inLow 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 inStandard mode, no operation will be performed.47