Stefano
Published © MIT

Send Encrypted Data via Kryptor (HSM/FPGA) and Raspberry Pi

Encrypt your data communication (WiFi, GPRS, SMS) connecting an HSM/FPGA to your RPi. Send sensor data fully end2end encrypted via 2G modem

IntermediateFull instructions provided2 hours2,485
Send Encrypted Data via Kryptor (HSM/FPGA) and Raspberry Pi

Things used in this project

Hardware components

Raspberry Pi 3 Model B
Raspberry Pi 3 Model B
×1
SparkFun Atmospheric Sensor Breakout - BME280
SparkFun Atmospheric Sensor Breakout - BME280
×1
Breadboard (generic)
Breadboard (generic)
×1
Skudo Kryptor HSM/FPGA
×1
SIMCom Wireless Solutions sim800c
×1
SIM data card
×1

Story

Read more

Schematics

Schematics

Schematics, open with Adobe Reader

Code

Code snippet #1

Plain text
pi@raspberrypi3:~/mystuff/sim800 $ dmesg | grep tty
[    0.000000] Kernel command line: coherent_pool=1M 8250.nr_uarts=1 bcm2708_fb.fbwidth=640 bcm2708_fb.fbheight=480 bcm2708_fb.fbswap=1 smsc95xx.macaddr=B8:27:EB:6C:FC:0D vc_mem.mem_base=0x3ec00000 vc_mem.mem_size=0x40000000  dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait fbcon=map:10 fbcon=font:ProFont6x11 logo.nologo
[    0.000911] console [tty1] enabled
[    0.974349] 3f201000.serial: ttyAMA0 at MMIO 0x3f201000 (irq = 81, base_baud = 0) is a PL011 rev2
pi@raspberrypi3:~/mystuff/sim800 $

Code snippet #2

Plain text
pi@raspberrypi3:~/mystuff/sim800 $ dmesg | grep tty
[    0.000000] Kernel command line: coherent_pool=1M 8250.nr_uarts=1 bcm2708_fb.fbwidth=640 bcm2708_fb.fbheight=480 bcm2708_fb.fbswap=1 smsc95xx.macaddr=B8:27:EB:6C:FC:0D vc_mem.mem_base=0x3ec00000 vc_mem.mem_size=0x40000000  dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait fbcon=map:10 fbcon=font:ProFont6x11 logo.nologo
[    0.000911] console [tty1] enabled
[    0.974349] 3f201000.serial: ttyAMA0 at MMIO 0x3f201000 (irq = 81, base_baud = 0) is a PL011 rev2
pi@raspberrypi3:~/mystuff/sim800 $

Code snippet #5

Plain text
AT+CGMM
SIMCOM_SIM800C

OK
AT+CGMR
Revision:1418B02SIM800C32_BT

OK

Code snippet #6

Plain text
AT+CGMM
SIMCOM_SIM800C

OK
AT+CGMR
Revision:1418B02SIM800C32_BT

OK

Code snippet #9

Plain text
import serial, time

with serial.Serial('/dev/ttyAMA0', 9600, timeout=1) as ser:

        ser.write(b"AT\r\n")
        line = ser.readlines()
        print (line)
        cmd="AT+CSQ\r"
        ser.write(cmd.encode())
        time.sleep(0.7)
        line2 = ser.readlines()
        print (line2)

        ser.close()

Code snippet #10

Plain text
import serial, time

with serial.Serial('/dev/ttyAMA0', 9600, timeout=1) as ser:

        ser.write(b"AT\r\n")
        line = ser.readlines()
        print (line)
        cmd="AT+CSQ\r"
        ser.write(cmd.encode())
        time.sleep(0.7)
        line2 = ser.readlines()
        print (line2)

        ser.close()

Code snippet #13

Plain text
# "em" is the apn for EMnify, tested by www.skudo.tech
connect "/usr/sbin/chat -v -f /etc/chatscripts/gprs -T em"

# Add the proper communication port:
/dev/ttyAMA0

# Baudrate
9600

# Assumes that your IP address is allocated dynamically by the ISP.
noipdefault
 
# Try to get the name server addresses from the ISP.
usepeerdns

# Use this connection as the default route to the internet.
defaultroute

# Makes PPPD "dial again" when the connection is lost.
persist

# Do not ask the remote to authenticate. This depends on your SIM provider
noauth

# No hardware flow control on the serial link with GSM Modem
nocrtscts

# No modem control lines with GSM Modem
local

Code snippet #14

Plain text
# "em" is the apn for EMnify, tested by www.skudo.tech
connect "/usr/sbin/chat -v -f /etc/chatscripts/gprs -T em"

# Add the proper communication port:
/dev/ttyAMA0

# Baudrate
9600

# Assumes that your IP address is allocated dynamically by the ISP.
noipdefault
 
# Try to get the name server addresses from the ISP.
usepeerdns

# Use this connection as the default route to the internet.
defaultroute

# Makes PPPD "dial again" when the connection is lost.
persist

# Do not ask the remote to authenticate. This depends on your SIM provider
noauth

# No hardware flow control on the serial link with GSM Modem
nocrtscts

# No modem control lines with GSM Modem
local

Code snippet #17

Plain text
# You can use this script unmodified to connect to cellular networks.
# The APN is specified in the peers file as the argument of the -T command
# line option of chat(8).

# For details about the AT commands involved please consult the relevant
# standard: 3GPP TS 27.007 - AT command set for User Equipment (UE).
# (http://www.3gpp.org/ftp/Specs/html-info/27007.htm)

ABORT           BUSY
ABORT           VOICE
ABORT           "NO CARRIER"
ABORT           "NO DIALTONE"
ABORT           "NO DIAL TONE"
ABORT           "NO ANSWER"
ABORT           "DELAYED"
ABORT           "ERROR"

# cease if the modem is not attached to the network yet
ABORT           "+CGATT: 0"

""              AT
TIMEOUT         12
OK              ATH
OK              ATE1

# +CPIN provides the SIM card PIN
#OK             "AT+CPIN=1234"

# +CFUN may allow to configure the handset to limit operations to
# GPRS/EDGE/UMTS/etc to save power, but the arguments are not standard
# except for 1 which means "full functionality".
#OK             AT+CFUN=1

OK              AT+CGDCONT=1,"IP","em","",0,0
OK              ATD*99#
TIMEOUT         22
CONNECT         ""

Code snippet #18

Plain text
# You can use this script unmodified to connect to cellular networks.
# The APN is specified in the peers file as the argument of the -T command
# line option of chat(8).

# For details about the AT commands involved please consult the relevant
# standard: 3GPP TS 27.007 - AT command set for User Equipment (UE).
# (http://www.3gpp.org/ftp/Specs/html-info/27007.htm)

ABORT           BUSY
ABORT           VOICE
ABORT           "NO CARRIER"
ABORT           "NO DIALTONE"
ABORT           "NO DIAL TONE"
ABORT           "NO ANSWER"
ABORT           "DELAYED"
ABORT           "ERROR"

# cease if the modem is not attached to the network yet
ABORT           "+CGATT: 0"

""              AT
TIMEOUT         12
OK              ATH
OK              ATE1

# +CPIN provides the SIM card PIN
#OK             "AT+CPIN=1234"

# +CFUN may allow to configure the handset to limit operations to
# GPRS/EDGE/UMTS/etc to save power, but the arguments are not standard
# except for 1 which means "full functionality".
#OK             AT+CFUN=1

OK              AT+CGDCONT=1,"IP","em","",0,0
OK              ATD*99#
TIMEOUT         22
CONNECT         ""

Code snippet #19

Plain text
pi@raspberrypi3:~/mystuff/sim800 $ cat /var/log/syslog | grep pppd
Jun 12 15:48:20 raspberrypi3 pppd[1182]: pppd 2.4.7 started by root, uid 0
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Serial connection established.
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Using interface ppp0
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Connect: ppp0 <--> /dev/ttyAMA0
Jun 12 15:48:22 raspberrypi3 pppd[1182]: PAP authentication succeeded
Jun 12 15:48:23 raspberrypi3 pppd[1182]: Could not determine remote IP address: defaulting to 10.64.64.64
Jun 12 15:48:23 raspberrypi3 pppd[1182]: not replacing default route to wlan0 [192.168.0.1]
Jun 12 15:48:23 raspberrypi3 pppd[1182]: local  IP address 100.101.160.2
Jun 12 15:48:23 raspberrypi3 pppd[1182]: remote IP address 10.64.64.64
Jun 12 15:48:23 raspberrypi3 pppd[1182]: primary   DNS address 8.8.8.8
Jun 12 15:48:23 raspberrypi3 pppd[1182]: secondary DNS address 8.8.4.4
pi@raspberrypi3:~/mystuff/sim800 $

Code snippet #20

Plain text
pi@raspberrypi3:~/mystuff/sim800 $ cat /var/log/syslog | grep pppd
Jun 12 15:48:20 raspberrypi3 pppd[1182]: pppd 2.4.7 started by root, uid 0
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Serial connection established.
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Using interface ppp0
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Connect: ppp0 <--> /dev/ttyAMA0
Jun 12 15:48:22 raspberrypi3 pppd[1182]: PAP authentication succeeded
Jun 12 15:48:23 raspberrypi3 pppd[1182]: Could not determine remote IP address: defaulting to 10.64.64.64
Jun 12 15:48:23 raspberrypi3 pppd[1182]: not replacing default route to wlan0 [192.168.0.1]
Jun 12 15:48:23 raspberrypi3 pppd[1182]: local  IP address 100.101.160.2
Jun 12 15:48:23 raspberrypi3 pppd[1182]: remote IP address 10.64.64.64
Jun 12 15:48:23 raspberrypi3 pppd[1182]: primary   DNS address 8.8.8.8
Jun 12 15:48:23 raspberrypi3 pppd[1182]: secondary DNS address 8.8.4.4
pi@raspberrypi3:~/mystuff/sim800 $

Code snippet #21

Plain text
pi@raspberrypi3:~/mystuff/sim800 $ ifconfig
eth0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether b8:27:eb:6c:fc:0d  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

ppp0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>  mtu 1500
        inet 100.101.160.2  netmask 255.255.255.255  destination 10.64.64.64
        ppp  txqueuelen 3  (Point-to-Point Protocol)
        RX packets 6  bytes 72 (72.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 7  bytes 111 (111.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.136  netmask 255.255.255.0  broadcast 192.168.0.255
        inet6 fe80::a069:f26f:c89c:a11b  prefixlen 64  scopeid 0x20<link>
        ether b8:27:eb:39:a9:58  txqueuelen 1000  (Ethernet)
        RX packets 14969  bytes 2048259 (1.9 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 5635  bytes 869635 (849.2 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

pi@raspberrypi3:~/mystuff/sim800 $

Code snippet #22

Plain text
pi@raspberrypi3:~/mystuff/sim800 $ ifconfig
eth0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether b8:27:eb:6c:fc:0d  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

ppp0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>  mtu 1500
        inet 100.101.160.2  netmask 255.255.255.255  destination 10.64.64.64
        ppp  txqueuelen 3  (Point-to-Point Protocol)
        RX packets 6  bytes 72 (72.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 7  bytes 111 (111.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.136  netmask 255.255.255.0  broadcast 192.168.0.255
        inet6 fe80::a069:f26f:c89c:a11b  prefixlen 64  scopeid 0x20<link>
        ether b8:27:eb:39:a9:58  txqueuelen 1000  (Ethernet)
        RX packets 14969  bytes 2048259 (1.9 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 5635  bytes 869635 (849.2 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

pi@raspberrypi3:~/mystuff/sim800 $

Code snippet #23

Plain text
pi@raspberrypi3:~/mystuff/sim800 $ sudo poff skudo
pi@raspberrypi3:~/mystuff/sim800 $ cat /var/log/syslog | grep pppd
Jun 12 15:48:20 raspberrypi3 pppd[1182]: pppd 2.4.7 started by root, uid 0
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Serial connection established.
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Using interface ppp0
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Connect: ppp0 <--> /dev/ttyAMA0
Jun 12 15:48:22 raspberrypi3 pppd[1182]: PAP authentication succeeded
Jun 12 15:48:23 raspberrypi3 pppd[1182]: Could not determine remote IP address: defaulting to 10.64.64.64
Jun 12 15:48:23 raspberrypi3 pppd[1182]: not replacing default route to wlan0 [192.168.0.1]
Jun 12 15:48:23 raspberrypi3 pppd[1182]: local  IP address 100.101.160.2
Jun 12 15:48:23 raspberrypi3 pppd[1182]: remote IP address 10.64.64.64
Jun 12 15:48:23 raspberrypi3 pppd[1182]: primary   DNS address 8.8.8.8
Jun 12 15:48:23 raspberrypi3 pppd[1182]: secondary DNS address 8.8.4.4
Jun 12 15:49:28 raspberrypi3 pppd[1182]: Terminating on signal 15
Jun 12 15:49:28 raspberrypi3 pppd[1182]: Connect time 1.1 minutes.
Jun 12 15:49:28 raspberrypi3 pppd[1182]: Sent 0 bytes, received 0 bytes.
Jun 12 15:49:28 raspberrypi3 pppd[1182]: Connection terminated.
Jun 12 15:49:28 raspberrypi3 pppd[1182]: Exit.
pi@raspberrypi3:~/mystuff/sim800 $

Code snippet #24

Plain text
pi@raspberrypi3:~/mystuff/sim800 $ sudo poff skudo
pi@raspberrypi3:~/mystuff/sim800 $ cat /var/log/syslog | grep pppd
Jun 12 15:48:20 raspberrypi3 pppd[1182]: pppd 2.4.7 started by root, uid 0
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Serial connection established.
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Using interface ppp0
Jun 12 15:48:20 raspberrypi3 pppd[1182]: Connect: ppp0 <--> /dev/ttyAMA0
Jun 12 15:48:22 raspberrypi3 pppd[1182]: PAP authentication succeeded
Jun 12 15:48:23 raspberrypi3 pppd[1182]: Could not determine remote IP address: defaulting to 10.64.64.64
Jun 12 15:48:23 raspberrypi3 pppd[1182]: not replacing default route to wlan0 [192.168.0.1]
Jun 12 15:48:23 raspberrypi3 pppd[1182]: local  IP address 100.101.160.2
Jun 12 15:48:23 raspberrypi3 pppd[1182]: remote IP address 10.64.64.64
Jun 12 15:48:23 raspberrypi3 pppd[1182]: primary   DNS address 8.8.8.8
Jun 12 15:48:23 raspberrypi3 pppd[1182]: secondary DNS address 8.8.4.4
Jun 12 15:49:28 raspberrypi3 pppd[1182]: Terminating on signal 15
Jun 12 15:49:28 raspberrypi3 pppd[1182]: Connect time 1.1 minutes.
Jun 12 15:49:28 raspberrypi3 pppd[1182]: Sent 0 bytes, received 0 bytes.
Jun 12 15:49:28 raspberrypi3 pppd[1182]: Connection terminated.
Jun 12 15:49:28 raspberrypi3 pppd[1182]: Exit.
pi@raspberrypi3:~/mystuff/sim800 $

Code snippet #25

Plain text
    cmd='AT+CMGF=1\r'
    ser.write(cmd.encode())
    time.sleep(1)
    cmd1='AT+CMGS='
    cmd2='"+46728315621"\r'
    cmd=cmd1+cmd2
    ser.write(cmd.encode())
    time.sleep(1)
    msg = "This is a test"
    ser.write (msg.encode())
    ser.write (chr(26).encode())
    time.sleep(4)
    line2 = ser.readlines()
    print (line2)

Code snippet #26

Plain text
    cmd='AT+CMGF=1\r'
    ser.write(cmd.encode())
    time.sleep(1)
    cmd1='AT+CMGS='
    cmd2='"+46728315621"\r'
    cmd=cmd1+cmd2
    ser.write(cmd.encode())
    time.sleep(1)
    msg = "This is a test"
    ser.write (msg.encode())
    ser.write (chr(26).encode())
    time.sleep(4)
    line2 = ser.readlines()
    print (line2)

Code snippet #27

Plain text
pi@raspberrypi3:~/mystuff/Kryptor $ ./hsm_cli -m
Version: b3430101
Procotol version mismatch.
This hsm_cli is using protocol 1.3, while device is reporting 1.1
Please use matching hsm_cli version, or update the device firmware.

Code snippet #28

Plain text
pi@raspberrypi3:~/mystuff/Kryptor $ ./hsm_cli -m
Version: b3430101
Procotol version mismatch.
This hsm_cli is using protocol 1.3, while device is reporting 1.1
Please use matching hsm_cli version, or update the device firmware.

Code snippet #29

Plain text
pi@raspberrypi3:~/mystuff/Kryptor $ ./hsm_cli -m
Vendor: Skudo OÜ (www.skudo.tech)
Product: HSM/FPGA
Serial: 57JP-DO6H-OKDG-HUT9
pi@raspberrypi3:~/mystuff/Kryptor $

Code snippet #30

Plain text
pi@raspberrypi3:~/mystuff/Kryptor $ ./hsm_cli -m
Vendor: Skudo OÜ (www.skudo.tech)
Product: HSM/FPGA
Serial: 57JP-DO6H-OKDG-HUT9
pi@raspberrypi3:~/mystuff/Kryptor $

Code snippet #33

Plain text
pi@raspberrypi3:~/mystuff/Kryptor $ nano clear.txt
pi@raspberrypi3:~/mystuff/Kryptor $ more clear.txt
This is a test
pi@raspberrypi3:~/mystuff/Kryptor $./hsm_cli -e clear.txt w 1 -o encrypted
pi@raspberrypi3:~/mystuff/Kryptor $ xxd encrypted
00000000: 0f00 0000 d28b 73ee 4775 a15e bb72 8dd6  ......s.Gu.^.r..
00000010: 0238 7b5f                                .8{_
pi@raspberrypi3:~/mystuff/Kryptor $

Code snippet #34

Plain text
pi@raspberrypi3:~/mystuff/Kryptor $ nano clear.txt
pi@raspberrypi3:~/mystuff/Kryptor $ more clear.txt
This is a test
pi@raspberrypi3:~/mystuff/Kryptor $./hsm_cli -e clear.txt w 1 -o encrypted
pi@raspberrypi3:~/mystuff/Kryptor $ xxd encrypted
00000000: 0f00 0000 d28b 73ee 4775 a15e bb72 8dd6  ......s.Gu.^.r..
00000010: 0238 7b5f                                .8{_
pi@raspberrypi3:~/mystuff/Kryptor $

Code snippet #35

Plain text
import serial, time, base64

with    open('encrypted', 'rb') as binary_file:
        binary_file_data = binary_file.read()
        base64_encoded_data = base64.b64encode(binary_file_data)
        base64_message = base64_encoded_data.decode('utf-8')

        print(base64_message)


with serial.Serial('/dev/ttyAMA0', 9600, timeout=1) as ser:

        ser.write(b"AT\r\n")
        line = ser.readlines()
        print (line)

        cmd='AT+CMGF=1\r'
        ser.write(cmd.encode())
        time.sleep(1)
        cmd1='AT+CMGS='
        cmd2='"+number"\r'    <---- here you should put the phone number
        cmd=cmd1+cmd2
        ser.write(cmd.encode())
        time.sleep(1)
        msg = base64_message
        ser.write (msg.encode())
        ser.write (chr(26).encode())
        time.sleep(4)
        line2 = ser.readlines()
        print (line2)
        line2 = ser.readlines()
        print (line2)
        ser.close()

Code snippet #36

Plain text
import serial, time, base64

with    open('encrypted', 'rb') as binary_file:
        binary_file_data = binary_file.read()
        base64_encoded_data = base64.b64encode(binary_file_data)
        base64_message = base64_encoded_data.decode('utf-8')

        print(base64_message)


with serial.Serial('/dev/ttyAMA0', 9600, timeout=1) as ser:

        ser.write(b"AT\r\n")
        line = ser.readlines()
        print (line)

        cmd='AT+CMGF=1\r'
        ser.write(cmd.encode())
        time.sleep(1)
        cmd1='AT+CMGS='
        cmd2='"+number"\r'    <---- here you should put the phone number
        cmd=cmd1+cmd2
        ser.write(cmd.encode())
        time.sleep(1)
        msg = base64_message
        ser.write (msg.encode())
        ser.write (chr(26).encode())
        time.sleep(4)
        line2 = ser.readlines()
        print (line2)
        line2 = ser.readlines()
        print (line2)
        ser.close()

Code snippet #37

Plain text
#!/usr/bin/env python

import socket
import sys
import json
import struct
import bme280

# temperature,pressure,humidity = bme280.readBME280All()

# check the request command, return the response body
def process_request(request):
    if request["command"] == "sensor_bme":
        return {
            "Temp (C)": temperature,
            "Press (hPa)": pressure,
            "Humid (%)": humidity
        }
    if request["command"] == "sensor2":
        return {
            "height": 128,
            "speed": 62
        }

# serialize and send the response
def respond(connection, sensor):
    response = json.dumps(sensor)
    connection.send(struct.pack("<i", len(response))) # header with the string l
ength
    connection.sendall(response)


# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port, listening all interfaces
server_address = ('192.168.0.159', 10001)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)

# Listen for incoming connections
sock.listen(1)


while True:
    # Wait for a connection
    print >>sys.stderr, 'waiting for a connection'
    connection, client_address = sock.accept()

    try:
        # read data from sensor
        temperature,pressure,humidity = bme280.readBME280All()
        print >>sys.stderr, 'connection from', client_address
        # receive the request length as a header
        length = struct.unpack('<i',connection.recv(4))[0]
        # accumulate the string with json-encoded request
        blob = ''
        while len(blob) < length:
            chunk = connection.recv(1024)
            if chunk:
                blob = blob + chunk
            else:
                break

        if len(blob) >= length:
            # deserialize the json into python request, process the request
            response = process_request(json.loads(blob))
            # return the response
            respond(connection, response)
        else:
            print "Incomplete request received"

    finally:
        # Clean up the connection
        connection.close()

Code snippet #38

Plain text
#!/usr/bin/env python

import socket
import sys
import json
import struct
import bme280

# temperature,pressure,humidity = bme280.readBME280All()

# check the request command, return the response body
def process_request(request):
    if request["command"] == "sensor_bme":
        return {
            "Temp (C)": temperature,
            "Press (hPa)": pressure,
            "Humid (%)": humidity
        }
    if request["command"] == "sensor2":
        return {
            "height": 128,
            "speed": 62
        }

# serialize and send the response
def respond(connection, sensor):
    response = json.dumps(sensor)
    connection.send(struct.pack("<i", len(response))) # header with the string l
ength
    connection.sendall(response)


# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port, listening all interfaces
server_address = ('192.168.0.159', 10001)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)

# Listen for incoming connections
sock.listen(1)


while True:
    # Wait for a connection
    print >>sys.stderr, 'waiting for a connection'
    connection, client_address = sock.accept()

    try:
        # read data from sensor
        temperature,pressure,humidity = bme280.readBME280All()
        print >>sys.stderr, 'connection from', client_address
        # receive the request length as a header
        length = struct.unpack('<i',connection.recv(4))[0]
        # accumulate the string with json-encoded request
        blob = ''
        while len(blob) < length:
            chunk = connection.recv(1024)
            if chunk:
                blob = blob + chunk
            else:
                break

        if len(blob) >= length:
            # deserialize the json into python request, process the request
            response = process_request(json.loads(blob))
            # return the response
            respond(connection, response)
        else:
            print "Incomplete request received"

    finally:
        # Clean up the connection
        connection.close()

Code snippet #39

Plain text
#!/usr/bin/env python

import socket
import sys
import json
import struct

def send_request(sock, command):
    data = { "command": command }
    request = json.dumps(data)
    sock.send(struct.pack('<i', len(request)), 4)
    sock.sendall(request)

def read_response(sock):
    length = struct.unpack('<i', sock.recv(4))[0]
    blob = ''

    while len(blob)<length:
        chunk = sock.recv(1024)
        if chunk:
            blob = blob+chunk
        else:
            break

    if len(blob)>=length:
        return blob
    else:
        return ''

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('192.168.0.159', 10001)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)

try:
    # Send request
    send_request(sock, "sensor1")
    response = read_response(sock)

    print(response)

finally:
    print >>sys.stderr, 'closing socket'
    sock.close()

Code snippet #40

Plain text
#!/usr/bin/env python

import socket
import sys
import json
import struct

def send_request(sock, command):
    data = { "command": command }
    request = json.dumps(data)
    sock.send(struct.pack('<i', len(request)), 4)
    sock.sendall(request)

def read_response(sock):
    length = struct.unpack('<i', sock.recv(4))[0]
    blob = ''

    while len(blob)<length:
        chunk = sock.recv(1024)
        if chunk:
            blob = blob+chunk
        else:
            break

    if len(blob)>=length:
        return blob
    else:
        return ''

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('192.168.0.159', 10001)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)

try:
    # Send request
    send_request(sock, "sensor1")
    response = read_response(sock)

    print(response)

finally:
    print >>sys.stderr, 'closing socket'
    sock.close()

Code snippet #45

Plain text
pi@raspberrypi3:~/mystuff $ python read_sensor.py
connecting to x.y.z.w port 10001
{"Press (hPa)": 1014.3060555865618, "Humid (%)": 41.53793272038257, "Temp (C)": 25.97}
closing socket
pi@raspberrypi3:~/mystuff $

Code snippet #46

Plain text
pi@raspberrypi3:~/mystuff $ python read_sensor.py
connecting to x.y.z.w port 10001
{"Press (hPa)": 1014.3060555865618, "Humid (%)": 41.53793272038257, "Temp (C)": 25.97}
closing socket
pi@raspberrypi3:~/mystuff $

Credits

Stefano

Stefano

1 project • 1 follower
Technology visionary with extensive international experiences. Simply put we built an "HSM on a chip" entirely done in Verilog using an FPGA

Comments