{"id":16713666,"url":"https://github.com/astronomersiva/ensembletech","last_synced_at":"2025-07-01T10:03:02.891Z","repository":{"id":64137776,"uuid":"27710834","full_name":"astronomersiva/ensembleTech","owner":"astronomersiva","description":"My intern projects in Raspberry Pi and Python for Ensemble Tech. ","archived":false,"fork":false,"pushed_at":"2014-12-12T08:50:06.000Z","size":1572,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-07-01T10:02:48.844Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/astronomersiva.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-12-08T11:04:02.000Z","updated_at":"2018-03-20T04:28:01.000Z","dependencies_parsed_at":"2023-01-14T23:45:49.328Z","dependency_job_id":null,"html_url":"https://github.com/astronomersiva/ensembleTech","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/astronomersiva/ensembleTech","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/astronomersiva%2FensembleTech","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/astronomersiva%2FensembleTech/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/astronomersiva%2FensembleTech/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/astronomersiva%2FensembleTech/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/astronomersiva","download_url":"https://codeload.github.com/astronomersiva/ensembleTech/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/astronomersiva%2FensembleTech/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262941536,"owners_count":23388147,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-12T20:47:38.421Z","updated_at":"2025-07-01T10:03:02.866Z","avatar_url":"https://github.com/astronomersiva.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n\u003cstyle\u003e\n    img{\n        height: 500px;\n        width:  500px;\n        align: center;\n    }\n\u003c/style\u003e\n\n# Getting started with Python\n\nPython is an interpreted, high level language that emphasises on the code\nreadability and its functions rather than the syntax. It also has a lot of\nbuilt-in methods and tools that allow programmers to express their code in very\nless lines of code. For this reason, it has been widely used for various\npurposes. It is also supported by the open source community and because of this,\nyou will find modules for everything right from email fetching to complex tasks\nlike image recognition.\n\nRaspberry Pi can be programmed using the Python language as well as the new,\nfeature rich Wolfram language.\n\n#### Basics of Python\n\nThe customary starting point of learning any programming language: Printing\n'hello world!'\n\n\n    print 'hello world!'\n\n    hello world!\n\n\nIn Python, you don't have to worry about memory allocation or specifying the\ndata type of variables unlike commonly used languages like C, C++ and Java. This\nmakes it easy for beginners and experts to concentrate on their code\nfunctionality. Also, Python uses indentation to specify blocks(instead of\nsemicolons and brackets).\n\n\n\n    a = 10\n\n\n    print type(a) #type() returns the type of the variable.\n\n    \u003ctype 'int'\u003e\n\n\n\n    b = 10.01\n\n\n    print type(b)\n\n    \u003ctype 'float'\u003e\n\n\n\n    c = 'python'\n\n\n    print type(c)\n\n    \u003ctype 'str'\u003e\n\n\n\n    d = 'p'\n\n\n    print type(d)\n\n    \u003ctype 'str'\u003e\n\n\nNote that, in Python, string and character are not different data types.\n\n\n    listExample = [1, 2, 3] #list is the Python equivalent of arrays in C, C++, etc.\n\nThe only difference is that, in Python, lists can be heterogeneous in nature.\nThat is, a list's can have elements of different data types.\n\n\n    listExample = [1, 'a', 1.9]\n\nThe variable's data type can also be changed when necessary.\n\n\n    integer = 5\n\n\n    print type(integer)\n\n    \u003ctype 'int'\u003e\n\n\n\n    integer = 'changing the type'\n\n\n    print type(integer)\n\n    \u003ctype 'str'\u003e\n\n\n#### Getting input from the user\n\n\n    variable =  raw_input() \n\n    8\n\n\n\n    print type(variable)\n\n    \u003ctype 'str'\u003e\n\n\nNote that the raw_input() function stores values as strings by default.\n\nTo change this, use the following built in methods.\n\n\n    variable = int(raw_input())\n\n    6\n\n\n\n    print type(variable)\n\n    \u003ctype 'int'\u003e\n\n\n\n    variable = float(raw_input())\n\n    8\n\n\n\n    print variable, type(variable)\n\n    8.0 \u003ctype 'float'\u003e\n\n\nNote that, the print function can be used to print multiple values by separating\nthem with a comma.\n\nTo display a prompt to the user while getting input, specifying the prompt\nstring like:\n\n\n    a = raw_input(\"Enter your name\")\n\n    Enter your nameEnsemble Tech\n\n\n\n    a\n\n\n\n\n    'Ensemble Tech'\n\n\n\n#### Some commonly used built-in methods\n\n\n    list = [1, 3, 5, 2, 4, 1]\n\n\n    list.count(1) #the count of the element 1 in the list\n\n    2\n\n\n\n    list.sort() #sorts the list\n\n\n    list #the list has been sorted\n\n\n\n\n    [1, 1, 2, 3, 4, 5]\n\n\n\n\n    list.append(6) #add an element to the end of the list.\n\nIn Python, a string is basically a list of characters. For this reason, list\nmethods can also be used for strings. There are also some extra methods.\n\n\n    string = \"this is an example\"\n\n\n    string.capitalize() #capitalizes the first letter of the string\n\n\n\n\n    'This is an example'\n\n\n\n\n    string = 'single quotes can also be used'\n\nBut make sure that you don't use ' and \" together. For example,\n\n\n    dontDoThis = 'look at the error\"\n\n\n      File \"\u003cipython-input-23-1868471ea474\u003e\", line 1\n        dontDoThis = 'look at the error\"\n                                       ^\n    SyntaxError: EOL while scanning string literal\n\n\n\n#### Loops and conditions\n\nIf, if..else, nested if:\n\n\n    if True:\n        print 'this'\n\n    this\n\n\n\n    if False:\n        print 'hello'\n    else:\n        print 'hello world'\n\n    hello world\n\n\n\n    a = 5\n\n\n    if a \u003e 5:\n        print 'this computer is very poor at Math'\n    else:\n        print 'Come on! Even a kid can say this'\n\n    Come on! Even a kid can say this\n\n\nNested if is achieved by using elif statements.\n\n\n    #this example uses whatever we have learnt till now\n    #can you guess the output without scrolling down?\n    userInput = int(raw_input(\"Enter something\"))\n    inType = type(userInput)\n    if inType == str: #== is used for checking equality. Use = only for assignment\n        print \"you entered a string\" #or maybe you forgot to cast it to the required type. Use int() or float()\n    elif inType == float:\n        print \"you entered a float value\"\n    elif inType == list:\n        print \"that is a list\"\n    else:\n        print \"This is an integer.\" #properly typed because this is the right output.\n\n    Enter somethingsomething\n\n\n\n    ---------------------------------------------------------------------------\n    ValueError                                Traceback (most recent call last)\n\n    \u003cipython-input-31-2d0aa59e6b53\u003e in \u003cmodule\u003e()\n          1 #this example uses whatever we have learnt till now\n          2 #can you guess the output without scrolling down?\n    ----\u003e 3 userInput = int(raw_input(\"Enter something\"))\n          4 inType = type(userInput)\n          5 if inType == str: #== is used for checking equality. Use = only for assignment\n\n\n    ValueError: invalid literal for int() with base 10: 'something'\n\n\nNo, I was cheating. You can't convert a string to an integer unless it has only\nnumbers. For example, you can change '9898' to a string but changing 'asdasdsad'\nto a number is not possible.\n\n\n    #this example uses whatever we have learnt till now\n    #can you guess the output without scrolling down?\n    userInput = int(raw_input(\"Enter something: \"))\n    inType = type(userInput)\n    if inType == str: #== is used for checking equality. Use = only for assignment\n        print \"you entered a string\" #or maybe you forgot to cast it to the required type. Use int() or float()\n    elif inType == float:\n        print \"you entered a float value\"\n    elif inType == list:\n        print \"that is a list\"\n    else:\n        print \"This is an integer.\" #properly typed because this is the right output.\n\n    Enter something: 123\n    This is an integer.\n\n\n#### Loops:\n\nFor loop: Uses range() and xrange() to iterate through a series of values.\n\n\n    range(1, 10) #series of values from 1 upto 10(excluding 10)\n\n\n\n\n    [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\n\n\n    xrange(1, 10)\n\n\n\n\n    xrange(1, 10)\n\n\n\nThe difference between range() and xrange() is beyond the scope of Python\napplication in RPi. However, in brief, use range() in situations where you need\nthe values in the series(like printing numbers from 1 to 100). Use xrange() when\nyou don't need the values(like printing hello world 100 times). You can use any\nof the two but using them according to the above guidelines will result in an\noptimised code.\n\n\n    for number in range(2):\n        print number\n\n    0\n    1\n\n\nNote that the arguments of both range() and xrange() is of the form\n(x)range(start, stop[, step]). Here the stop parameter is mandatory. The start\nparameter is 0 by default. step parameter allows you to go through the list in\nincrements. For example,\n\n\n    range(0, 10, 2) #note that the start parameter is needed if a step is provided.\n\n\n\n\n    [0, 2, 4, 6, 8]\n\n\n\n\n    a = 5\n    while a \u003c 10:\n        print a\n        a += 1 #the increment and decrement operators are not present in Python\n\n    5\n    6\n    7\n    8\n    9\n\n\nPython doesn't provide a switch case construct. Use nested if(with elif) when\nnecessary.\n\n#### User defined methods\n\nThe basic syntax is :\n\ndef functionName(optional, parameters, if, needed):\n    the function\n    does this\n\n\n    def evenCheck(number):\n        if (number % 2) == 0:\n            return True\n        else:\n            return False\n    \n    def anotherImplementation(number):\n        if (number % 2) == 0:\n            return \"even\"\n        else:\n            return \"odd\"\n    \n    for testCase in xrange(2): \n        n = int(raw_input())\n        if evenCheck(n):\n            print \"the number is even\"\n        else:\n            print \"the number is odd\"\n            \n        result = anotherImplementation(n)\n        print \"The number is \" + result #string concatenation can be done with the + operator\n        print \"The number %d is %s\" %(n, result)\n\n    3\n    the number is odd\n    The number is odd\n    The number 3 is odd\n    4\n    the number is even\n    The number is even\n    The number 4 is even\n\n\n### Raspberry Pi with Python\n\nIn combination with the above mentioned Python basics, you can use the RPi.GPIO\nmodule to program the GPIO pins of the Raspberry Pi. This module is already\navailable in RPi so you don't have to install it. If you need any additional\nmodules, launch the terminal in the RPi and use the command sudo pip install\nmoduleName\n\n\n    import RPi.GPIO as GPIO #imports the module. using the 'as GPIO' makes it possible to use all the \n                            #module components as GPIO.something instead of RPi.GPIO.something\n\nThe following are some basics. An extensive documentation can be found here:\nhttp://pythonhosted.org/RPIO/\n\n\n    GPIO.setmode(GPIO.BOARD) #sets the numbering scheme according to the board\n    GPIO.setwarnings(False)  #sets warnings to false. cleaner ouput.\n    GPIO.setup(7, GPIO.OUT)  #set pin 7 as output\n    GPIO.output(7, True)     #Set the output as true. In simple terms, light on\n    GPIO.output(7, False)    #sets the output to false. In simple terms, light off\n    GPIO.cleanup()           #reset every channel that has been set up by this program,\n                             # and unexport interrupt gpio interfaces\n\nMake sure you don't use the wrong pins. This image from http://www.raspberrypi-\nspy.co.uk/2014/07/raspberry-pi-b-gpio-header-details-and-pinout/ should give you\nan idea of what to use and what not to use.\n\n\u003cimg src = \"gpio.png\"\u003e\n\nHere is a simple program to turn on an LED.\n\n\n    import RPi.GPIO as GPIO\n    import time\n    \n    GPIO.setmode(GPIO.BOARD)\n    GPIO.setwarnings(False)\n    GPIO.setup(7, GPIO.OUT)\n    \n    GPIO.output(7, True)\n    time.sleep(3)\n    GPIO.output(7, False)\n\nThis program turns on the LED, keeps it on for 3 seconds and then turns it off.\n\nTo make the LED blink at specific time intervals(say blink thrice. once in every\ntwo seconds)\n\n\n    import RPi.GPIO as GPIO\n    import time\n    \n    GPIO.setmode(GPIO.BOARD)\n    GPIO.setwarnings(False)\n    GPIO.setup(7, GPIO.OUT)\n    \n    for blink in xrange(3):\n        GPIO.output(7, True)\n        time.sleep(0.5)\n        GPIO.output(7, False)\n        time.sleep(2)\n\n\u003cimg src = \"pinDiagrams/singleLed.png\"\u003e\n\nTo do the same with multiple LEDS,\n\n\n    #one led blinks, then the next..waits \n    #for two seconds and then repeats it.\n    \n    import RPi.GPIO as GPIO\n    import time\n    \n    GPIO.setmode(GPIO.BOARD)\n    GPIO.setwarnings(False)\n    GPIO.setup(3, GPIO.OUT)\n    GPIO.setup(7, GPIO.OUT)\n    \n    for blink in xrange(3):\n        GPIO.output(7, True)\n        time.sleep(0.5)\n        GPIO.output(7, False)\n        GPIO.output(3, True)\n        time.sleep(0.5)\n        GPIO.output(3, False)\n        time.sleep(2)\n\n\u003cimg src = \"pinDiagrams/twoLed.png\" style = \"height: 200px, width: 200px\"\u003e\n\nTo do the same with a user input for the number of times and the blink duration,\nuse the following code.\n\n\n    import RPi.GPIO as GPIO\n    import time\n    \n    #turns on and blinks an LED for a number of times\n    #specified by the user.\n    \n    GPIO.setmode(GPIO.BOARD)\n    GPIO.setwarnings(False)\n    GPIO.setup(7, GPIO.OUT)\n    \n    try:\n        noOfTimes = int(raw_input(\"Enter the number of blinks\"))\n    except:\n        print 'Please enter an integer value'\n    \n    try:\n        blinkDuration = float(raw_input(\"Enter the duration of the blinks\"))\n    except:\n        print 'Please enter a number'\n    \n    for n in xrange(noOfTimes):    \n        GPIO.output(7, True)\n        time.sleep(blinkDuration)\n        GPIO.output(7, False)\n        time.sleep(blinkDuration)\n\n\nHere is a simple program to control LED in a Rasberry Pi using your voice\n\nThis uses SL4A, a scripting tool for Android with Python for Android enabled in\nit. The setup is pretty easy and straightforward. Along with it, use the\nfollowing commands in your RPi to install the required modules.\n\n`sudo apt-get python-pip`\n\n`sudo pip install pygmail`\n\nEnter the following command in your SL4A interpreter\n\n\n    import os\n    import glob\n    import mimetypes \n    from email import encoders\n    from email.mime.audio import MIMEAudio\n    from email.mime.base import MIMEBase\n    from email.mime.image import MIMEImage\n    from email.mime.multipart import MIMEMultipart\n    from email.mime.text import MIMEText\n    \n    def attach_files(msg, attachements):\n      for attachment in attachments:\n        attachment = attachment.strip()\n        for path in glob.glob(attachment):\n          filename = os.path.basename(path)\n          if not os.path.isfile(path):\n            continue\n          # Guess the content type based on the file's extension.  Encoding\n          # will be ignored, although we should check for simple things like\n          # gzip'd or compressed files.\n          ctype, encoding = mimetypes.guess_type(path)\n          if ctype is None or encoding is not None:\n            # No guess could be made, or the file is encoded (compressed), so\n            # use a generic bag-of-bits type.\n            ctype = 'application/octet-stream'\n          maintype, subtype = ctype.split('/', 1)\n          if maintype == 'text':\n            fp = open(path)\n            # Note: we should handle calculating the charset\n            part = MIMEText(fp.read(), _subtype=subtype)\n            fp.close()\n          elif maintype == 'image':\n            fp = open(path, 'rb')\n            part = MIMEImage(fp.read(), _subtype=subtype)\n            fp.close()\n          elif maintype == 'audio':\n            fp = open(path, 'rb')\n            part = MIMEAudio(fp.read(), _subtype=subtype)\n            fp.close()\n          else:\n            fp = open(path, 'rb')\n            part = MIMEBase(maintype, subtype)\n            part.set_payload(fp.read())\n            fp.close()\n            # Encode the payload using Base64\n            encoders.encode_base64(part)\n          # Set the filename parameter\n          part.add_header('Content-Disposition', 'attachment', filename=filename)\n          msg.attach(part)\n    \n    def sendemail(email_name, email_user, email_pswd, mailto, subject, body, attachments):\n      import smtplib\n    \n      # DON'T CHANGE THIS!\n      # ...unless you're rewriting this script for your own SMTP server!\n      smtp_server = 'smtp.gmail.com'\n      smtp_port = 587\n    \n      # Build an SMTP compatible message\n      msg = MIMEMultipart()\n      msg['Subject'] = subject\n      msg['To'] = mailto\n      msg['From'] = email_name + \" \u003c\" + email_user + \"\u003e\"\n      msg.attach(MIMEText(body, 'plain'))\n      attach_files(msg, attachments)\n    \n      # Attempt to connect and send the email\n      try:\n        smtpObj = '' # Declare within this block.\n        # Check for SMTP over SSL by port number and connect accordingly\n        if( smtp_port == 465):\n          smtpObj = smtplib.SMTP_SSL(smtp_server,smtp_port)\n        else:\n          smtpObj = smtplib.SMTP(smtp_server,smtp_port)\n        smtpObj.ehlo()\n        # StartTLS if using the default TLS port number\n        if(smtp_port == 587):\n          smtpObj.starttls()\n          smtpObj.ehlo\n        # Login, send and close the connection.\n        smtpObj.login(email_user, email_pswd)\n        smtpObj.sendmail(email_user, mailto, msg.as_string())\n        smtpObj.close()\n        return 1  # Return 1 to denote success!\n      except Exception, err:\n        # Print error and return 0 on failure.\n        print err\n        return 0\n    \n    import sys\n    import android\n    \n    droid = android.Android()\n    \n    email_name = \"Your Name\"\n    email_user = \"emailid@gmail.com\"\n    email_pswd = \"password\"\n    mailto = \"emailid@gmail.com\"\n    subject = \"LED\"\n    attachments = ''\n    \n    body = droid.recognizeSpeech().result\n    \n    \n    if (sendemail(email_name, email_user, email_pswd, mailto, subject, body, attachments)):\n          sys.exit(0)\n    else:\n          droid.makeToast(\"Failed to send email\")\n      \n\nAnd save the following code in your Raspberry Pi\n\n\n    import gmail\n    import RPi.GPIO as GPIO\n    import time\n    \n    GPIO.setmode(GPIO.BOARD)\n    GPIO.setwarnings(False)\n    GPIO.setup(7, GPIO.OUT)\n    \n    print 'authenticating. please wait'\n    \n    g = gmail.login('username', 'password')\n    while True:\n    \tcommandMails = g.inbox().mail(unread = True, sender = 'sourceEmailgmail.com', subject = 'LED')\n    \ttry:\t\n    \t\tcommandMails[0].fetch()\n    \t\tcommand = commandMails[0].body.lower()\n    \t\tcommandMails[0].delete()\n    \t\tif 'light' in command or 'lite' in command:\n    \t\t\tif 'on' in command:\n    \t\t\t\tGPIO.output(7, True)\n    \t\t\tif 'off' in command or 'of' in command:\n    \t\t\t\tGPIO.output(7, False)\n    \t\telse:\n    \t\t\tpass\n    \texcept:\n    \t\ttime.sleep(10)\n\nRun both the codes and see the magic. You can easily modify this code to control\nmore than one LED. By adding a few more if..elif..else or the more complex set\nintersection approach, you can create something like a home automation system.\n\n### The next level of RPi projects...\n\nTill now, we have only seen how to control the RPi using the internet. We used\nan email based approach which may not be effective all the time. A better\napproach would be to use the RPi's networking capabilities and use some other\ndevice connected to the same local network that the RPi is in to control the\nGPIO pins.\n\n\nYou can use either Python or nodeJS(a Javascript based runtime environment for\nserver-side and networking applications).\n\nHere is a Python based approach.\n\nWe will be using lighttpd to run a server on the Raspberry Pi. To install\nlighttpd, use\n\n`sudo apt-get install lighttpd`\n\nNow open the file browser in your RPi and type this in the address bar:\n\n`/var/www/`\n\nCreate an index.html with contents according to your wish.\n\n\u003chtml\u003e\n  \u003chead\u003e\n    \u003ctitle\u003eEnsemble Tech\u003c/title\u003e\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003ch1\u003eHello World!\u003c/h1\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n\nIf you are not able to create this file, use the following commands after\nstarting the terminal.\n\n`cd /var/www/`\n\n`chmod -R 777`\n\nand then create the index.html file.\n\nTo test this, open the terminal and run\n\n`sudo service lighttpd start`\n\nNow using any device that is connected to the same local network that the RPi is\nin, open a web browser of your choice and type the IP address of the RPi in the\naddress bar. You can find this using the `ip addr show` command. If all goes\nwell(it usually does if you have followed the instructions), you will be able to\nsee the index file you had created previously.\n\nWe will using FastCGI to run our Python program on the server. To install, use\n\n`sudo apt-get install python-flup`\n\nCreate the following file in the /var/www/ path and change its permissions to\n755. Use `chmod -R led.py` . Note that you can give any file name but remember\nthis for later use.\n\n\n    #!/usr/bin/pythonRoot\n    import RPi.GPIO as GPIO     \n    from flup.server.fcgi import WSGIServer \n    import sys\n    import urlparse\n     \n    # set up our GPIO pins\n    GPIO.setmode(G.BOARD)\n    GPIO.setup(7, GPIO.OUT) #use any GPIO pin\n     \n    \n    def app(environ, start_response): \n      start_response(\"200 OK\", [(\"Content-Type\", \"text/html\")])\n      i = urlparse.parse_qs(environ[\"QUERY_STRING\"])\n      yield ('\u0026nbsp;')\n      if \"led\" in i:\n        if i[\"led\"][0] == \"on\": \n          GPIO.output(7, True)   # Turn it on\n        elif i[\"led\"][0] == \"off\":\n          GPIO.output(7, False)  # Turn it off\n     \n    WSGIServer(app).run()\n\nWe need to run Python for this script. However, doing so with default settings\nwill result in security issues as you will have to provide sudo rights to\ncontrol GPIO with Python. To avoid this,\n\nls -l /usr/bin/python\n\nNote the version of your Python from the result of the above command. Use that\nversion number(for eg. if it is 2.7) as\n\nsudo cp /usr/bin/python2.7 /usr/bin/pythonRoot\nsudo chmod u+s /usr/bin/pythonRoot\n\nGo to the directory /etc/lighttpd in the file browser and change the file\npermissions as mentioned earlier. This is to enable editing of the lighttpd.conf\nfile.\n\nOpen the lighttpd.conf file and add mod_fastcgi to the server.modules list.\n\nThen, add this to the conf file at the end.\n\nfastcgi.server = (\n   \".py\" =\u003e (\n     \"python-fcgi\" =\u003e (\n       \"socket\" =\u003e \"/tmp/fastcgi.python.socket\",\n       \"bin-path\" =\u003e \"/var/www/doStuff.py\",\n       \"check-local\" =\u003e \"disable\",\n       \"max-procs\" =\u003e 1)\n    )\n )\n\nTo test this, you will have to restart the server. To do so, use any of the two\nfollowing techniques(the former is an obviously better approach):\n\n`sudo service lighttpd restart`\n\u003cbr\u003eOr\u003cbr\u003e\n`sudo service lighttpd stop`\n\u003cbr\u003e\n`sudo service lighttpd start`\n\nIf you open the same address in your browser(192.168.0.32 in my case), you will\nsee the same index.html. Now do the following in the URL.\u003cbr\u003e\n192.168.0.32/led.py?led=on\n\u003cbr\u003eThe LED will now turn on.\u003cbr\u003e\n192.168.0.32/led.py?led=off\n\u003cbr\u003eThe LED will now turn off.\u003cbr\u003e\n\n### Capturing photos over network\n\n##### Server code(the computer where the images are to be saved). \n\n\n    import io\n    import socket\n    import struct\n    from PIL import Image\n    import os\n    \n    # Start a socket listening for connections on 0.0.0.0:8000 (0.0.0.0 means\n    # all interfaces)\n    server_socket = socket.socket()\n    server_socket.bind(('0.0.0.0', 8000))\n    server_socket.listen(0)\n    \n    # Accept a single connection and make a file-like object out of it\n    connection = server_socket.accept()[0].makefile('rb')\n    try:\n        os.mkdir('RPi')\n    except:\n        os.chdir('RPi')\n    count = 1\n    \n    try:\n        while True:\n            # Read the length of the image as a 32-bit unsigned int. If the\n            # length is zero, quit the loop\n            image_len = struct.unpack('\u003cL', connection.read(struct.calcsize('\u003cL')))[0]\n            if not image_len:\n                break\n            # Construct a stream to hold the image data and read the image\n            # data from the connection\n            image_stream = io.BytesIO()\n            image_stream.write(connection.read(image_len))\n            # Rewind the stream, open it as an image with PIL and do some\n            # processing on it\n            image_stream.seek(0)\n            image = Image.open(image_stream)\n            image.save(str(count) + '.jpg')\n            count += 1\n            print('Image is %dx%d' % image.size)\n            image.verify()\n            print('Image is verified')\n    finally:\n        connection.close()\n        server_socket.close()\n\n\nOn the Raspberry pi, use the following code. In the place of my_server, use the\nip address of your server. Run ifconfig to find out the IP.\n\n\n    import io\n    import socket\n    import struct\n    import time\n    import picamera\n    \n    # Connect a client socket to my_server:8000 (change my_server to the\n    # hostname of your server)\n    client_socket = socket.socket()\n    client_socket.connect(('my_server', 8000))\n    \n    # Make a file-like object out of the connection\n    connection = client_socket.makefile('wb')\n    try:\n        with picamera.PiCamera() as camera:\n            camera.resolution = (640, 480)\n            # Start a preview and let the camera warm up for 2 seconds\n            camera.start_preview()\n            time.sleep(2)\n    \n            # Note the start time and construct a stream to hold image data\n            # temporarily (we could write it directly to connection but in this\n            # case we want to find out the size of each capture first to keep\n            # our protocol simple)\n            start = time.time()\n            stream = io.BytesIO()\n            for foo in camera.capture_continuous(stream, 'jpeg'):\n                # Write the length of the capture to the stream and flush to\n                # ensure it actually gets sent\n                connection.write(struct.pack('\u003cL', stream.tell()))\n                connection.flush()\n                # Rewind the stream and send the image data over the wire\n                stream.seek(0)\n                connection.write(stream.read())\n                # If we've been capturing for more than 30 seconds, quit\n                if time.time() - start \u003e 30:\n                    break\n                # Reset the stream for the next capture\n                stream.seek(0)\n                stream.truncate()\n        # Write a length of zero to the stream to signal we're done\n        connection.write(struct.pack('\u003cL', 0))\n    finally:\n        connection.close()\n        client_socket.close()\n\n### Interfacing Arduino with RPi\n\nFirst setup the serial pins on RPi\n\n`sudo cp /boot/cmdline.txt /boot/cmdline_backup.txt`\n\n`sudo nano /boot/cmdline.txt`\n\nChange this \u003cbr\u003e\n`dwc_otg.lpm_enable=0 console=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2\nrootfstype=ext4 elevator=deadline rootwait`\n\nTo\n\n`dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4\nelevator=deadline rootwait`\n\n`sudo nano /etc/inittab`\n\nSearch for ttyAMA0 and comment out that line by including a # in the beginning\nof that line.\n\nConnect the TX pin of the Arduino to RX of the RPi. Make sure that the ground of\nRPi is connected to the RPi as well.\n\nConsider the following example where the temperature readings are recorded and\nshared over a server. The client then plots a graph with that output data.\n\n###### Server(RPi)\n\n\n    #!/usr/bin/python\n    \n    import web\n    import serial\n    import time\n    \n    \n    urls = ('/', 'index')\n    \n    class index:\n        def GET(self):\n            s = serial.Serial('/dev/ttyAMA0')\n    \ttemp = int(s.readline().strip('\\n')) / 2\n            return str(temp)\n    \n    if __name__ == \"__main__\":\n        app = web.application(urls, globals())\n        app.run()\n\n###### Client side:\n\n\n    import urllib2\n    import time\n    import matplotlib.pyplot as plt\n    \n    t = []\n    tempValues = []\n    \n    print 'please wait..values are being read'\n    \n    for x in range(1, 10):\n        t.append(x)\n    \ttemp = int(urllib2.urlopen('http://192.168.0.32:8080').read())\n        print ldr\n        tempValues.append(ldr)\n    \n    plt.plot(t, lightValues)\n    plt.show()\n\n\nCommunicating with Arduino over serial port:\n\n\n    \n    void setup()\n    {\n      Serial.begin(9600);  \n    }\n    \n    void loop()\n    {\n      if(Serial.available())\n      {\n        while(Serial.available()\u003e0)\n        {\n          char inByte = Serial.read();\n          Serial.print(inByte);\n        }\n        Serial.print('\\n');\n        Serial.flush();\n      }\n      delay(3000);\n    }\n\n## Making a script run on startup in RPi\n\nUse crontab -e. Scroll to the bottom and type `@reboot command file \u0026` Press\nctrl+o, enter and then ctrl+x. You can use the same to run a particular script\nat various time intervals.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fastronomersiva%2Fensembletech","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fastronomersiva%2Fensembletech","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fastronomersiva%2Fensembletech/lists"}