Code Snippets

From piMyHome Project
Jump to navigation Jump to search

Sending messages with netcat

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

pi@raspberry ~ $ echo "<message>" | netcat <gateway-IP> <gateway-port>

A Monitor Session with Python

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

start editor nano and create monitor.py

nano monitor.py

Copy and paste the script below into that file and save it. After you saved the file, you have to make the file executable:

chmod 755 monitor.py

Copy the content of this script to monitor.py

 1 #!/usr/bin/python
 2 # -*- coding: utf-8 -*-
 3 import socket
 4 
 5 # IP address and port to connect to the gateway, please 
 6 # change these values according to your environment
 7 default_gateway_host = "192.168.60.201"
 8 default_gateway_port = 20000
 9 
10 gateway_addr_port = default_gateway_host, default_gateway_port
11 
12 def monitor():
13     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
14     try:
15         sock.connect(gateway_addr_port)
16         data = sock.recv(1024)
17         # expect ACK from gateway
18         if data != "*#*1##":
19             raise Exception("Did not receive expected ACK, but: "+data)
20         # Switch session to MONITOR mode
21         sock.send("*99*1##")
22         data = ""
23         while 1:
24             # Read data from MyHome BUS
25             next = sock.recv(1024)
26             if next == "":
27                 break               # EOF
28             data = data + next
29             eom = data.find("##")
30             if eom < 0:
31                 continue;           # Not a complete message, need more
32             if data[0] != "*":
33                 raise Exception("Message does not start with '*': "+data)
34             print data
35             msg = data[1:eom]
36             data = data[eom+2:]
37     finally:
38         sock.close()
39 
40 monitor()

Now start the monitor and watch the messages fly by. Exit with CTRL-C.

./monitor.py