Thursday, January 31, 2013

Send mail from your gmail account with C#

I'm currently working on a new project. I'm supposed to read from a USB temperature sensor, and log the temperature. And if the temperature is below a certain threshold temperature the application will warn the client thru mail.


And so now i have at least gotten the SendMail class working, and ready for implementation with the rest of the program. So here is the source code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;

namespace TempNET
{
    class SendMail
    {
        public string sendMail(string recieverMailAddress, string recieverName, string messageSubject, string messageBody)
        { // method for sending mail
            try
            {
                // using a GMail account
                var fromAddress = new MailAddress("gmailaccount@gmail.com", "Senders name"); 
                var toAddress = new MailAddress(recieverMailAddress, recieverName);
                const string fromPassword = "gmailaccount password";

                // create smtp client object containing all needed info
                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                };
                // create mail
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = messageSubject,
                    Body = messageBody
                })
                {
                    smtp.Send(message);
                }
                // mail sendt successfully
                return "Mail sendt";
            }
            catch (Exception ex)
            {
                // something failed, return error message
                return "Error: " + ex.Message;
            }
        }
    }
}

Monday, January 21, 2013

My first Python app for Android, and it works!

I tried making a simple app for controlling the RaspberryPi lights controller i made earlier. It was to be a simple script, only really making a POST to a web-interface hosted on my LAN. However, simple tasks get really complex when the only tool you have is the most alien-ass backwards developing studio kit-SDK i have ever laid my eyes on. Yes im talking about AndroidADT/Eclipse.

God, please explain to me why a simple project template that only displays a blank screen need to consist of 131 Files divided across 66 Folders?!


And why does my 4 core computer, sporting 8Gb of ram and another gig of VRAM load for an amount of time that surely involves the Avogadro constant before it's able to run my simple app (displaying a blank screen). Yea, it... aint great.

So after Android-ADT and Eclipse just pissed me off to no end i decided Java could go fuck itself; my time is better spent on Python.

To run and develop Python on Android you need a Python interpreter installed on your phone. This was the main thing putting me off Python for phones in the first place, as it adds some complexity for the end user. But in my case that's usually just me anyways. Pluss it's really just an app that you need to download:
QPython+ and it's on google play store (for free).

QPython+ has a nice, no bullshit userinterface, and comes with some preinstalled libs, a text-editor and a debugger. Everything you need to develop, debug and run Python on your phone.

This below is my app in Python; 1 file, 0 folders. If my math is correct the complexity dropped by exactly half an infinity:

import urllib
# you need urllib to connect to the url
import androidhelper
# androidhelper is included in QPython+
# gives easy access to lots of android stuff, like GUI

droid = androidhelper.Android() 

def turnLights():
 # This displays a dialog with 3 options
 # Program loops untill user wants to exit
 while True:  
     title = 'Light switch:'
     droid.dialogCreateAlert(title)
     droid.dialogSetItems(['On', 'Off', 'Exit'])
     droid.dialogShow() 
     response = droid.dialogGetResponse().result['item']
     if response == 0:
            # The app connects to one of two url's
            # The web server at that url determines what
            # to do based on the page requested
            urlon = "http://192.168.1.6:8080/?turn=on"
            sock = urllib.urlopen(urlon)
            content = sock.read() 
            sock.close()
            print content
     elif response == 1:
            urloff = "http://192.168.1.6:8080/?turn=off"
            sock = urllib.urlopen(urloff)
            content = sock.read() 
            sock.close()
            print content
     elif response == 2: 
            # The user pressed Exit
            break 
# Run the app    
turnLights()

Python for Android is just awesome. Each app starts out as just one simple .py file. Easy as that. My app takes up 699 bytes. And i did bug-fixes and debugging on my phone and used the on-screen keyboard to add a couple of missing indents.

 My simple, beautiful app; a functioning light switch:


Sunday, January 20, 2013

Add a python script to startup

Im rather new to linux, and this was the first time ever that i had to get a python script running at boot, and with root privileges.
Have to say it was rather straight forward. Nothing special for python, just had to add a line of code in
/etc/local.rc
Just opened it in nano:
sudo nano /etc/local.rc

 
and added to the file:
sudo python /home/pi/turn.py


Wednesday, January 16, 2013

C# code to switch lights thru web-interface

Using the WebBrowser controll in Visual Studio 2010 it's really easy to make a interface to access the web and send data.

The code below is what makes up the desktop app that uses my python web interface to switch lights.

private void button1_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://192.168.1.6:8080/?turn=on");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://192.168.1.6:8080/?turn=off");
        }

The app is just a web browser that navigates to my web-interface with the click of the buttons. Displaying the web interface in the small browser window.

Tuesday, January 15, 2013

Flatcables, saves you from soldering to pins



Old HDD flatcables or floppydrive cables go perfect for the GPIO pins on the Pi.
No need to buy any expensive special connectors when you can just use left-over junk, right?
It's a messy setup i know, but it works, and with time it will be neatly wrapped and polished.

Raspberry Pi GPIO web interface using webpy

Finally made a web-interface for the GPIO on my Raspberry Pi that controlls the lights in my living room.
The script uses webpy, and starts hosting a webpage on port 8080 that listens for visitors and parameters:
If i open the page:
http://192.168.1.6:8080/?turn=on
Lights will be switched on.
And this next one switches them off again:
http://192.168.1.6:8080/?turn=off

I put the source together after reading this guide to webpy:
http://cloud101.eu/blog/2012/04/24/python-for-the-web-with-webpy/#more-

webpy is installed easy from apt-get:
       sudo apt-get install python-webpy

Here is the script:

#!/usr/bin/env python
# first line points to path for python

# we import the webpy library
import web

import RPi.GPIO as GPIO

#dont bug me with warnings
GPIO.setwarnings(False)

# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)

# set up GPIO output channels
GPIO.setup(18, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)

urls = ('/','root')
app = web.application(urls,globals())
 
class root:
 
    def __init__(self):
        self.hello = "snakes on a pie!"
 
    def GET(self):
        getInput = web.input(turn="")
        kommando = str(getInput.turn)
        if kommando == "on":
            #    set RPi board pins high
            GPIO.output(18, GPIO.HIGH)
            GPIO.output(16, GPIO.HIGH)
            return "Lights on"
        if kommando == "off":
            #    set RPi board pins low
            GPIO.output(18, GPIO.LOW)
            GPIO.output(16, GPIO.LOW)
            return "Lights off"
 
if __name__ == "__main__":
        app.run()

Saturday, January 12, 2013

How to display code on the web properly

When i started this blog, one of the problems i soon ran into was: how to display highlighted source code on my blog. You cant just copy it, because then the syntax-colors disapear and  it's unreadable.


blogspot.com has a [code] tag you can use, but it doesnt really do much, just changes the font really.

But i have found the solution:
http://tohtml.com/
It is a great site! It takes source code in pretty much any language and spits out HTML with beautiful highlighting that you can just copy and paste right to you blog.
Job done in short of a second.
http://tohtml.com/



C# method for printing ASCI images to console

Im currently taking a course in C# and the introductory is mostly console apps.
Console app are a nice, to-the-point programs, but after spending hours piecing it together its mind-rapingly terrible to watch such a dull interface.
So to spice things up abit and make the app truly your own it's nice to implement some ASCI art.


So you go download some ASCI image, for example here:
http://www.chris.com/ascii/index.php?art=cartoons/felix%20the%20cat
You copy paste it to a text file, lets call it felix.txt
Now problem is: how do you implement felix.txt into your console app?

So here is a C# method i wrote for just that. And it also implements delay. So you can make it look like a old school terminal, typing one char at a time (set timeout to 0 to just print the image)


static void printASCI_img(string file, int timeout)
        // prints ASCI text file to console
        // pause between every char given in milliseconds
        {
            try
            {
                byte[] img1;
                img1 = File.ReadAllBytes(file);

                foreach (byte i in img1)
                {
                    Console.Write(Convert.ToChar(i));
                    System.Threading.Thread.Sleep(timeout);
                }
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

Raspberry Pi GPIO example code in python

Im building a system for controlling the lights in my home from my raspberry pi.
So i've hooked up two solid state relays to the gpio pins om my RPi and i've made this python script for controlling it.

This script requires that you have installed RPi.GPIO
http://code.google.com/p/raspberry-gpio-python/
download the .deb file here

And you need to run the script as root since that's a requirement for access to the GPIO pins.

So currently i can run this script from my computer or phone via SSH, wich is alot better than walking around hitting switches, but im on a mission to develop a web-interface so it will be even more easy to use. Since not everyone in my household is tech savvy enough to make easy use of things like SSH.









# GPIO-OnOff.py
# written by fredrik 12.january.2013
#
# raspberry pi GPIO extentions
# requires root for access to the GPIO pins
import RPi.GPIO as GPIO

#dont bug me with warnings
GPIO.setwarnings(False)

# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)

# set up GPIO output channels
GPIO.setup(18, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)


x = 0
def on():
    print ("Lights On")
#    set RPi board pins high
    GPIO.output(18, GPIO.HIGH)
    GPIO.output(16, GPIO.HIGH)
 
def off():
    print ("Lights Off")
#    set RPi board pins low
    GPIO.output(18, GPIO.LOW)
    GPIO.output(16, GPIO.LOW)
 
menu = [off,on]
 
while x < len(menu) :
    print "Lights",menu[x].__name__,", press","["+str(x)+"]"
    x += 1
 
c = input()
menu[c]()




Wednesday, January 9, 2013

Is there a caffeinated cereal out there?!?

I woke up today after about 4 hours of sleep. Brain barely functioning, mixing milk in my cereal while chugging my third cup of coffee when i realize; "Hey! This is too many operations! I should be able to simplify this!" (or preferably someone else should simplify it for me)

milk + cereal = food
coffee = water + caffeine + black
milk = water + white

See how water for example is repeated several times. And those colors. I cant even see colors in the morning! So what i need is a cereal that contains my daily vitamins, my required 300mg caffeine. Even better if it contained dried milk also, so i could just add cold water!

morning_diet = food + vitamins + (3 * coffee)

Im so pissed off at this box being an aprils fool. Goddamn, it's been months, they could at least removed the link!
                                              Spazztroids - Caffeinated Breakfast Cereal