Contacts Downloads Technical Notes
Overview:
Bluetooth is playing a very important role in term of short long communication .such an important role push developers to improve it better and faster for new requirement of the market ,the success of BLE is similar to success of USB and its fast versioning .The main focus on this topic is to introduce the steps to design a custom BLE solution or add BLE support to your current application .
[In this document when I mention BLE , i refer to BLUETOOTH LOW ENERGY 4.X]
According to standard specification the new version of BlueTooth technology relayed on the concept of Low Energy It means using a single cell coin battery as power source, a BLE device's life could be extended to several years.there are many advantages and a few weakness of BLE 4 , It dosn’t support audio streaming , so if you’re planning to support an audio streaming device ,BLE is not a good solution for you, the way it works is based on transferring small packet data through signal events , but the good latency of signals with fast transaction 3ms from start to finish probably recompense this low data rate in communication, it sleeps when no event or communication is on going, in sleep mode it consume less than 1 µA , and wakeup if necessary.From many aspects BLE is different from a Classic BT ,more connectivity range, low energy consumption ,in the table below you see those difference,BLE is low cost and easy to implement ,don't be surprised if I say the battery will cost more than the electronics!
To wrap up this overview ,before starting your project you have to know, BLE is designed for sending small chunks of data that's why BLE is not advised for File Transfer operation specially when processing big files,it cannot handle it as we expect and as we get used with WIFI, once again notice BLE is perfect for kind of devices based on command with small packet data to carry out,with minimum time processing, BLE is not designed to execute heavy calculation and math processing ,those things should be delegated to Master device rather than slave BLE , this point is very important your BLE device is there to hand you the data you need and not to process or execute them , any mathematical operation and/or presentation of this data is to be implemented on Master side.Later when you write and download your codes into device's firmware be careful to not implement huge routines which make processor busy for a relative long time.
Below a list of known Use Cases
1- Proximity detection,presence detection 2-Time 3-Emergency 4- Network availability 5- Personal User Interface 6- Simple remote control 7-Browse over Bluetooth
8- Temperature Sensor 9- Humidity Sensor 10- Generic I/O (automation) 11- Battery status 12- Heart rate monitor 13-Physical activity monitor
14-Blood glucose monitor 15- Cycling sensors 16-Pulse Oximeter 17-Body thermometer
As you see the volume of data transferred in each transaction in BLE is less than a classic BT! however you notice that even if BLE perform a smaller data packet in a single transaction , the transactions occurancy in BLE is higher than a classic BT , this acceptable latency makes the difference and put it on top of the short range communication protocol.
In this topic we're not going to discover all those details in every corner of this marvelous technology but we need a minimum knowledge to start a successful project around BLE,things like how BLE communicates to outside world is the first step to implement it in our solution.
Bluetooth devices currently available in market either they support BLE or not, are divided by 3 categories:
Classic Bluetooth (Legacy):
is classic generation from 1.x to 3.x
Bluetooth Smart :
is new generation known as BLE v4.x,they are not backward-compatible with previous Classic Bluetooth
Bluetooth Smart Ready:
indicates a dual-mode device compatible with both Classic and low energy peripherals.
Bluetooth Smart indicates a low energy-only device which requires either a Smart Ready or another Smart device in order to function.In IT Jargon,sometimes professional use "Central" and "peripheral" Centeral refers to any smartphone,tablette,...and peripheral is the BLE device attached to it.other term usually in this jargon are [Master] and [slave], Master refer to Smartdevice ,tablette,...which control the device , and Slave is the BLE device
[notice : A Slave cannot have two Master at the same time]
Other interesting feature unique to BLE device is the ability to get enough information about device even before connecting ,this feature is exploited by professional to push advertizing over it.Advertising is the primary way a peripheral device make its presence via Bluetooth LE.
Advertising packets are very small ,broadcasted by BLE device to nearby , this feature allow master devices (smartdevice)to be able to retrieve enough information before connecting.notice that in any case the connection is initiated by Master , so it’s up to master device to decide wether to connect or not.Advertising packets contain useful data, such as the peripheral’s name. It can also include some extra data related to what the peripheral collects. For example, in the case of a heart rate monitor, the packet also provides heartbeats per minute (BPM) data.The job of a central is to scan for those advertising packets, identify any peripherals it finds relevant, and connect to individual devices for more information.
During the lifecycle of connection or advertizing all communications are asynchronous.
Topology :
As design classic Bluetooth Master can be connected to up to 7 slave devices simultaneously , however according to SIG specification this limit is not defined for Blue tooth Low Energy(BLE) but it seems to have a practical limitation since in Advertizing phase BLE consume energy and by higher number of devices that may be a major challanging to the principal of Low Energy, so from topology state , A Slave can only be connected to one Master at a time but a Master can be connected to an unlimited (undefined) number of Slaves , A Master could be playing the role of Slave at the same time, there is no any direct communication between two slaves , no direct connection , therefore for such a scenario , Slave must use a Master as a bridge to achieve that as shown here:
Hardware design :
According to SIG (Special Interest Group ), BLE is using the same frequency range as Classic BT(and also WIFI) ,From 400 GHz to 2.4835 GHz ISM band=> delta =0.08GHz=80MH pass band , this 80MHZ is distributed as channels ,In BlueTooth classic this range is divided into 79*1MHz (79 channels)
however In BLE this range is divided into 40*2MHz (40 channels) within these 2 MHZ we can send or receive BLE data.channels (37,38,39) are used for advertizing & discovery service in different part of spectrs to ensure safety against interference, the rest are data channels , once connection established and initiated data channels are used instead.
BLE device communicates with smart devices (masters) trough events signals every transaction of data or advertizing occurs in the interval of around 3ms , data is dispatched on multiple channels , advertizing are carried out by 3 channels 37,38,39, the following diagram taken by TI (Texas Instrument) show this communication
BLE device signals are transfered with GFSK modulation GAUSSIAN FREQUENCY SHIFT KEYING, I briefly describe the principal of GFSK modulation to better understand the signal pattern of a BLE device .GFSK is Gaussian FSK which mean it's derivation of FSK modulation by passing signals throgh a Low Pass Filter ,
GFSK modulation is generated by previously filtering signals before sending it to FSK Modulator
A Gaussian Low Pass Filter get input sigals before sending it to FSK Modulator so the Frequency Resonse Function in more detail is shown here
The reason why GFSK has been adopted for BLE is the fact that it's well behaved in therm of useful particularity of a Gaussian signal in which the frequency response impulse and time response both are Gaussian, by makin inverse Fourier we get what is shown below
you see the result and comparaison of both modulation in Fig.As you see communication signal for a BLE
The data packets transferring profiles[Services+Characteristics+descriptors...] (known as ATT/GATT) are carried by this Gaussian signal in Physic Layer ,remember that in physic layer Logic BLE data packets(Services) are encapsulated with additional data , headers and CRC added by other layers as shown here
This data is provided to physical support but we don't care about it , we should focus on data structure at Application level, at profile level, service retrieving ....etc our job is not to analyse the management of other layers such as Link ,Physic,.. , because each layer is managed separately by its own protocol manager , i wanted to show a full schema of what's going on in a real world just to let you figure out how is a real communication in action!
Logic layer:
In Networking & Communication ,stack of different layer to carry out data is represented as following figure:
GATT/ATT [Generic Attribute Profile/Attribute Protocol]
This pair is the two main concept of BT4 transported data packet are named characteristics/services, Profils are a collection of services, a service a collection of Characteristics and a Characteristic a collection of descriptors and a value.BLE communication is based on exchange of attributes between two devices through services,
Services:
There services are kind of interfaces in form of data structures including profiles linked to a given function supported by the sensors A service contains one or more Characteristics and each Characteristic contains a value and one or more descriptors.Indeed Services are used to break data up into logic entities, and contain specific chunks of data called characteristics. A service can have one or more characteristics, and each service distinguishes itself from other services by means of a unique numeric ID called a UUID, which can be either 16-bit (for officially adopted BLE Services) or 128-bit (for custom services).
Charactersitics :
are generally the properties of the sensors, measured and reported by sensors , a Characteristic has many readable/writable attributes but a single value, this value represents a real human physical value measured by a device's sensor , when an attribute or Characteristic is writable it can be used both server or client in order to setup a handler,enable a notification or configuration or even to set a feature on device.Every attribute has a UUID which is formatted as a 16 bit or 128 bits unique numbers, 16 bits are reserved and defined by Bluetooth SIG, however 128 bits,are custom and free to be used for any purpose! if you're planning to provide a custom BLE device ,use 128 bits values , you will see later how to download a custom firmware on a BLE module.The lowest level concept in GATT transactions is the Characteristic, which encapsulates a single data point (though it may contain an array of related data, such as X/Y/Z values from a 3-axis accelerometer, etc.).
Descriptors:
descriptors are informations related to characteristics value for example if this value is a temperature, descriptors tell us a description of the value Ex:"Temperature" another descriptor may return us the unity of this value Ex"°C" or "°F"
In Pseudo code we can represent a Value as this data structure
struct values{
propertyA;
propertyB;
....
config cfg;
}
UUID:
uuid are unique identifiers for every single Service or Characteristic implemented on the device,as I said they are either Custom or defined by the chip maker/provider , when a Master device or an application is connected to a BLE device , the first thing should be performed is to retrieve all services and characteristics of BLE device , informations provided by BLE device at this time includes UUIDs of all services & characteristics, if later Application needs to communicate to a specific characteristic, it will do it by previously provided uuid of that specific Characteristics.Here an example from Nordic SemiConductor the following uuids are defined for measure of "Battery Level" , "Glucose" and "Heart rate" [by a medical device sensor] , "Temperature"
#define BLE_UUID_BATTERY_LEVEL_STATE_CHAR 0x2A1B
#define BLE_UUID_GLUCOSE_MEASUREMENT_CHAR 0x2A18
#define BLE_UUID_HEART_RATE_MEASUREMENT_CHAR 0x2A37
#define BLE_UUID_TEMPERATURE_MEASUREMENT_CHAR 0x2A1C
Suppose your device is a Medical smart sensor from Nordic SemiConductor ,and your application is a smartphone application to read and display and probably calculate data As I mentioned
Once you are connected to your medical device , to read GLUCOSE value or Heart rate value
you perform a READ request to related Service (which in turn linked by its own UUID) and you provide uuid of such a characteristic in your READ request (Refer to programming section).
The concept of Service & Characteristics & Attributes are very similar to USB communication
In USB the channel of communication are based on Interface ,Endpoints …
One of the most likely feature supported by some BLE devices chipsets is OTA downloading,OTA stands for Over_The_Air , so we can upgrade the BLE device's firmware wirelessly through the Bluetooth connection.generally the update is done by an application installed on a smart devices (smartphone Android or IOS)
Notice:
You can only scan for Bluetooth LE devices or scan for Classic Bluetooth devices, as described in Bluetooth. You cannot scan for both Bluetooth LE and classic devices at the same time.
Development:
When we are planning to support BLE in our products ,since a BLE device is used in a Client-Server environment , before making any decision we have to make things clear , are we going to develop a Client or A Server?,a Master device or a Slave device?
In both case we have at least one of 3 scenarios as mentioned below:
1) We are a vendor of BLE modules so we are going to design a custom BLE module from scratch.
2) Our device is a BLE device we purchase an already existant module then we customize it by flashing Firmware
3)we purchase an already existant device then we support it on our own products, without any customization.
In the first case as a vendor our development consists of design a new Hardware ,implements electronic components in full adequation with all communication protocols and compatible with major known OS in market.the vendor generally make their own Bluetooth stack ex:Toshiba,Broadcom,TI,Microsoft....
In second case we're dealing with a device to be reprogrammed for a specific purpose.In this case we are on Slave mode or Server side ,our job consists of define our interface on the device ,those interface are profile, Services and Characteristics which expose device functions to end user.The next step will be compiling and downloading those information to device.A compiler is required to customize the firmware , a Downloader is also required to download new firmware so called image to device.since OTA (over-the-Air) feature is available on the majority of BLE devices , even a smartphone could be playing this role to download codes to device. BLE devices generally have two memory location dedicated to firmware images used by Device Boot Loader,one location for current running version of firmware , the second one is for new version image.Once downloader sent new version , boot loader pick it up in the next time device restarts .The best Compiler in the market so far is IAR embedded workbench , expensive but very powerful with a rich IDE software allowing you write your firmware in C/C++ .
In the third scenario you are going to develop an application to handle communication with a specific BLE device.in this case developer is in Master mode or Client side,here you're dealing mostly with a software rather than a hardware, if your target OS is supposed to support BLE ,so the only task in your charge is how to use BLE API in order to perform Read/Write/Control operation . I've prepared a few basic operation you need to write your code in such a scenario at the end of this document.
For Master side development there are two well known development kits available,one from Texas Instrument CC2541 SensorTag featured by 6 built-in censors :IR temperature Sensor,Humidity Sensor,Pressure Sensor,Accelerometer,Gyroscope,Magnetometer.
If you're planing to have at least of those features on your device this kit could help you to master the feature by explore all services and characteristics exposed by device,it would be a good starting point in your project but currently all demo and library provided by the company are only available for IOS , so if ios is not your host OS for your application, stay tuned to future update from Texas Instrument.
Notice TI solution allow you to compile code for Master side , if your project is about a customized device with your own profile & services
You should purchase a third party compiler such as IAR embedded workbench to write and download codes to firmware.
The second one is WICED SMART from Broadcom ,also with the same built-in censors as TI,the good point with WICED SMART is they provide not only a kit to develop master side but also an IDE to develop Slave side and download codes on firmware after defining your services and characteristics of a customizable dongle device, this IDE automatically generates codes based on defined profile information you provide through wizard pages, so you don't need any additional compiler to customize your device.Broadcom IDE integrate to Eclipse and their sdk supports C/C++/Java for Android
Both Broadcom and TI kit support OTA (Over-The Air) upgrade
Basic Steps in programming:
The codes i ‘ve prepared have been developed and tested under Android OS 4.4 using Java language , but if you’re targeting IOS ,Windows or any other OS the basic steps remain the same.I’ve also provided an example of a complete project attached to this document.
To start this section I present you few basic BLE API functions recently added to Android SDK 4.4
BluetoothGattService : return the list of services included in devices
BluetoothGattCharacteristic :return the list of characteristics included in GATT(service)?
BluetoothGattDescriptor:return the list of descriptors in this characteristics
1)first get a bluetooth adapter
public static BluetoothAdapter getBluetoothAdapter(Context context) {
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager == null)
return null;
return bluetoothManager.getAdapter();
}
2) checkout BLE
public static int getBleStatus(Context context) {
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { return STATUS_BLE_NOT_AVAILABLE; }
final BluetoothAdapter adapter = getBluetoothAdapter(context);
// Checks if Bluetooth is supported on the device.
if (adapter == null) {
return STATUS_BLUETOOTH_NOT_AVAILABLE;
}
if (adapter.isEnabled())
return STATUS_BLUETOOTH_DISABLED;
return STATUS_BLE_ENABLED;
}
you can also enable BT on your device using :
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Then for processing here is the step you should perform:
1)Starting a device discovery /scan as below
given an adapter use API startLeScan to start discovery process something like that:
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
as you see there is a callback which is request answer back from your device, there you generally retrieve information back from BLE device
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
As you see this callback bring to you an object of BluetoothDevice class which inturn store whatever you need to know about all discovered devices including the one you want to connect to
BluetoothDevice object gives you " Name + Address" ,from the list of discovered devices you select the one you're interesting to then
the next step is to forward these two parameters (its name and address) to another activity through extra values in Intent like that:
final Intent intent = new Intent(this, DeviceControlActivity.class);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
now it's the time of connection , from this new activity ,
you're gonna to use ServiceConnection API to start a service which is in charge of connection
ServiceConnection
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
then using mBluetoothLeService.getSupportedGattServices() we get a list of all services within the selected device
mBluetoothLeService is an instance of BluetoothLeService which manage connection , states, read/write operations....
when a device found we can call connectGatt API by passing a callback in which we get all information of a service like that:
device.connectGatt(this, false, mGattCallback);
in mGattCallback we perform onCharacteristicRead+....
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
};
Khosrov Boloorian – 2014
REFERENCES:
http://www.broadcom.com/products/wiced/smart/
Introduction:
This article is a study and an investigation on navigation systems,used and known worldwide as GPS device.This work is based on GPS signal specification of 1995 and recent additional improvements.The idea of writing this article was sparked a few years ago when i was working on a GPS project in my company.
The goal of this article is to introduce some important aspect of navigation systems to people who are seeking a start point to investigate on the matter, It’s a brief study and susceptible to have some errors slipped inside, so it cannot be considered as a reference or complete document..Some pictures have been taken from Google Images and history is added partly from GPS organisation resources.
Notice:In this Article we are referring to a Civilian and general purpose GPS .
The Principal of GPS (Global Positioning System ):
GPS is a system providing time and location information. A GPS receiver is a device to use these information in order to guide a Vehicle, an airplane,...to reach its destination.most people think their device is emitting signals to achieve this purpose, but in reality a GPS receiver device is a passive device and its main purpose is to receive signals from satellite and not to send out. In fact the main job of every GPS receiver device is to calculate its own position from satellite’s position.
History:
The emerging of GPS as we know today is related to General relativity; in fact in 1954 scientists were looking for a set of experiments to investigate on Einstein's general relativity using accurate atomic clocks around orbit.The GPS project started in 1973,initially for a military purpose,In 1983 Korean Air Lines Flight 007, carrying 269 people, was shot down after straying into the USSR's prohibited airspace, after this accident President Ronald Reagan has ordered by a directive to make GPS available to civilians as well, and this was the birth of GPS in civilian purpose. It has been improved step by step and almost fully operational in 1994.
Initially, the highest quality signal was reserved for military use, and the signal available for civilian use was intentionally degraded ("Selective Availability", SA). This changed with United States President Bill Clinton ordering Selective Availability turned off at midnight May 1, 2000, improving the precision of civilian GPS from 100 meters (about 300 feet) to 20 meters (about 65 feet).AS we'll see later, the most prominent part of a GPS device is its Clock, which accuracy is playing a crucial role in every GPS receiver device.
Geometry:
Maybe better to review a few principal of Geometry which help us to understand better the fundamental of GPS
1) In a 2D geometry the intersection between a circle and a line is represented by two points.
2) In a 2D geometry the intersection between two circles is represented by mostly two points.
3) In 3D Geometry the intersection between a sphere and a plane is a 2D circle (mapped to 2D) (Fig1).
4) In 3D Geometry the intersection between two spheres is a 2D circle (mapped to 2D) (Fig2)
5) In 3D Geometry the intersection between a spheres and a circle or 3 spheres is two points (Fig3)
By adding 4th sphere the intersection would be a point, and that’s the point we are interesting to,in a GPS study
Concept:
To Simplify things ,I’m going to give you an Example in 2D geometry
Imagine two city located on a map as A,B, and we know enough about them in term of Geographical positions, we have also located a third city (P),and we want to calculate its position knowing we are given A,B position and distance r1,r2. P will be the point of intersection of two circle of r1,r2 (distances) ,as we see here we have two points of intersection but just one of them is acceptable.
Therefore in order to find the correct position we need an additional point C, as shown here,
it’s also true when you look at the following equations:
(x-α1)² + (y-β1)² = r1²
(x- α2)² + (y- β2)² = r2²
(x- α3)² + (y- β3)² = r3²
These equation will give us an unique answer, P(x,y)
This example demonstrate what a Navigation system is doing ,in fact it’s computing its position in an arithmetic way given the coordinates of other satellites, a Navigation system is a graphical calculator knowing enough about a few satellites in its line of sight, calculating its own location and track it on its preinstalled map.
Now replace Circles by spheres ,P is located somewhere on the earth,actually P is your receiver location.
In 3D ,Calculation is similar, we have to deal with a similar scenario, except that in this case we need 4 spheres instead of 3 to compute Intersection, and that’s exactly what your navigation system does, to calculate your position,it waits to identify at least 4 satellite in its view, then the process of calculation is starting to resolve 4 equations which results in a point (your position).In the following figure 4 satellite are found by your navigation system device
By adding 4th sphere the intersection would be a point, and that’s the point we are interesting to,in a GPS study
The following equations must be resolved by your device in order to find your position
(x-a1)² + (y-b1)² + (z-c1)² - r1² = 0
(x-a2)² + (y-b2)² + (z-c2)² - r2² = 0
(x-a3)² + (y-b3)² + (z-c3)² - r3² = 0
(x-a4)² + (y-b4)² + (z-c4)² - r4² = 0
x² + y² + z² - 2a1x - 2b1y - 2c1z + a1² + b1² + c1² - r1² = 0
x² + y² + z² - 2a2x - 2b2y - 2c2z + a2² + b2² + c2² - r2² = 0
x² + y² + z² - 2a3x - 2b3y - 2c3z + a3² + b3² + c3² - r3² = 0
x² + y² + z² - 2a4x - 2b4y - 2c4z + a4² + b4² + c4² - r4² = 0
suppose :
a1² + b1² + c1² - r1² =
a2² + b2² + c2² - r2² =
a3² + b3² + c3² - r3² =
a4² + b4² + c4² - r4² =
x² + y² + z² - 2a1x - 2b1y - 2c1z + = 0
- x² + y² + z² - 2a2x - 2b2y - 2c2z + = 0
—————————————————
2a2x - 2a1x + 2b2y - 2b1y + 2c2z - 2c1z + – = 0
x² + y² + z² - 2a1x - 2b1y - 2c1z + = 0
- x² + y² + z² - 2a3x - 2b3y - 2c3z + = 0
—————————————————
2a3x - 2a1x + 2b3y - 2b1y + 2c3z - 2c1z + – = 0
x² + y² + z² - 2a1x - 2b1y - 2c1z + = 0
- x² + y² + z² - 2a4x - 2b4y - 2c4z + = 0
—————————————————
2a4x - 2a1x + 2b4y - 2b1y + 2c4z - 2c1z + – = 0
So we get 3 planes:
2a2x - 2a1x + 2b2y - 2b1y + 2c2z - 2c1z + – = 0
2a3x - 2a1x + 2b3y - 2b1y + 2c3z - 2c1z + – = 0
2a4x - 2a1x + 2b4y - 2b1y + 2c4z - 2c1z + – = 0
Assuming that:
– =Δ1, – = Δ2, – = Δ3
2a2=a ; 2a1=b ; 2a3=g ; 2a4=j
2b2=c ; 2b1=d ; 2b3=h ; 2b4=k
2c2=e ; 2c1=f ; 2c3=i ; 2c4=l
Now we have three equations
x(a-b) + y(c-d) + z(e-f) + Δ1 = 0
x(g-b) + y(h-d) + z(i-f) + Δ2 = 0
x(j-b) + y(k-d) + z(l-f) + Δ3 = 0
These equation have only one answer =P(x,y,z) (your location)
Here an example of calculation made by a device Emulator
Distance between satellite and receiver shown as r1,r2,r3,r4……etc are calculated from the time a GPS signal takes to reach us, that means the difference between satellite clocks and the time we get it In UTC, the data sent by satellite includes clock time and when we receive it ,we can calculate, the distance by :
Where ri ,ti are respectively distance and difference of time between satellite i and our GPS receiver device.
C is the speed of light or an electromagnetic signal (approximately), Ti is included in information sent by satellite in Data analyse section (you will see more in detail).
The GPS of today as we know it, consists of at least 24 satellites in an orbit of 20000 km around the earth,
they are transmitting GPS signals at 5 level of frequency L1 to L5 depending on what service is used ,Civilian,military,Nuclear detonation detection, forecasting and ionospheric studies,etc.
The range of frequency is going from L1=1,1GHZ to L5=1.6GHZ .
The choice of this range is due to a few facts as below:
A)The frequency must be below 2 GHZ ,if f>2 GHZ ,receiver has to adopt antenna equipment
B) Minimum influenced in therm of noise and weather conditions
Data Analyse and Programming:
A GPS signal data packet consists of two part C/V code mostly known as Golden code and navigation message , C/V code is generated as a very complex pattern , but more details about it,is going beyond the scope of this article.The message includes all information a Receiver needs to know ,to compute its position,its frequency is 50Hz and modulated with Golden code over a BPSK modulator on L1 then transmitted into air Fig8,Fig9.The data is divided into 25 frames (fig9) of 1500 bit (25*1500=37500).As I mentioned data transmission rate is 50HZ ,so to receive the whole message body,Receiver takes :DataSize/f=37500/50=12.5 min, each frame is received every 30 sec 12.5 / 25 =30 sec.The frames contain information like position of every satellite including the sender of data .Satellites send constantly these informations,when you turn on your navigation system it must receive all 25 frames in order to identify the most visible satellites so your device takes about 12.5 min to get all frames if Quick fix is not done (see below),each frame is also divided to 5 subframe of 300 bit ,The two last subframes are used to identify a satellite , after identification receiver uses only three first subframes and so it takes only 30 sec which is the time to get a frame.Every 30 sec it recalculate its position.
Subframe 4 contains information about satellite 25-32
Subframe 5 contains information about satellite 1-24
As we see here, each satellite sends out information about not only itself but also other satellites as well
Notice : GPS Receiver ,after receiving almanac and ephemeris, store them localy in order to be available in future (it uses them later)
A frame is divided into five subframes Fig11
TLM is a data header containing some information like age of Ephemeris data,etc it’s 30 bit in size and fig12 shows the fields structure in detail.HOW is used in a military purpose.The satellites broadcast two types of data, Almanac and Ephemeris. Almanac data is course orbital parameters for all SVs. Each SV broadcasts Almanac data for all SVs. This Almanac data is not very precise and is considered valid for up to several months.Ephemeris data by comparison is very precise orbital and clock correction for each SV and is necessary for precise positioning.Each SV broadcasts only its own Ephemeris data. This data is only considered valid for about 30 minutes. The Ephemeris data is broadcast by each SV every 30 seconds.When the GPS is initially turned on after being off for more than 30 minutes, it "looks" for SVs based on where it is based on the almanac and current time.With this information, appropriate SVs can be selected for initial search.
SV : Satellite in vision.
What is a Quick fix:
almanac and ephemeris contains date/time information
This date/time is valid for 7 days, in which receiver knows enough about satellite, so during this period it can quickly switch to its position When you update you GPS receiver using you PC, almanac and ephemeris is up to date and receiver doesn’t wait for all 25 frames to be received, because It has already identified the satellite.After analyzing a GPS packet data, we are able now to put the information into data structures which are much more significant for developers who want to put the concepts into a system’s firmware.
typedef Class CGPSData
{
CGPSData();
long nCvPRNCode;//1023 bits 2^1023 possibility
DATAFRAME Data[25];
... ///Some Computation methodes
}CGPSDATA;
typedef Struct DataFrame
{
SUBFRAMEDATA SubData[5];//5 subframes
}DATAFRAME;
typedef Struct Subframe //size of structure=300 bit
{
DWORD TLM;//30bit information= 8 preamble +16 bit data+ 6bit parity telemetry word=age of ephemeris data
DWORD HOW//17bit time of week+7bit data+6 bit parity Hand over word= time Ticks spent from the previous Sunday 0:00 o’clock (military use)
DWORD CCD[8];//240 bits information ,satellite clock correction data ,allow synchronization between receiver and satellite
}SUBFRAMEDATA;
Khosrov Boloorian
March 2011
In this article I’m trying to modelize the basic Sets theory operation by programming , Sets theory is a fundamental concept helping Developers and Software architects to implement some good generic algorithms in order to solve problems in a generic vision, generally this kind of solution is useful and appreciated by Design Pattern architects.
To modelize things we selects very basic operations to implement , because basics are fundamental for extending model into a complex model , the abstraction is playing a big role in Design Pattern , that’s why I implement a generic class so later by extending It can be applied to lots of scenario.
In mathematics a Set is a collection of elements or objects with no necessary links between elements,
A = {1,7,8,25,17,9,30,42,70,18,25,99,55,88}
B = {2,27,8,88,18}
C = {“one”,”two”,”three”,”four"}
D = {🇨🇦,🇨🇿,🇨🇭,🇫🇷,🇺🇸}
//union of C and D
A ∪ B = {1,2,7,8,25,27,17,18,9,30,42,70,18,25,99,55,88}
//Intersection of A and B
A ∩ B = {8,88,18} //union of A and B
//union of C and D = C + D
C ∪ D = {“one”,”two”,”three”,”four”,🇨🇦,🇨🇿,🇨🇭,🇫🇷,🇺🇸}
//Intersection of A and B
A ∩ C = ∅
//substraction of A and B
A - B = {1,7,25,17,9,30,42,70,25,99,55}
Now we are going to implement programmatically those basic ∪ (union) , ∩ (intersection), - (Subtract)
Subset
A is a subset of B when all members of A are also member of B ∀ x ∈ A => x ∈ B
A = {1,2,4,6,b} , B= {4,b,a,d,f,c}
A ∪ B = {1,2,4,6,b,a,d,f,c} => ∀ x ∈ A ∨ x ∈ B
A ∩ B = {4,b} => ∀ x ∈ A ∧ x ∈ B
A - B ={1,2,6} => ∀ x ∈ A ∧ x ∉ B
We create a generic class let’s call MathArray , to simplify things and in order to be able to check equality of elements (avoid to overload an additional equality operator) let’s suppose a generic type of Equatable class.
we add a list of items and a convenience initializer for default purpose
public class MathArray<T:Equatable>{
var mItems = [T]()
var items: [T]{
get {
return self.mItems
}
set{
self.mItems = newValue
}
}
public convenience init(){
let arr = Array<T>()
self.init(array: arr)
}
public init(array:[T]){
items = array
}
}
One of the great power of Swift is Overloading , those C++ developers are probably familiar with the nice C++ ability to define or redefine operators like +,-,==,&
for example it will be nice to define + operator to operate on any object we like , I mean by defining it we can apply it to A and B to get union A ∪ B as A+B , or we can define A - B or …
let union = A + B [or = A ∪ B]
let subtract = A - B
we can also check a collection if it’s a subset of another collection as
let isSubset = A ⊂ B
Now we implement all those nice operators in a global scoop
//give operator , this operator is exclusively used for debugging and test purpose
prefix func => <T>(right:MathArray<T>)->[T]{
return right.items
}
//Minus operator
func - <T>(left:MathArray<T>,right:MathArray<T>)->[T]{
let check = {
(x:T)->Bool in
return right.items.indexOf(x)==nil
}
return left.items.filter(check)
}
//subset operator
func ⊂ <T>(left:MathArray<T>,right:MathArray<T>)->Bool{
for element in left.items {
guard right.items.indexOf(element) != nil else { return false}
}
return true
}
//equal operator
func == <T>(left:MathArray<T>,right:MathArray<T>)->Bool{
for element in left.items {
guard right.items.indexOf(element) != nil else { return false}
}
for element in right.items {
guard left.items.indexOf(element) != nil else {return false}
}
return true
}
// union operator, + operator can be also replaced by ∪
func + <T>(left : MathArray<T>,right : MathArray<T>)->[T]{
var result = [T]()
for element in left.items{
result.append(element)
}
for element in right.items{
result.append(element)
}
return result
}
//intersection operator
func ∩ <T>(left : MathArray<T>,right : MathArray<T>)->[T]{
let check = {(x:T)->Bool in return right.items.indexOf(x) != nil}
return left.items.filter(check)
}
//Full class implementation , compiled & tested with Swift2 on XCODE 7.2
import Foundation
import UIKit
public class MathArray<T:Equatable>{
var mItems = [T]()
var items: [T]{
get {
return self.mItems
}
set{
self.mItems = newValue
}
}
public convenience init(){
let arr = Array<T>()
self.init(array: arr)
}
public init(array:[T]){
items = array
}
public static func getUnion<T:Equatable>(array1:[T],array2:[T])->[T]{
return MathArray<T>(array: array1)+MathArray<T>(array: array2)//add
}
public static func getInterset<T:Equatable>(array1:[T],array2:[T])->[T]{
return MathArray<T>(array: array1) ∩ MathArray<T>(array: array2)
}
public static func isSetsEqual<T:Equatable>(array1:[T],array2:[T])->Bool{
return MathArray<T>(array: array1) == MathArray<T>(array: array2)
}
public static func isSubset<T:Equatable>(array1:[T],array2:[T])->Bool{
return MathArray<T>(array: array1) ⊂ MathArray<T>(array: array2)
}
public static func subtract<T:Equatable>(array1:[T],array2:[T])->[T]{
return MathArray<T>(array: array1) - MathArray<T>(array: array2)//minus
}
public static func getItemsForArray<T:Equatable>(array:[T])->[T]{
return =>MathArray<T>(array: array)
}
}
//Here we overload our Sets operators , notice overloading is only allowed in a global scoop
//so we define our Overloaded Operator out of our class
infix operator ∩ {}
prefix operator => {}
infix operator ⊂ {}
prefix func => <T>(right:MathArray<T>)->[T]{
return right.items
}
//Minus operator
func - <T>(left:MathArray<T>,right:MathArray<T>)->[T]{
let check = {
(x:T)->Bool in
return right.items.indexOf(x)==nil
}
return left.items.filter(check)
}
//subset operator
func ⊂ <T>(left:MathArray<T>,right:MathArray<T>)->Bool{
for element in left.items {
guard right.items.indexOf(element) != nil else { return false}
}
return true
}
//equal operator
func == <T>(left:MathArray<T>,right:MathArray<T>)->Bool{
for element in left.items {
guard right.items.indexOf(element) != nil else { return false}
}
for element in right.items {
guard left.items.indexOf(element) != nil else {return false}
}
return true
}
// union operator
func + <T>(left : MathArray<T>,right : MathArray<T>)->[T]{
var result = [T]()
for element in left.items{
result.append(element)
}
for element in right.items{
result.append(element)
}
return result
}
//intersection operator
func ∩ <T>(left : MathArray<T>,right : MathArray<T>)->[T]{
let check = {(x:T)->Bool in return right.items.indexOf(x) != nil}
return left.items.filter(check)
}
===========================================================
To test the class we can for example :
let A = [5,17,9,30,42,70,18,25,99,55,88]
let B = [5,25,61,54]
let result = MathArray<Int>.subtract(A, array2: B)
print("\(result)”)
print => [61,54]
if f(t) is even:
if f(t) is odd:
Remind : Lorentzienne Integral
Type Alias
type Kilometers = i32;
type Kg = f64;
struct MyAllocator; 👈 Buffer
{GlobalAlloc is a trait to be implemented}
Code:
unsafe impl GlobalAlloc for MyAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
// Call to default system allocator or custom logic
System.alloc(layout) // Here, we delegate to the system allocator
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
// Deallocate the memory using the default system allocator
System.dealloc(ptr, layout);
}
}
#[global_allocator]
static GLOBAL: MyAllocator = MyAllocator;👈Override System allocation
Example:
Ex1:
let boxed_value = Box::new(42); // Allocated by MyAllocator
println!("Boxed value: {}", boxed_value);
let mut vector = Vec::new(); // Vec also uses heap memory
vector.push(1);
vector.push(2);
println!("Vector: {:?}", vector);
Ex2:
let alloc = MyAllocator;
let ptr = unsafe { alloc.allocate(Layout::new::<i32>())? };
// Use the allocated memory
//Free memory
unsafe { System.deallocate(ptr, Layout::new::<i32>()) };
When you are using GLOBAL override, all allocation new() for any object is redirect to MyAllocator
#[global_allocator]
static GLOBAL: MyAllocator = MyAllocator;👈Override System allocation
Interior pointers are pointers that allow for safe access to data that is located inside another structure. They are particularly useful when you want to manage ownership and borrowing while enabling access to data in a flexible manner.
•Types of Interior Pointers:
1.Box<T>: A heap-allocated pointer that owns the data.
2.Rc<T>: A reference-counted pointer that enables multiple ownership of the same data.
3.Arc<T>: An atomic reference-counted pointer for thread-safe reference counting.
4.RefCell<T>: A mutable memory location with dynamically checked borrow rules.
Example 1:
let user = User{id : 10};
// uu.id=15; => error , require mut
How access id field out of scope?
Answer: using Interior pointer:
let data = Rc::new(RefCell::new(user));
let data_clone = Rc::clone(&data);
{
let mut borrowed_data = data_clone.borrow_mut();
borrowed_data.id += 5; // Mutate the data
}
println!("Value: {}", data.borrow().id); // Output: Value: 15
Example 2:
let value = Cell::new(5);
// Access and modify the inner value
let current = value.get();
value.set(current + 1);
println!("New value: {}", value.get());
let data = (("Alan", 27), [1, 2, 3]);
let (name, age) = data.0; // Destructure first element (tuple)
let numbers = data.1; // Destructure second element (array)
use bit_vec::BitVec;
fn set_bit_at_index(mut data: BitVec, index: usize) -> BitVec {
data.set(index, true);
data
}
let mut data = BitVec::from_elem(8, false);
println!("BitVec: {:?}", data); // { storage: "00000000", nbits: 8 }
data = set_bit_at_index(data, 3);
println!("BitVec: {:?}", data); // { storage: "00010000", nbits: 8 }
enum Point {
Origin,
Cartesian(i32, i32),
}
let point = Point::Cartesian(1, 2);
match point {
Point::Origin => println!("Origin point"),
Point::Cartesian(x, y) => println!("Cartesian point: ({}, {})", x, y),
}
SRP protocol
SRP version : 6a
SRP is the safe way to exchange sensitive data on a Client-Server
Architecture.
SRP is a secure password-based authentication and key-exchange protocol. It solves the problem of authenticating clients to servers securely, in cases where the user of the client software must memorize a small secret (like a password) and carries no other secret information, and where the server carries a verifier for each user, which allows it to authenticate the client but which, if compromised, would not allow the attacker to impersonate the client
With high sensitive data, regular password Hashing* is not 100% secure.
Cost of a trusted third party server.
* All algo variants MD5 ,SHA-1, SHA-2,….PBKDF,…
SRP is similar to Diffie–Hellman , and relied to a public key-exchange.
First idea goes back to 1998
More focused ,following some security-hole found on Diffie–Hellman
Advantages
Protected from Dictionary Attack📖 or Channel Eavesdrop👂.
Doesn’t require a trusted third party server
Zero-Knowledge Password from Server side
Example:
1Password uses SRP
1Password remembers them all for you. Save your passwords and log in to sites with a single click. It's that simple.
Concept
Exchange with Server without sending Password/PIN.
Client registers on Server with User ID (Ex:email) and a Secret (Salt+verifier)
Server create the user record.
Client login with User ID and a Pubic Key A
Server send a Public Key B and a Secret (Salt)
Client submit a Transaction (send an order)
As all cryptography concept ,everything begins by prime numbers,
Thanks “Pierre de Fermat”:
In SRP everything begins by picking two big prime numbers p,q such as:
The pair (p,q) called SRP group and in SRP version 6a they are represented by N an g.
Two public key A (Client) and B (Sever) are derived from random a, b
Random a=> Transform to A (public key)
Random b=> Transform to B (public Key)
salt is also a random generated on both side.
v = q^x % N, where x = SHA256(s | SHA256(Username | “:” | Password)).
API
Since The SRP algorithm is a pure heavy mathematic calculation,
It’s preferable to implement Client side in a low level programming language such as C/C++.This way it can be shared through a lib with other high-level language such as Java/Swift.
The API is very simple , we have 3 phase of transactions so 3 API would be like the following prototype:
Enrollement session
Enrollement is done only one time , it's similar tocreation of an account SHOULD NOT CALL ENROLLEMENT IN EVERY SESSION!
References:
Stanford SRP Home page :
Wikipedia: https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol
https://pythonhosted.org/srp/srp.html
Khosrov Boloorian ©2016
Contact:kboloorian@hotmail.com