Suchen

Registrieren

Vielen Dank für Deine Anmeldung! Du bekommst nun eine Email mit einem Aktivierungslink.

username already taken
Du hast bereits einen Account? .

Login

Passwort vergessen?
Du hast noch keinen Account? Registrieren um den UI-Designer und das Forum zu benutzen oder eigene Projekte anzulegen.
Log dich ein um Beiträge schreiben zu können!



new python server script

#1 März 3, 2013 11:39:33 by Mausbiber

new python server script

Hello

UPDATE 04.03.2013 - see End of Thread

so, as i told you i have a new script for use of NetIO.
It's the same script like this in the RasPi-Section, only without the class for hardware buttons.
You can use it to controll nearly everything on a server with NetIO.
Many thanks to the germany python forum und espacially to User “Sirius3”. He did most of the work

At this moment there is no error handling … feel free to help me out with that!

The script can:

- works as a real server, so the script don't close if you shut down the app
- you can do system calls
- make use of eventHandling, so faster respond of events
- in this example you can control switched socket-outlet

Here it is
import asyncore
import socket
import select
import subprocess
import os
class Client(asyncore.dispatcher_with_send):
    def __init__(self, socket=None, pollster=None):
        asyncore.dispatcher_with_send.__init__(self, socket)
        self.data = ''
        if pollster:
            self.pollster = pollster
            pollster.register(self, select.EPOLLIN)
    def handle_close(self):
        if self.pollster:
            self.pollster.unregister(self)
    def handle_read(self):
        receivedData = self.recv(8192)
        if not receivedData:
            self.close()
            return
        receivedData = self.data + receivedData
        while '\n' in receivedData:
            line, receivedData = receivedData.split('\n',1)
            self.handle_command(line)
        self.data = receivedData
    def handle_command(self, line):
        if line == 'Switch1 on':
            self.send('on')
            os.system("/root/switch 1 1")
        elif line == 'Switch1 off':
            self.send('off')
            os.system("/root/switch 1 0")
        elif line == 'Switch2':
            self.send('restart')
            os.system("xbmc-send --host=localhost --port=9777 --action=RestartApp")
        elif line == 'Switch3':
            self.send('off')
            ausgabe='xbmc-send --host=localhost --port=9777 --action="PlayerControl(Stop)"'
            os.system(ausgabe)
        else:
            self.send('unknown command')
class Server(asyncore.dispatcher):
    def __init__(self, listen_to, pollster):
        asyncore.dispatcher.__init__(self)
        self.pollster = pollster
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(listen_to)
        self.listen(5)
    def handle_accept(self):
        newSocket, address = self.accept()
        print "Connected from", address
        Client(newSocket,self.pollster)
def readwrite(obj, flags):
    try:
        if flags & select.EPOLLIN:
            obj.handle_read_event()
        if flags & select.EPOLLOUT:
            obj.handle_write_event()
        if flags & select.EPOLLPRI:
            obj.handle_expt_event()
        if flags & (select.EPOLLHUP | select.EPOLLERR | select.POLLNVAL):
            obj.handle_close()
    except socket.error, e:
        if e.args[0] not in asyncore._DISCONNECTED:
            obj.handle_error()
        else:
            obj.handle_close()
    except asyncore._reraised_exceptions:
        raise
    except:
        obj.handle_error()
class EPoll(object):
    def __init__(self):
        self.epoll = select.epoll()
        self.fdmap = {}
    def register(self, obj, flags):
        fd = obj.fileno()
        self.epoll.register(fd, flags)
        self.fdmap[fd] = obj
    def unregister(self, obj):
        fd = obj.fileno()
        del self.fdmap[fd]
        self.epoll.unregister(fd)
    def poll(self):
        evt = self.epoll.poll()
        for fd, flags in evt:
            yield self.fdmap[fd], flags
if __name__ == "__main__":
    pollster = EPoll()
    pollster.register(Server(("",54321),pollster), select.EPOLLIN)
    while True:
        evt = pollster.poll()
        for obj, flags in evt:
            readwrite(obj, flags)

And now, next step to a complete daemon.
You can use the next script so start/stop the script with “/etc/init.d/NetworkManager start/stop” and to add the script it to the system autostart
Simply save the script under “/etc/init.d/NetworkManager” and do “chmod +x /etc/init.d/NetworkManager”
#!/bin/bash
DAEMON="/usr/bin/python"
ARGS="/root/NetworkServer.py"
PIDFILE=/root/NetworkServer.pid
case "$1" in
  start)
    echo "Starting server"
    /sbin/start-stop-daemon --start --pidfile $PIDFILE \
        --user root --group root \
        -b --make-pidfile \
        --chuid root \
        --exec $DAEMON $ARGS
    ;;
  stop)
    echo "Stopping server"
    /sbin/start-stop-daemon --stop --pidfile $PIDFILE --verbose
    ;;
  *)
    echo "Usage: /etc/init.d/carbage-serve {start|stop}"
    exit 1
    ;;
esac
exit 0

Editiert Mausbiber (März 4, 2013 19:15:07)

#2 März 3, 2013 16:25:13 by david.eickhoff

new python server script

Hi Mausbiber, thanks again - also in this forum

If you like you can add this as a project in the new project site.
Then it is easier for users to find it.

#3 März 3, 2013 17:02:29 by Mausbiber

new python server script

Dann warte noch 2-3 Wochen, derzeit binde ich ein:
- Raspberry Pi schalten über GPIO-Pins
- HomeEasy USB-Funkmodul zur Ansteuerung von Funksteckdosen und Schaltern
- GEMBIRD SiS-PM USB-Steckdosenleiste
- xbmc Mediacenter
- (falls du mal einen Samsung SmartTV bekommst und ne Lösung findet auch den)

Das alles soll dann über Scripts auf dem Server und auf 2-3 RasPis laufen

#4 März 4, 2013 19:13:29 by Mausbiber

new python server script

UPDATE 04.03.2013

#5 März 13, 2013 23:47:12 by bhodgs01

new python server script

what file folder does the NetworkServer file need to be to run?

#6 März 14, 2013 10:07:28 by Mausbiber

new python server script

What do you mean with file folder?

#7 Aug. 25, 2013 12:02:37 by christoph21279

new python server script

Hi Mausbieber,

I use this script for my home control. It is based on i2c-bus with an Conrad C-Control. I have connected the Raspberry via RS232.

The script is working well, but after a few connections by Android-Phone I get an error-message:

Traceback (most recent call last):
File “NetworkServer.py”, line 238, in <module>
readwrite(obj, flags)
File “NetworkServer.py”, line 201, in readwrite
obj.handle_close()
File “NetworkServer.py”, line 87, in handle_close
self.pollster.unregister(self)
File “NetworkServer.py”, line 215, in unregister
fd = obj.fileno()
File “/usr/lib/python2.7/socket.py”, line 224, in meth
return getattr(self._sock,name)(*args)
File “/usr/lib/python2.7/socket.py”, line 170, in _dummy
raise error(EBADF, ‘Bad file descriptor’)
socket.error: Bad file descriptor

After this I have to restart the script.

What could this be?

Thank you very much,

Christoph

#8 Aug. 25, 2013 16:00:50 by david.eickhoff

new python server script

I think you try to close the connection which is already closes due to a connection issue.. check the ‘except’ statements.. probably remove the obj.handle_close() line for testing..

The error shows you in which line the error occured.

#9 Nov. 28, 2013 23:56:16 by aby1

new python server script

hi, any chance to explain this code a bit, im very new to programming pi and i'd love to know how it works, thanks!

#10 Dez. 4, 2013 08:42:22 by Koggel

new python server script

Hi @all,

thank you for the great script! That's what I was looking for :-) Now i change a little bit the code and the startup script, but can not get the status auf the plexconnect daemon. Maybe someone has an idea

Here the Phytonscript:

#!/usr/bin/python 
import asyncore
import socket
import select
import subprocess
import os
def restart():
  command = "/usr/bin/sudo /sbin/shutdown -r now"
  import subprocess
  process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
  output = process.communicate()[0]
  print output
def shutdown():
  command = "/usr/bin/sudo /sbin/shutdown -h now"
  import subprocess
  process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
  output = process.communicate()[0]
  print output
plexprocessname = 'PlexConnect'
def plexdaemonrunning():
  activeprocesses = os.popen("ps -Af").read()
  proccount = activeprocesses.count(plexprocessname)
  if proccount > 7:
    print proccount, ' processes running of ', plexprocessname, 'type'
    return True
  else:
    print plexprocessname, ' not found'
    return False
class Client(asyncore.dispatcher_with_send):
    def __init__(self, socket=None, pollster=None):
        asyncore.dispatcher_with_send.__init__(self, socket)
        self.data = ''
        if pollster:
            self.pollster = pollster
            pollster.register(self, select.EPOLLIN)
    def handle_close(self):
        if self.pollster:
            self.pollster.unregister(self)
    def handle_read(self):
        receivedData = self.recv(8192)
        if not receivedData:
            self.close()
            return
        receivedData = self.data + receivedData
        while '\n' in receivedData:
            line, receivedData = receivedData.split('\n',1)
            self.handle_command(line)
        self.data = receivedData
    def handle_command(self, line):
        if line == 'PlexConnectStatus':
            daemonrunning = plexdaemonrunning()
            if daemonrunning:
                self.send('run')
            else:
                self.send('stop')
            print 'PlexConnect running: ', daemonrunning
        elif line == 'PlexConnectStart':
            self.send('Starting...')
            print 'Starting Plexconnect'
        elif line == 'PlexConnectStop':
            self.send('Stopping')  
            print 'Plexconnect Stop'
        elif line == 'RaspberryReboot':
            self.send('rebooting...')  
            print 'System is going to reboot'
            restart()
        elif line == 'RaspberryShutdown':
            self.send('shutdown...')  
            print 'System is going to shutdown'
            shutdown()
        else:
            self.send('unknown command')
class Server(asyncore.dispatcher):
    def __init__(self, listen_to, pollster):
        asyncore.dispatcher.__init__(self)
        self.pollster = pollster
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(listen_to)
        self.listen(5)
    def handle_accept(self):
        newSocket, address = self.accept()
        print "Connected from", address
        Client(newSocket,self.pollster)
def readwrite(obj, flags):
    try:
        if flags & select.EPOLLIN:
            obj.handle_read_event()
        if flags & select.EPOLLOUT:
            obj.handle_write_event()
        if flags & select.EPOLLPRI:
            obj.handle_expt_event()
        if flags & (select.EPOLLHUP | select.EPOLLERR | select.POLLNVAL):
            obj.handle_close()
    except socket.error, e:
        if e.args[0] not in asyncore._DISCONNECTED:
            obj.handle_error()
        else:
            obj.handle_close()
    except asyncore._reraised_exceptions:
        raise
    except:
        obj.handle_error()
class EPoll(object):
    def __init__(self):
        self.epoll = select.epoll()
        self.fdmap = {}
    def register(self, obj, flags):
        fd = obj.fileno()
        self.epoll.register(fd, flags)
        self.fdmap[fd] = obj
    def unregister(self, obj):
        fd = obj.fileno()

And the startup script

#!/bin/bash
### BEGIN INIT INFO
# Provides:          netioserver
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: This is the NetIo Server daemon
# Description:       This script starts NetIo Server
### END INIT INFO
NAME=NetioServer
INSTDIR="/usr/local/lib/Netio_server"
DAEMON="$INSTDIR/MyNetioServer.py"
DAEMON_OPTS="2>&1 >/dev/null"
DAEMON_USER="root"
PIDFILE=/var/run/MyNetioServer.pid
case "$1" in
  start)
    echo "Starting server"
    /sbin/start-stop-daemon --start --pidfile $PIDFILE \
        --user root --group root \
        -b --make-pidfile \
        --chuid root \
        --exec $DAEMON
    ;;
  stop)
    echo "Stopping server"
    /sbin/start-stop-daemon --stop --pidfile $PIDFILE --verbose
    ;;
  *)
    echo "Usage: /etc/init.d/netioserver {start|stop}"
    exit 1
    ;;
esac
exit 0

Most works fine, i can do shutdown and reboot the raspberry pi. Also the status of the plexconnect daemon is committed, but not after startup. A short restart is necessary to fix it.

Thanks to all for there great work!

Koggel