Thursday, August 31, 2017

Python tutorial for beginners(Python Basics)


Python

                  Python is an object-oriented programming language created by Guido Rossum in 1989. It is ideally designed for rapid prototyping of complex applications. It has interfaces to many OS system calls and libraries and is extensible to C or C++. Many large companies use the Python programming language include NASA, Google, YouTube, BitTorrent, etc.
                   Python is widely used in Artificial Intelligence, Natural Language Generation, Neural Networks and other advanced fields of Computer Science. Python had deep focus on code readability & this class will teach you python from basics.

Python exposes the following qualities

  • Portability

Python runs everywhere, and porting a program from Linux to Windows or Mac is usually just a matter of fixing paths and settings.

  • Developer productivity

Python program is typically one-fifth to one-third the size of equivalent Java or C++ code. This means the job gets done faster.

  • An extensive library

Python has an incredibly wide standard library

  • Software quality

Python is heavily focused on readability, coherence, and quality. The language uniformity allows for high readability and this is crucial nowadays where code is more of a collective effort than a solo experience.

  • Software integration

             Another important aspect is that Python can be extended and integrated with many otherlanguages, which means that even when a company is using a different language as their mainstream tool, Python can come in and act as a glue agent between complex applications that need to talk to each other in some way.

Python is used in many different contexts, such as system programming, web programming, GUI applications, gaming and robotics, rapid prototyping, system integration, data science, database applications, and much more.

What are the drawbacks?

                    Probably, the only drawback that one could find in Python, which is not due to personal preferences, is the execution speed. Typically, Python is slower than its compiled brothers. The standard implementation of Python produces, when you run an application, a compiled version of the source code called byte code (with the extension .pyc), which is then run by the Python interpreter. The advantage of this approach is portability, which we pay for with a slowdown due to the fact that Python is not compiled down to machine level as are other languages.


Installing Python


                 Python is fully integrated and most likely already installed in basically almost every Linux distribution. If you have a Mac, it's likely that Python is already there as well (however, possibly only Python 2.7), whereas if you're using Windows, you probably need to install it.

The place you want to start is the official Python website: https://www.python.org. This website hosts the official Python documentation and many other resources that you will find very useful. Take the time to explore it.

Find the download section and choose the installer for your OS. If you are on Windows, make sure that when you run the installer, you check the option install pip

To open the console in Windows, go to the Start menu, choose Run, and type cmdWhatever console you open, type python at the prompt, and make sure the Python interactive shell shows up. Type exit() to quit.


Running a Python program


Python contains modules and packages. Modules are the functions and packages are built in functions.
In Python, to calculate the factorial of number 5, we just need the following code:

>>> from math import factorial
>>> factorial(5)
120

Lets print integer, string and array


>>> n = 3  # integer number
>>> address = "Bangalore, India"  # S. Holmes
>>> employee = {'age': 20,'Name': 'Python'}



To print, just type variables

>>> n
3
>>> address

namespace is therefore a mapping from names to objects. Examples are the set of built-in names (containing functions that are always accessible for free in any Python program), the global names in a module, and the local names in a function. Even the set of attributes of an object can be considered a namespace.

A scope is a textual region of a Python program, where a namespace is directly accessible.

There are four different scopes that Python makes accessible (not necessarily all of them present at the same time, of course):
  • The local scope, which is the innermost one and contains the local names.
  • The enclosing scope, that is, the scope of any enclosing function. It contains non-local names and also non-global names.
  • The global scope contains the global names.
  • The built-in scope contains the built-in names. Python comes with a set of functions that you can use in a off-the-shelf fashion, such as printallabs, and so on. They live in the built-in scope.
Creating and running a simple scope program
scopes1.py
# Local versus Global

# we define a function, called local
def local():
    m = 7
    print(m)

m = 5
print(m)

# we call, or `execute` the function local
local()
Running the program from your command prompt
python scopes1.py

We see two numbers printed on the console: 5 and 7


Object and classes

bike.py# let's define the class Bike

 class Bike:
    def __init__(self, colour, frame_material):
        self.colour = colour
        self.frame_material = frame_material

     def brake(self):
        print("Braking!")

 # let's create a couple of instances
red_bike = Bike('Red', 'Carbon fiber')
blue_bike = Bike('Blue', 'Steel')

 # let's inspect the objects we have, instances of the Bike class.
print(red_bike.colour)  # prints: Red
print(red_bike.frame_material)  # prints: Carbon fiber
print(blue_bike.colour)  # prints: Blue
print(blue_bike.frame_material)  #  prints: Steel

 # let's brake!

red_bike.brake()  # prints: Braking!

The first method, __init__ is an initializer. It uses some Python magic to set up the objects with the values we pass when we create it.


Built in Datatypes

  • int : Integer numbers
  • bool : Boolean, true or false
  • sys.float_info : floating point numbers
  • fractions : Fractions hold a rational numerator and denominator in their lowest forms.
  • decimal : Floating numbers with more precission
Tuples
A tuple is a sequence of arbitrary Python objects. In a tuple, items are separated by commas.

>>> one_element_tuple = (42, )  # you need the comma!
>>> three_elements_tuple = (1, 3, 5)
>>> a, b, c = 1, 2, 3  # tuple for multiple assignment
>>> a, b, c  # implicit tuple to print with one instruction
(1, 2, 3)
>>> 3 in three_elements_tuple  # membership test
True
Lists
Lists are commonly used to store collections of homogeneous objects, but there is nothing preventing you to store heterogeneous collections as well. 

>>> list((1, 3, 5, 7, 9))  # list from a tuple
[1, 3, 5, 7, 9]
>>> list('hello')  # list from a string
['h', 'e', 'l', 'l', 'o']
List have following functions append, count, extend, index, insert, pop, reverse,  sort, clear, min, max, sum, len
>>> a = [1, 2, 1, 3]
>>> a.append(13)  # we can append anything at the end
>>> a
Set 

Stored collection of objects

>>> small_primes = set()  # empty set
>>> small_primes.add(2)  # adding one element at a time
>>> small_primes.add(3)
>>> small_primes.add(5)
>>> small_primes
{2, 3, 5}
>>> small_pr
Dictionaries
A dictionary maps keys to values. Keys need to be hashable objects, while values can be of any arbitrary type.
>>> a = dict(A=1, Z=-1)

Iterations and Decisions making

If, Elif, Else
#ifelse.py

income = 15000
if income < 10000:
    tax_coefficient = 0.0  #1
elif income < 30000:
    tax_coefficient = 0.2  #2
elif income < 100000:
    tax_coefficient = 0.35  #3
else:
    tax_coefficient = 0.45  #4

print('I will pay:', income * tax_coefficient, 'in taxes')
Output

$ python taxes.py

I will pay: 3000.0 in taxes
for loop

for number in [0, 1, 2, 3, 4]:
    print(number)
while loop
position = 10
while position < 0:    
    position -= 1

Function

            A function in Python is defined by using the def keyword, after which the name of the function follows, terminated by a pair of braces (which may or may not contain input parameters) and, finally, a colon (:) signals the end of the function definition line. Immediately afterwards, indented by four spaces, we find the body of the function, which is the set of instructions that the function will execute when called.


x = 3
def func(y):
    print(y)
func(x)  # prints: 3

Built-in functions

Python comes with a lot of built-in functions. They are available anywhere and you can get a list of them by inspecting the builtin module with dir(__builtin__), or by going to the official Python documentation. Unfortunately, I don't have the room to go through all of them here. Some of them we've already seen, such as anybinbooldivmodfilterfloatgetattridintlenlistminprintsettupletype, and zip, but there are many more, which you should read at least once.
Adding comment or documenting the code
def square(n):
    """Return the square of a number n. """
    return n ** 2
def get_username(userid):
    """Return the username of a user given their id. """
    return db.get(user_id=userid).username
Importing objects
from lib.funcdef import square, cube
print(square(10))
print(cube(10))
Class and Objects
Python is based on Object Oriented Programming (OOP), Python supports all OOPs conepts like Class, Object, polymorphism , Inheritance, static class and methods. The two main players in OOP are objects and classesClasses are used to create objects (objects are instances of the classes with which they were created), so we could see them as instance factories. When objects are created by a class, they inherit the class attributes and methods. They represent concrete items in the program's domain.
class Square():
    side = 8
    def area(self):  # self is a reference to an instance
        return self.side ** 2
sq = Square()
print(sq.area())  # 64 (side is found on the class)
print(Square.area(sq))  # 64 (equivalent to sq.area())
sq.side = 10
print(sq.area())  # 100 (side is found on the instance)
Share:

Thursday, August 24, 2017

Introduction to Bluetooth Low Energy

Bluetooth Low Energy (BLE) tutorial

                       Bluetooth Low Energy (Bluetooth LE, BLE, marketed as Bluetooth Smart) is a wireless personal area network technology designed and marketed by the Bluetooth Special Interest Group aimed at novel applications in the healthcare, fitness, beacons, security, and home entertainment industries. Compared to Classic Bluetooth, Bluetooth Smart is intended to provide considerably reduced power consumption and cost while maintaining a similar communication range.

BLE Architecture 





Table shows the wireless technologies implemented for the three main device types on the market today.


Device
BR/EDR (classic Bluetooth) support
BLE (Bluetooth Low Energy) support
Pre-4.0 Bluetooth
Yes
No
4.x Single-Mode (Bluetooth Smart)
No
Yes
4.x Dual-Mode (Bluetooth Smart Ready)
Yes
Yes

As you can see, the Bluetooth Specification (4.0 and above) defines two wireless technologies:

  • BR/EDR (classic Bluetooth)
The wireless standard that has evolved with the Bluetooth Specification since 1.0.

  • BLE (Bluetooth Low Energy)
The low-power wireless standard introduced with version 4.0 of the specification.
And these are the two device types that be used with these configurations:

  • Single-mode (BLE, Bluetooth Smart) device
A device that implements BLE, which can communicate with single-mode and dual-mode devices, but not with devices supporting BR/EDR only.

  • Dual-mode (BR/EDR/LE, Bluetooth Smart Ready) device
A device that implements both BR/EDR and BLE, which can communicate with any Bluetooth device.
So, in practice, a typical best-case scenario should probably assume a potential maximum data throughpout in the neighborhood of 5-10 KB per second, depending on the limitations of both peers.
It’s possible to create and configure a BLE device that can reliably transmit data 30 meters or more line-of-sight, but a typical operating range is probably closer to 2 to 5 meters, with a conscious effort to reduce the range and save battery life without the transmission distance becoming a nuisance to the end user.
A Bluetooth Low Energy device can communicate with the outside world in two ways: broadcasting or connections. 
The standard advertising packet contains a 31-byte payload used to include data that describes the broadcaster and its capabilities, but it can also include any custom information you want to broadcast to other devices. If this standard 31-byte payload isn’t large enough to fit all of the required data, BLE also supports an optional secondary advertising payload (called the Scan Response), which allows devices that detect a broadcasting device to request a second advertising frame with another 31-byte payload, for up to 62 bytes total.

The standard advertising packet contains a 31-byte payload used to include data that describes the broadcaster and its capabilities, but it can also include any custom information you want to broadcast to other devices. If this standard 31-byte payload isn’t large enough to fit all of the required data, BLE also supports an optional secondary advertising payload (called the Scan Response), which allows devices that detect a broadcasting device to request a second advertising frame with another 31-byte payload, for up to 62 bytes total.

A connection is a permanent, periodical data exchange of packets between two devices. It is therefore inherently private (the data is sent to and received by only the two peers involved in a connection, and no other device unless it’s indiscriminately sniffing).

Connections involve two separate roles:

  • Central (master)
Repeatedly scans the preset frequencies for connectable advertising packets and, when suitable, initates a connection. Once the connection is established, the central manages the timing and initiates the periodical data exchanges.

  • Peripheral (slave)
A device that sends connectable advertising packets periodically and accepts incoming connections. Once in an active connection, the peripheral follows the central’s timing and exchanges data regularly with it.

  • Profiles
“Vertical slices” of functionality covering either basic modes of operation required by all devices (Generic Access Profile, Generic Attribute Profile) or specific use cases (Proximity Profile, Glucose Profile), profiles essentially define how protocols should be used to achieve a particular goal, whether generic or specific.

GENERIC PROFILES

Generic profiles are defined by the specification, and it’s important to understand how two of them are fundamental to ensuring interoperability between BLE devices from different vendors:

  • Generic Access Profile (GAP)
Covering the usage model of the lower-level radio protocols to define roles, procedures, and modes that allow devices to broadcast data, discover devices, establish connections, manage connections, and negotiate security levels, GAP is, in essence, the topmost control layer of BLE. This profile is mandatory for all BLE devices, and all must comply with it.

  • Generic Attribute Profile (GATT)
Dealing with data exchange in BLE, GATT defines a basic data model and procedures to allow devices to discover, read, write, and push data elements between them. It is, in essence, the topmost data layer of BLE.


Each of these basic building blocks of the protocol stack is split into several layers that provide the functionality required to operate:

Application

The application, like in all other types of systems, is the highest layer and the one responsible for containing the logic, user interface, and data handling of everything related to the actual use-case that the application implements. The architecture of an application is highly dependent on each particular implementation.

Host

Includes the following layers:
  •        Generic Access Profile (GAP)
                              The Generic Access Profile (GAP) dictates how devices interact with each other at a lower level, outside of the actual protocol stack. GAP can be considered to define the BLE topmost control layer, given that it specifies how devices perform control procedures such as device discovery, connection, security establishment, and others to ensure interoperability and to allow data exchange to take place between devices from different vendors.

  •         Generic Attribute Profile (GATT)
The Generic Attribute Profile (GATT) builds on the Attribute Protocol (ATT) and adds a hierarchy and data abstraction model on top of it. In a way, it can be considered the backbone of BLE data transfer because it defines how data is organized and exchanged between applications.


It defines generic data objects that can be used and reused by a variety of application profiles (known as GATT-based profiles). It maintains the same client/server architecture present in ATT, but the data is now encapsulated in services, which consist of one or more characteristics. Each characteristic can be thought of as the union of a piece of user data along with metadata (descriptive information about that value such as properties, user-visible name, units, and more).

  •         Logical Link Control and Adaptation Protocol (L2CAP)
The rather cryptically named Logical Link Control and Adaptation Protocol (L2CAP) provides two main pieces of functionality. First, it serves as a protocol multiplexer that takes multiple protocols from the upper layers and encapsulates them into the standard BLE packet format (and vice versa).
For Bluetooth Low Energy, the L2CAP layer is in charge or routing two main protocols: the Attribute Protocol (ATT) and the Security Manager Protocol (SMP).

  •         Attribute Protocol (ATT)

  •         Security Manager (SM)
The Security Manager (SM) is both a protocol and a series of security algorithms designed to provide the Bluetooth protocol stack with the ability to generate and exchange security keys, which then allow the peers to communicate securely over an encrypted link, to trust the identity of the remote device, and finally, to hide the public Bluetooth Address if required to avoid malicious peers tracking a particular device.
The Security Manager defines two roles:
Initiator
Always corresponds to the Link Layer master and therefore the GAP central.
Responder
Always corresponds to the Link Layer slave and therefore the GAP peripheral.

SECURITY PROCEDURES

The Security Manager provides support for the following three procedures:
Pairing
The procedure by which a temporary common security encryption key is generated to be able to switch to a secure, encrypted link. This temporary key is not stored and is therefore not reusable in subsequent connections.
Bonding
A sequence of pairing followed by the generation and exchange of permanent security keys, destined to be stored in nonvolatile memory and therefore creating a permanent bond between two devices, which will allow them to quickly set up a secure link in subsequent connections without having to perform a bonding procedure again.
Encryption Re-establishment
After a bonding procedure is complete, keys might have been stored on both sides of the connection. If encryption keys have been stored, this procedure defines how to use those keys in subsequent connections to re-establish a secure, encrypted connection without having to go through the pairing (or bonding) procedure again.

  •         Host Controller Interface (HCI), Host side

Controller

Includes the following layers:

  •         Host Controller Interface (HCI), Controller side
                   The Bluetooth specification defines HCI as a set of commands and events for the host and the controller to interact with each other, along with a data packet format and a set of rules for flow control and other procedures. Additionally, the spec defines several transports, each of which augments the HCI protocol for a specific physical transport (UART, USB, SDIO, etc.).

  •        Link Layer (LL)
                 The Link Layer is the part that directly interfaces with the PHY, and it is usually implemented as a combination of custom hardware and software. 

  •         Physical Layer (PHY)
                  The physical (PHY) layer is the part that actually contains the analog communications circuitry, capable of modulating and demodulating analog signals and transforming them into digital symbols.

ADVERTISING AND SCANNING

BLE has only one packet format and two types of packets (advertising and data packets), which simplifies the protocol stack implementation immensely. Advertising packets serve two purposes:
  • To broadcast data for applications that do not need the overhead of a full connection establishment
  • To discover slaves and to connect to them
Share:

Popular Posts

Contact Form

Name

Email *

Message *