HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Getting funky with Pi

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withfunkygetting

Problem

Push a button and an LED lights up1 and sends a signal to another computer that plays a song.

First project on the Raspberry pi, really simple but definitely fun and educational to implement. Also, second time using python and sockets so I'd especially appreciate input on anything I do inefficiently.2

  • Mostly feedback to ensure that the program is running/button is active.



  • I know it's straightforward, but this site has shown me that even the simplest things leave room to be executed much more elegantly.



SongServer.java:

```
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.awt.Desktop;

public class SongServer {
final static int PORT = 9001;

public static void main(String[] args) {
try(ServerSocket server = new ServerSocket(PORT)) {
System.out.println(new Date() + "\nServer online.");

while(true) {
new Thread(new ClientHandler(server.accept())).start();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

private static class ClientHandler implements Runnable {
private Socket socket;
private BufferedReader in;
private PrintWriter out;

ClientHandler(Socket socket) {
this.socket = socket;
System.out.println("Client connected!");
}

@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

out.println("Connection success");
while (true) {
String input = in.readLine();
if (input == null || input.trim().isEmpty()) {
continue;
}

Solution

Looks good as a proof of concept. I recommend to modularize python code, that is

-
Make socket interface into a function

-
Make GPIO interface into a function

-
Have a

if __name__ == '__main__'


clause to call them (directly or via a main) function.

I would also handle failures to connect (retry maybe?); a total fun is to implement service discovery via pybonjour or zeroconf.

Code Snippets

if __name__ == '__main__'

Context

StackExchange Code Review Q#107343, answer score: 3

Revisions (0)

No revisions yet.