Wednesday 18 October 2017

Writing dynamic data to excel sheet using python

"""writing dynamic data to excel sheet using ordered dictionaries generating continuous Name tags in the excel sheet based on name and dynamic values"""
import xlwt
from collections import OrderedDict


def push_data_to_excel():
    book = xlwt.Workbook(encoding="utf-8")
    sheet1 = book.add_sheet("Device_Details")
    list1 = ["Tag Name", "parameter_name", "state", "results"]
    for i,j in enumerate(list1):
        sheet1.write(0, i, j)
    book.save("trial.xls")
    return sheet1, book


def create_tag():
    sheet_obj, book = push_data_to_excel()
    c = 1
    tag_name = "Narendra"
    state = "R/W"
    parameter_name = "coil_1"
    results = (1, 0, 1, 1, 0, 0, 1,0,1,1,1)
    if len(results)>0:
        dict1 = OrderedDict()
        i = 1
        for val in results:
            # creating dictionary for keys(tag names) & corresponding values(1,0,1,1,0,0,...)
            t_name = tag_name + '_' + str(i)
            dict1[t_name] = val
            i += 1
            print(dict1.keys())

        for m, n in dict1.items():
            sheet_obj.write(c,0, m)
            sheet_obj.write(c, 1, parameter_name)
            sheet_obj.write(c, 2, state)
            sheet_obj.write(c, 3, n)
            c += 1
            book.save("trial.xls")

create_tag()

                                Request: Please provide your valuable comments

Wednesday 12 July 2017

Python code to read json file data with Example

"""
json full form "JavaScript Object notation".
Inspired by java script but now independent to any programming language
In json most frequent functions are 4 (load, loads, dump, dumps)
"""
# python code to read json file data Example 1
"""
Note:1 In Notepad/Notepad++ save below data with extension .json
while saving we can provide any name.
save the file, where the source(.py) file you are supposed to write,
I mean in the same directory)"""

{"Narendra":[{"id":"HM0002162","Working in HM": " past7 years",
"Designation":"Test Module Lead", "BU":"PES"},
{"Father's Name":"Udaya Bhaskara rao gaaru",
"Address":["Urivi village","Pedana Mandal",
"Krishna D.t", "A.P"],
"Qualification": "M.tech"}],
"Surendra":{"id":"HM0004xx", "age": 32, "Mobile_no": "9959xxx530"},
"Idly_cost": 30,
"Dosa_cost": 35,
"Puri_cost": 30
}
"""
"""json.load() is used to read the dictionary data, from JSON file """

import json
# from json import load


with open("any_name.json") as data_file:
data = json.load(data_file)

print(data)

""" or """

# with open("any_name.json") as data_file:
# data = load(data_file)

print(data["Narendra"]) # getting all the values of narendra
print(data["Narendra"][0]["id"])
print(data["Narendra"][0]["Designation"])
print(data["Narendra"][1]["Father's Name"])

surendr_details = data['Surendra']
print(surendr_details)
s_id = data['Surendra']["id"]
print(s_id)
print(data["Dosa_cost"])
""" json.loads() is used to convert the JSON String into the Python dictionary."""

# person = '{"name": "Bob", "languages": ["English", "Fench"]}'
# person_dict = json.loads(person)
# print(person_dict)
# print(person_dict['languages'])

# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
# Output: ['English', 'French']

"""**********************************************************************"""

"""json.dump() method can be used for writing data into JSON file.

Syntax: json.dump(dict, file_pointer)"""

""" dump() method is used when the Python objects have to be stored in a file.
dump() needs the json file name in which the output has to be stored as an argument."""

# Data to be written
dictionary = {
"name": "Mahalakshmi Boyina",
"D.O.B": "10-Feb-2020",
"Blood group": "B+ve",
"phonenumber": "9000 30 1444"
}

# with open("sample.json", "w") as outfile:
# json.dump(dictionary, outfile)


"""
json.dumps() method can convert a Python object into a JSON string.
Syntax: json.dumps(dict, indent)

dumps() is used when the objects are required to be in string format(used for parsing, printing,...)
dumps() does not require any such file name to be passed.
"""


# Data to be written
dictionary = {
"Emp Id": "HM0002162",
"Name": "Narendra",
"Qualification": "M.Tech",
"Designation": "Test Module Lead"
}

# json_object = json.dumps(dictionary, indent=4)
# print(json_object, "\n", type(json_object))

# python code to read JSON file data Example 2

# copy below lines to a notepad and save with (.json)Extention. Ex: config.json

{
  
  "Local_Machine_Path": "/home/narendrab/Screen_Capture_Working_V2/",

  "Linux_Remote_Machine_Path": "/home/Bhagyasree/ntest/",
  "Linux_Remote_Machine_IP_Addr": "172.116.16.2",
  "Linux_Remote_Machine_User_Name": "Bhagyasree",
  "Linux_Remote_Machine_Pass_word": "Nanna@123!!",

}

========================================================================
# Python code: Copy the following code and save the file (Narendra.py)
import json

json_file = "config.json"
def get_entire_json_data(json_file):
    with open(json_file) as data_file:
        service_data = json.load(data_file)
    # pprint(service_data)  # it will print entire data present in the json file    return service_data

x = get_entire_json_data(json_file)
# print x


Linux_Remote_Machine_IP_Addr = str(x["Linux_Remote_Machine_IP_Addr"])
# print(Linux_Remote_Machine_IP_Addr)
Linux_Remote_Machine_User_Name = str(x["Linux_Remote_Machine_User_Name"])
# print(Linux_Remote_Machine_User_Name)
Linux_Remote_Machine_Pass_word = str(x["Linux_Remote_Machine_Pass_word"])
# print(Linux_Remote_Machine_Pass_word)

Local_Machine_Path = str(x["Local_Machine_Path"])
# print(Local_Machine_Path)
Linux_Remote_Machine_Path = str(x["Linux_Remote_Machine_Path"])
# print(Linux_Remote_Machine_Path)

Monday 6 March 2017

Python code to get ini data with Example

"""
Write the required data to be passed in a notepad & save that file with "ini" extention.
Place the below code in the python file.
"""
Example:



Code:
def getIniData(section):
    config = configparser.ConfigParser()
    config.optionxform = str
    config.read("testconfig.ini")
    section_dict = {}
    for option in config.options(section):
        section_dict[option] = config.get(section, option)
    return section_dict



Python - Active COMPORT Detection & Verifying BLE device


"""
==> Connect the BLE devices and normal USB devices to the PC, then run this Python script, which will give a list of BLE devices.
"""

import serial
import serial.tools.list_ports
def dev_identify():
    ports = list(serial.tools.list_ports.comports()) # will give list of Active COM Ports
    for p in ports:                                                  
        #print(str(p))
        port = str(p)[:4]    #slicing for exact COMport number
        baud = 9600
        #global ser
        ser = serial.Serial(port, baud, timeout=1)
       # print(ser)
       # open the serial port
        if ser.isOpen():
            print(ser.name + ' is open')
            cmd="ATI\r"
            ser.write(cmd.encode())
            msg=ser.read(64)
            print(msg)  #print(type(msg))==> str
            #print(len(msg))
            print(msg[35:52])
            s=msg[35:52]
            if s == "":
                print("This is Not a BLE device")
    return

dev_identify()

                                Request: Please provide your valuable comments

Tuesday 10 January 2017

XMPP protocol overview with Images.

XMPP Protocol (eXtensible Messaging and Presence Protocol.):
============
Introduction
XMPP is a communications protocol for message-oriented middleware based on Extensible Markup Language (XML) & has been used for publish-subscribe systems, signaling for VoIP, video, file transfer, gaming, the Internet of Things (IoT) applications.
eXtensible:  Not limited to initial conditions & XMPP can be customized to individual needs. (Machine to machine communication)
Messaging: Primary method of communication is a transmission of short messages between “Server & Client “and “Client & Client”
Presence:  Reactive to user’s presence & status. XMPP uses Presence driven logic to trigger events.

Protocol: XMPP is not a proprietary language. XMPP is based on standardization from the XML standards Federation. XMPP is an open platform.




XMPP takes place inside a single data stream between user and server.


Communication in the XMPP server is broken into Stanzas (sections).
Stanzas are short contained XML messages sent through the server between clients and other clients”, “Servers & Clients “, and as well as Servers & Servers”,
Stanzas come in 3 types Presence, IQ, Messages.
1.      Presence Stanza: 

·         Used to indicate User Status & can be used as a trigger for events inside the server.
·         Presence is shared with all users on Roster (Ex: if you have somebody on your Roster & they Login, you will receive a Presence stanza from them)
·         Presence may be sent by components, servers, or clients.
·         5 different show tags used to indicate status along with presence” chat, away, Xa, DND, Unavailable “.
Initial Presence:
·         Presence is sent to the Server from Client once login finished. After that Server delivers presence to any interested Parties, have on the Roster.
Presence Probe:
·         Act as “Are you there?” statement” to verify that connected resources are still in ONLINE, this can be a handle for different clients. Probing typically by the server.
·         Presence probes not used If User and Server are on the same machine
Presence Broadcast:
·          Used when changing status, like Away.
<presence>
                <show>away</ show>
</presence>
This presence stanza sent to the server, that server delivers to interested parties have on the Roster.  A presence stanza MUST NOT contain more than one <show/> element.
away -- The entity or resource is temporarily away.

·         chat -- The entity or resource is actively interested in chatting.

·         dnd -- The entity or resource is busy (dnd = "Do Not Disturb").

·         xa -- The entity or resource is away for an extended period (xa =
·         "eXtended Away").

   If no <show/> element is provided, the entity is assumed to be online
   and available.

2.      IQ(Info-Query) Stanza
·         The primary method how information is obtained and sent.
·         Can be used to request/change settings.
·         Provide for a Request and response mechanism.
·         There are 4 different types of IQ stanzas (Set, Get, Result, and Error)
IQ(Info-Query)- Service discovery (disco)
·         disco can be used to find out details about Users, Servers, Features etc…
·         disco#items requests available items (MUC rooms, users, services)
·         disco#info requests information about a specific entity
requests are made like this
<iq from =’yourjid@example.com’ id=’22’to=’example.com’ type=’get’>
        <query xmlns=’http://jabber.org/protocol/disco#items’/>
</iq>
To jid may be to server, components, or users.
From jid is not always necessary.
3.      Message Stanza
·         Designed to carry person to person text.
·         Can be extended to deliver rich text or different formatting.
·         There are 5 different message types
o    Chat-one-on-one messages between two users.
o    Group chat- messages being sent to &from MUCs (Multiple user chats)
o    Headline- alert messages that do not expect a reply
o    Normal- Standalone message with no history, but the reply is expected.
o    Error- messages reserved for error delivery.
Components
·         Items of the code that can extend, or provide services to the server.
·         Typically come with a server install, however, there may be separate components that are added to the server installation after server up and running, and can be turned on or off depending upon server installation.
·         Will typically have a JID assigned to components.
·         Examples of components.
o    HTTP interface
o    MUC
o    AMP
o    Jingle

                                Request: Please provide your valuable comments

Monday 9 January 2017

IETF (Internet Engineering Task Force) defines standard Internet operating protocols such as TCP/IP

What is IETF (Internet Engineering Task Force):
=====================================
  • IETF develops and promotes voluntary Internet standards, in particular, the standards that comprise the Internet protocol suite (TCP/IP)
  • IETF is a large open international community/organization of network standards , with no formal membership for the Internet.

Friday 6 January 2017

Small UI development Program using Python

Small UI development Program using Python :

When a new person joined in a project, The person needs basic information regarding the project.
__author__ = "Narendra Boyina"

# Python version 3.5.2
import os
from tkinter import *
#from docx import *
w = Tk()
w.title("Laird project")
w.geometry("600x600+200+100")
n = 'Times New Roman',12,'italic'

def Ofileopen():
    os.system("notepad {0}".format(r'D:\waste\Fleet STEL.txt'))
    #give the path where the file is located (raw input)
def Ffileopen():
    os.system("notepad {0}".format(r'D:\waste\Fleet STEL.txt'))
def Tfileopen():
    os.system("notepad {0}".format(r'D:\waste\TR100STEL.txt'))
def Afileopen():
    os.system("notepad {0}".format(r'D:\waste\TR100STEL.txt'))
##    f = open('D:\\waste\\TR100STEL.txt','r')
##    Label(text=f.read(),font=(n)).pack()

def mmm():
    a= v.get()
    if(a == 1):
        a1=Tk()
        a1.title("Orion")
        Label(a1,text='Wlcome to Orion device').pack()
        button = Button(a1,text='Open File',width=30, command =Ofileopen).pack()
    elif(a == 2):
        a2=Tk()
        a2.title("Fleet")
        button = Button(a2,text='Open File',width=30, command =Ffileopen).pack()
    elif(a == 3):
        a3=Tk()
        a3.title("TR100")
        Label(a3,text='Wlcome to TR100 device').pack()
        button = Button(a3,text='Open STEL File',width=30, command =Tfileopen).pack()
        button = Button(a3,text='Open API File',width=30, command =Afileopen).pack()
mymenu = Menu()# object  created to holds horizontal list

listone = Menu()    #This  object is for holding list of File commands(New File, Open Save Exit)
listone.add_command(label='Overview of the Project')
##listone.add_command(label='Open File')
##listone.add_command(label='Save File')
##listone.add_command(label='Exit')

listtwo =  Menu()  # This object is for holding list of  project members
listtwo.add_command(label='Ravi Naga kumar')
listtwo.add_command(label='Kumar Akshat')
listtwo.add_command(label='Sivaram Prasad')
listtwo.add_command(label='Vidya Sagar')
listtwo.add_command(label='Narendra')

listthree = Menu() # This object is for holding list of Softwares & software tools
listthree.add_command(label='Renesas_Flash_Programmer')
listthree.add_command(label='FleetBootMonitor')
listthree.add_command(label='--------------')
listthree.add_command(label='DevSuite')
listthree.add_command(label='Bugzilla')

listfour =  Menu()  # This object is for holding list of  Hardware Tools
listfour.add_command(label='Gryphon Simulator')
listfour.add_command(label='RFchamber')
listfour.add_command(label='Lab Sat Simulator')
listfour.add_command(label='RPS')

listfive =  Menu()  # This object is for holding list of  contact info
listfive.add_command(label='Ravi-9945324200')
listfive.add_command(label='Siva-9951421342')
listfive.add_command(label='Akshat-9722525280')
listfive.add_command(label='Sagar-9448547552')
listfive.add_command(label='Narendra-9700422902')

mymenu.add_cascade(label="Home",menu=listone,)
mymenu.add_cascade(label="Project members",menu=listtwo)
mymenu.add_cascade(label="Softwares & S/W Tools",menu=listthree)
mymenu.add_cascade(label="H/W Tools",menu=listfour)
mymenu.add_cascade(label="Contact info",menu=listfive)
mymenu.add_cascade(label="Help")
w.config(menu =mymenu) # myGui  object is the window(  We are adding/ configuring menu items)
v=IntVar()
v.set(2)

Devices = [("Orion",1),("Fleet",2),("TR100",3)]
Label(w,text='Choose the device for STEL Document',padx=20).pack(anchor=W)
for txt,val in Devices:
             Radiobutton(w,text=txt,padx=40,indicatoron=0,variable=v,command=mmm,value=val).pack(anchor=W)
w.mainloop()