Python socket message receiver - Nova

I was curious if anyone was using the Custom cloud to send messages directly to their own script running on flask/django/whatever to receive the socket connection using one of the Nova (or any) modems. Was thinking about creating one but I have never messed with sockets. Currently using the message router.

Made one here if anyone is interested. Made for fun at the moment, but gives me more freedom in the future if I don’t want to use the message router. It will accept multiple socket connections!

Instead of using the HologramCloud, you will need to use the CustomCloud like this on your pi or whatever you are using:

credentials = None
send_host = "example.com"
send_port = 6333
receive_host = "0.0.0.0"
receive_port = 4010
hologram=CustomCloud(credentials,send_host,send_port,receive_host,receive_port,network='cellular')

Then the rest of your script on that device stays the same.

Then host this script wherever you want :slight_smile:

import socket
from threading import Thread
import threading
import requests

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 6333            # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(100)

def clientthread(conn, addr):
    while True:
        data = conn.recv(1024)
        if not data: break
        if data == b'\r\n': continue
        print(addr,"Said:",data.decode())
        #reply to the hologram or the sdk will get mad
        message = "200".encode()
        conn.send(message)
        # DO SOMETHING WITH YOUR DATA ... Like send it to a web server
        response = requests.post('https://example.com/', data=data)
        print(str(response.status_code), "Response from Web Server")

while True:
    conn, addr = s.accept()
    list_of_clients.append(conn)
    print (addr, " connected")
    t=Thread(target=clientthread, args=(conn, addr))
    t.start()
    print("Active Threads: ", threading.active_count())

conn.close()
s.close()

This is quick and dirty. Made mostly from combining a few tutorials and scripts I found around the web, and has absolutely no error checking.