Difference between revisions of "Code Snippets"
Jump to navigation
Jump to search
Line 19: | Line 19: | ||
import socket | import socket | ||
− | # IP address and port to connect to the gateway, please | + | # IP address and port to connect to the gateway, please |
+ | # change these values according to your environment | ||
default_gateway_host = "192.168.60.201" | default_gateway_host = "192.168.60.201" | ||
default_gateway_port = 20000 | default_gateway_port = 20000 | ||
Line 37: | Line 38: | ||
data = "" | data = "" | ||
while 1: | while 1: | ||
− | # Read data from MyHome | + | # Read data from MyHome BUS |
next = sock.recv(1024) | next = sock.recv(1024) | ||
if next == "": | if next == "": | ||
Line 57: | Line 58: | ||
Now start the monitor and watch the messages fly by. Exit with CTRL-C. | Now start the monitor and watch the messages fly by. Exit with CTRL-C. | ||
− | < | + | <source lang="bash">./monitor.py</source> |
Revision as of 11:22, 16 November 2014
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:
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
# IP address and port to connect to the gateway, please
# change these values according to your environment
default_gateway_host = "192.168.60.201"
default_gateway_port = 20000
gateway_addr_port = default_gateway_host, default_gateway_port
def monitor():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(gateway_addr_port)
data = sock.recv(1024)
# expect ACK from gateway
if data != "*#*1##":
raise Exception("Did not receive expected ACK, but: "+data)
# Switch session to MONITOR mode
sock.send("*99*1##")
data = ""
while 1:
# Read data from MyHome BUS
next = sock.recv(1024)
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)
print data
msg = data[1:eom]
data = data[eom+2:]
finally:
sock.close()
monitor()
Now start the monitor and watch the messages fly by. Exit with CTRL-C.
./monitor.py