Difference between revisions of "Code Snippets"

From piMyHome Project
Jump to navigation Jump to search
 
(24 intermediate revisions by the same user not shown)
Line 1: Line 1:
== Sending messages to a Bticino Gateway with netcat ==
+
If you wanna get a feeling of how you can interact with a Bticino gateway, you should try our code snippets below.
The Linux command <tt>'''[http://en.wikipedia.org/wiki/Netcat netcat]'''</tt> makes it very easy to send messages from a Raspberry Pi to a Bticino Gateway. The syntax is:
+
 
 +
= Linux console =
 +
The Linux command <tt>'''[http://en.wikipedia.org/wiki/Netcat netcat]'''</tt> makes it very easy to send messages from a Raspberry Pi to a Bticino Gateway.  
 +
 
 +
=== Sending messages to a Bticino Gateway with netcat ===
 +
Syntax:
 
<source lang="bash">echo "<message>" | netcat <gateway-IP> <gateway-port></source >
 
<source lang="bash">echo "<message>" | netcat <gateway-IP> <gateway-port></source >
  
Line 6: Line 11:
 
<source lang="bash">echo "*1*0*94#4#05##" | netcat 192.168.1.55 20000</source >
 
<source lang="bash">echo "*1*0*94#4#05##" | netcat 192.168.1.55 20000</source >
  
If your command gets executed, you should get a response like that: <tt>'''*#*1##'''</tt> (ACK).
+
If your command gets executed, you should get <tt>'''*#*1##'''</tt> (ACK) as a response.
If not you will get a <tt>'''*#*0##'''</tt> (NACK).
+
If the command fails for some reason, you will get a <tt>'''*#*0##'''</tt> (NACK).
 +
 
 +
 
 +
 
 +
= Python =
 +
Python is a very powerful scripting language and available for all major operation systems like Linux, Windows and Apple OSX. In MAC OSX and Linux environments, Python is usually pre-installed. If not already installed on your system, please follow these steps:
 +
{| class="wikitable"
 +
! style="text-align:left;"| OS
 +
! style="text-align:left;"| How to install python
 +
|-
 +
|Raspberry Pi, Debian, Ubuntu
 +
|<tt>sudo apt-get install python</tt>
 +
|-
 +
|Windows
 +
|Download and install Python from [http://legacy.python.org/download/ python.org]
 +
|-
 +
|Apple MAC OSX
 +
|Download and install Python from [http://legacy.python.org/download/ python.org]
 +
|}
 +
 
  
 
== Sending messages to a Bticino Gateway with Python ==
 
== Sending messages to a Bticino Gateway with Python ==
 +
Below is a very simple Python script to send messages to a Bticino gateway. The script sends each command line argument as a single message to the gateway.
 +
Syntax:
 +
<pre>./btsend.py <OWN-message> <OWN-message> <OWN-message></pre>
 +
For example, turn off light 15 and turn on light 17:
 +
<pre>./btsend.py *1*0*15## *1*1*17##</pre>
 
=== The Python Script btsend.py ===
 
=== The Python Script btsend.py ===
Copy the content of this script to btsend.py
 
 
<source lang="python">
 
<source lang="python">
 
#!/usr/bin/python
 
#!/usr/bin/python
Line 18: Line 46:
 
import sys
 
import sys
  
gateway_host = "192.168.60.201"     # set here the IP of your gateway
+
gateway_host = "192.168.1.35"       # set here the IP of your gateway
 
gateway_port = 20000                # set here the port of your gateway
 
gateway_port = 20000                # set here the port of your gateway
 
   
 
   
Line 28: Line 56:
 
     sock.send(msg)
 
     sock.send(msg)
  
for arg in sys.argv[1:]:
+
for arg in sys.argv[1:]:           # cut off first argument (btsend.py)
     send_message(arg)
+
     send_message(arg)               # send all arguments as message
 
     print "Sending " + arg
 
     print "Sending " + arg
 
</source>
 
</source>
  
 
== A Python Monitor Session with Bticino Gateway ==
 
== A Python Monitor Session with Bticino Gateway ==
To understand the OWN messages better, you should start a monitor session and watch the OWN messages flying in from your home automation system. Analyzing these messages gives you an idea how it works. Below is a simple monitor script in Python.  
+
To understand the OWN messages better, you should start a monitor session and watch the OWN messages flying in from your home automation system. Analyzing these messages gives you an idea how it works. Below is a simple monitor script in Python. [http://www.pimyhome.org/files/monitor.py Download monitor.py]
 
+
=== The Python Script btmonitor.py ===
==== For Raspberry Pi ====
 
 
 
Start editor an editor (in our example nano) and create monitor.py
 
<source lang="bash">sudo nano monitor.py</source>
 
 
 
Copy and paste the script below into that file and save it.
 
After you saved the file, you have to make the file executable:
 
<source lang="bash">sudo chmod 755 monitor.py</source>
 
 
 
Now start the monitor and watch the messages fly by. Exit with CTRL-C.
 
<source lang="bash">sudo ./monitor.py</source>
 
 
 
==== For Windows ====
 
Download and install [https://www.python.org/downloads/windows/ Python for Windows] and create the file <tt>monitor.py</tt> and edit with an text editor. Copy and paste the source code below in that file and save it. Then just double click <tt>monitor.py</tt>.
 
 
 
=== The Python Script monitor.py ===
 
Copy the content of this script to monitor.py
 
 
<source lang="python">
 
<source lang="python">
 
#!/usr/bin/python
 
#!/usr/bin/python
 
# -*- coding: utf-8 -*-
 
# -*- coding: utf-8 -*-
 
import socket
 
import socket
 +
import sys
 
   
 
   
gateway_host = "192.168.60.201"     # set here the IP of your gateway
+
gateway_host = "192.168.1.35"       # set here the IP of your gateway
 
gateway_port = 20000                # set here the port of your gateway
 
gateway_port = 20000                # set here the port of your gateway
 
   
 
   
Line 84: Line 96:
 
             msg = data[0:eom+2]    # message is from position 0 until end of ##
 
             msg = data[0:eom+2]    # message is from position 0 until end of ##
 
             data = data[eom+2:]    # next message starts after ##
 
             data = data[eom+2:]    # next message starts after ##
             print msg
+
             print (msg)
     finally:
+
     except:
 
         sock.close()
 
         sock.close()
 +
        print ("\nSocket connection closed.")
 +
        sys.exit()
 
   
 
   
 
monitor()                          # start the monitor
 
monitor()                          # start the monitor
 
</source>
 
</source>
 +
 +
=== The Python Script btmonitor.py for Python 3 ===
 +
In Python 3, socket returns bytes objects and we have to take this into account
 +
<source lang="python">
 +
#!/usr/bin/env python3
 +
# -*- coding: utf-8 -*-
 +
import socket
 +
 +
gateway_host = '192.168.1.35'      # set here the IP of your gateway
 +
gateway_port = 20000                  # set here the port of your gateway
 +
 +
def monitor():
 +
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 +
    try:
 +
        sock.connect((gateway_host, gateway_port))
 +
        data = sock.recv(1024).decode()  # decoding byt to string
 +
        if data != '*#*1##':        # expect ACK from gateway
 +
            raise Exception('Did not receive expected ACK, but: '+data)
 +
        sock.send(b'*99*1##')        # Switch session to MONITOR mode
 +
        data = ''
 +
        while 1:
 +
            next = sock.recv(1024).decode()  # now read data from MyHome BUS
 +
            if next == '':
 +
                break              # EOF
 +
            data = data + next
 +
            eom = data.find('##')
 +
            if eom < 0:
 +
                continue;          # Not a complete message, need more
 +
            if data[0] != '*':
 +
                raise Exception('Message does not start with '*': '+data)
 +
            msg = data[0:eom+2]    # message is from position 0 until end of ##
 +
            data = data[eom+2:]    # next message starts after ##
 +
            print (msg)
 +
    except:
 +
        sock.close()
 +
        print ('\nSocket connection closed.')
 +
        exit()
 +
 +
monitor()                          # start the monitor</source>

Latest revision as of 08:48, 15 March 2019

If you wanna get a feeling of how you can interact with a Bticino gateway, you should try our code snippets below.

Linux console

The Linux command netcat makes it very easy to send messages from a Raspberry Pi to a Bticino Gateway.

Sending messages to a Bticino Gateway with netcat

Syntax:

echo "<message>" | netcat <gateway-IP> <gateway-port>

For example: turn off light 94 (9.4) on interface 5:

echo "*1*0*94#4#05##" | netcat 192.168.1.55 20000

If your command gets executed, you should get *#*1## (ACK) as a response. If the command fails for some reason, you will get a *#*0## (NACK).


Python

Python is a very powerful scripting language and available for all major operation systems like Linux, Windows and Apple OSX. In MAC OSX and Linux environments, Python is usually pre-installed. If not already installed on your system, please follow these steps:

OS How to install python
Raspberry Pi, Debian, Ubuntu sudo apt-get install python
Windows Download and install Python from python.org
Apple MAC OSX Download and install Python from python.org


Sending messages to a Bticino Gateway with Python

Below is a very simple Python script to send messages to a Bticino gateway. The script sends each command line argument as a single message to the gateway. Syntax:

./btsend.py <OWN-message> <OWN-message> <OWN-message>

For example, turn off light 15 and turn on light 17:

./btsend.py *1*0*15## *1*1*17##

The Python Script btsend.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import sys

gateway_host = "192.168.1.35"       # set here the IP of your gateway
gateway_port = 20000                # set here the port of your gateway
 
gateway_addr_port = gateway_host, gateway_port

def send_message(msg):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(gateway_addr_port)
    sock.send(msg)

for arg in sys.argv[1:]:            # cut off first argument (btsend.py)
    send_message(arg)               # send all arguments as message
    print "Sending " + arg

A Python Monitor Session with Bticino Gateway

To understand the OWN messages better, you should start a monitor session and watch the OWN messages flying in from your home automation system. Analyzing these messages gives you an idea how it works. Below is a simple monitor script in Python. Download monitor.py

The Python Script btmonitor.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import sys
 
gateway_host = "192.168.1.35"       # set here the IP of your gateway
gateway_port = 20000                # set here the port of your gateway
 
gateway_addr_port = gateway_host, gateway_port
 
def monitor():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect(gateway_addr_port)
        data = sock.recv(1024)
        if data != "*#*1##":        # expect ACK from gateway
            raise Exception("Did not receive expected ACK, but: "+data)
        sock.send("*99*1##")        # Switch session to MONITOR mode
        data = ""
        while 1:
            next = sock.recv(1024)  # now read data from MyHome BUS
            if next == "":
                break               # EOF
            data = data + next
            eom = data.find("##")
            if eom < 0:
                continue;           # Not a complete message, need more
            if data[0] != "*":
                raise Exception("Message does not start with '*': "+data)
            msg = data[0:eom+2]     # message is from position 0 until end of ##
            data = data[eom+2:]     # next message starts after ##
            print (msg)
    except:
        sock.close()
        print ("\nSocket connection closed.")
        sys.exit()
 
monitor()                           # start the monitor

The Python Script btmonitor.py for Python 3

In Python 3, socket returns bytes objects and we have to take this into account

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
 
gateway_host = '192.168.1.35'       # set here the IP of your gateway
gateway_port = 20000                  # set here the port of your gateway
 
def monitor():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((gateway_host, gateway_port))
        data = sock.recv(1024).decode()  # decoding byt to string
        if data != '*#*1##':         # expect ACK from gateway
            raise Exception('Did not receive expected ACK, but: '+data)
        sock.send(b'*99*1##')        # Switch session to MONITOR mode
        data = ''
        while 1:
            next = sock.recv(1024).decode()  # now read data from MyHome BUS
            if next == '':
                break               # EOF
            data = data + next
            eom = data.find('##')
            if eom < 0:
                continue;           # Not a complete message, need more
            if data[0] != '*':
                raise Exception('Message does not start with '*': '+data)
            msg = data[0:eom+2]     # message is from position 0 until end of ##
            data = data[eom+2:]     # next message starts after ##
            print (msg)
    except:
        sock.close()
        print ('\nSocket connection closed.')
        exit()
 
monitor()                           # start the monitor