Home of the Squeezebox™ & Transporter® network music players.
Page 3 of 6 FirstFirst 12345 ... LastLast
Results 21 to 30 of 57
  1. #21
    Quote Originally Posted by epoch1970 View Post
    Wha??

    Have you tried "gpio raspberry pi python" on google ?

    On google! I searched on the forum, on RPi forum i open un post and i have a python script for manage GPIO but is only with MPD not LMS. I try change this script for LMS

    http://www.raspberrypi.org/phpBB3/vi...eda87&start=25

    If MPD playing music, GPIO is opens, if in pause/stop GPIO closes.


    Quote Originally Posted by script
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    from mpd import MPDClient
    import RPi.GPIO as GPIO
    import time

    RELAIS_ACTIF=False
    PIN_RELAIS=12

    def relai(etat):
    GPIO.output(PIN_RELAIS, etat) # Bascule le pin du relai à l'état voulu
    RELAIS_ACTIF=etat

    def main():
    # Test de lecture audio
    client = MPDClient()
    while(1):
    try:
    # Connection au client mpd et lecture du status
    client.connect(host='localhost', port='6600')
    client.password('password')
    status=client.status()

    if status['state']=='play' and RELAIS_ACTIF is False:
    relai(True)
    elif status['state']=='stop' or status['state']=='pause':
    relai(False)
    client.disconnect()
    except:
    print 'Erreur connection'
    raise
    time.sleep(1) # On fait dodo pendant une seconde, et on recommence !

    if __name__ == "__main__":
    GPIO.setup(PIN_RELAIS, GPIO.OUT) # paramétrage du pin en sortie
    relai(False)
    main()

  2. #22
    Senior Member
    Join Date
    Apr 2008
    Location
    Paris, France
    Posts
    2,254
    2 SB 3 • 1 PCP 6 • Libratone Loop, Zipp, Zipp Mini • iPeng (iPhone + iPad) • LMS 7.9 (linux) with plugins: CD Player, WaveInput, Triode's BBC iPlayer by bpa • IRBlaster by Gwendesign (Felix) • Smart Mix, Music Walk With Me, What Was That Tune? by Michael Herger • PowerSave by Jason Holtzapple • Song Info, Song Lyrics by Erland Isaksson • AirPlay Bridge by philippe_44 • WeatherTime by Martin Rehfeld • Auto Dim Display, SaverSwitcher, ContextMenu by Peter Watkins.

  3. #23
    Quote Originally Posted by epoch1970 View Post
    i see, but isn't for manage GPIO, is for have inforamtions over serveurs/player

    but thanks

  4. #24
    Junior Member
    Join Date
    Aug 2012
    Posts
    15
    Hello,

    Sorry for bumping this thread, but for people who are still searching for an easy script to trigger a relay i've created a python script that runs at boot.
    The script checks the powerstate of the player every second (script runs on a raspberry pi where squeezelite is installed), and if powerstate = 1 then relay is turned on, otherwise the relay is turned off.
    It works perfectly. The only thing you need to enter is the mac-adress of your player and the adress of your server (ip adress or url).

    For the start up process i let the script wait 5 minutes before it gets executed, because if the player and the server are on the same machine, and the machine is rebooted, it takes a while to start lms.

    If there are things that can be changed in order to make the script better (I'm sure that will be easy, this was my first python script) , feel free to do so and post your changes please! :-)

    Code:
    import sys
    import httplib
    import RPi.GPIO as GPIO
    import time
    
    time.sleep (300)
    
    if float(sys.version[:3]) >= 2.6:
        import json
    else:
        # python 2.4 or 2.5 can also import simplejson
        # as working alternative to the json included.
        import simplejson as json
    
    # change to your server
    
    server = "yourserverip"
    playermac = "your player mac adresse"
    
    # This provides http 1.1 keep alive so preventing DNS lookup 
    # For each request.
    
    while True: 
    
    	conn = httplib.HTTPConnection(server)
    
    	#Make a python dictionary for the request.
    
    	data = {
        	"id": 1, 
    	    "method": "slim.request", 
    	    "params": [
            	"", 
    	        [
            	    "player", 
    	            "count", 
            	    "?"
    	        ]
    	    ]
    	}
    
    	# So now we convert the dictionary data to a string
    	params = json.dumps(data, sort_keys=True, indent=4)
    	# Make the keep alive request
    	conn.request("POST", "/jsonrpc.js", params)
    	httpResponse = conn.getresponse()
    	#print "httpResponse.status=%s, httpResponse.reason=%s" % (httpResponse.status, httpResponse.reason)
    	data = httpResponse.read()
    	# Load the JSON string back to python dictionary
    	responce = json.loads(data)
    	# print the python dictionary as a JSON string.
    	# print json.dumps(responce, sort_keys=True, indent=4)
    	# Extract the number of players from the python dictionary
    	numberplayers = responce['result']["_count"]
    	# print "numberplayers=%s" % numberplayers
    
    	playerIdentifiers = []
    	playerdetected = ""
    	for i in range(numberplayers):
    	    data = { "id":1,
    	                "method":"slim.request",
    	                "params":[ "", 
    					["player","id",i,"?"]
    	                  ]
    	            }
    	    params = json.dumps(data, sort_keys=True, indent=4)
    	#    print params
    	    conn.request("POST", "/jsonrpc.js", params)
    	    httpResponse = conn.getresponse()
    	#   print "httpResponse.status=%s, httpResponse.reason=%s" % (httpResponse.status, httpResponse.reason)
    	    data = httpResponse.read()
    	#    print data
    	    responce = json.loads(data)
    	    playerId = responce['result']["_id"]
    	#    print playerId
    	#    print "id=%s" % playerId
    	#    print playermac
    	
    	    if (playerId == playermac):
    		playerdetected = playerId
    	
    	if playerdetected <> "":
    	#	print playerdetected
    		data = { "id":1,
    	                "method":"slim.request",
    	                "params":[playerdetected,
    					["power","?"]
    				]               
    			}
    		params = json.dumps(data, sort_keys=True, indent=4)
    	 #       print params
    	        conn.request("POST", "/jsonrpc.js", params)
    	        httpResponse = conn.getresponse()
    	 #       print "httpResponse.status=%s, httpResponse.reason=%s" % (httpResponse.status, httpResponse.reason)
    	        data = httpResponse.read()
    	 #       print data
    	        responce = json.loads(data)
    	        powerstate = responce['result']["_power"]
    		if powerstate ==  "1":
    #			print "player: " + playerdetected + " power state: " + powerstate
    			GPIO.setmode(GPIO.BCM)
    			GPIO.setwarnings(False)
    			GPIO.setup(18, GPIO.OUT)
    			GPIO.output(18, True)
    		else:
    			powerstate = "0"
    #			print "player: " + playerdetected + " power state: " + powerstate
    			GPIO.setmode(GPIO.BCM)
    			GPIO.setwarnings(False)
    			GPIO.setup(18, GPIO.OUT)
    			GPIO.output(18, False)
    	time.sleep (1)

  5. #25
    Thanks, i test now

  6. #26
    Junior Member
    Join Date
    Aug 2012
    Posts
    15
    Ok! :-) Let me know if it works or not..

  7. #27
    i tried but don't work

    i put the script in /hom/gpio.sh with chmod 777

    i put before yout script

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-

    i put ip of RPi : 192.168.1.9
    and mac adress of squeezeslave (in web interface, setting, player, ) : b8:27:eb:e4:2a:af

    I edit /etc/rc.local

    and put before exit0
    /home/gpio.sh &

    I plugged my relay
    vcc in pin 2 of RPi (5V)
    ground in pin 6 of RPi (ground)
    ctrl in pin 12 of RPi (gpio18)

    i reboot but don't work, what I did wrong?

    thanks

    EDIT I tested withe a tester and pin 12 (gpio18) out continuous 3.3V with LMS on or off
    Last edited by TheD6Bel; 2013-05-01 at 06:59.

  8. #28
    if i execute gpio.sh i have error:

    root@squeezeplug:/home# ./gpio.sh
    Traceback (most recent call last):
    File "./gpio.sh", line 52, in <module>
    responce = json.loads(data)
    File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
    File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    File "/usr/lib/python2.7/json/decoder.py", line 383, in raw_decode
    raise ValueError("No JSON object could be decoded")
    ValueError: No JSON object could be decoded

  9. #29
    Junior Member
    Join Date
    Aug 2012
    Posts
    15
    Hi, I'll tell you what I did to make it work:

    I saved the script as relay.py and ran it just with "python relay.py" (as root).
    Later I made a service script in etc\init.d to run it at boot..

    Maybe you should try to add :9000 behind the ip adress of your server? Maybe that can be the problem.

    My relay is connected as follows: VCC pin 2, GND pin 6, CTRL pin 12..

  10. #30
    i resolve my first problem

    i change

    #!/usr/bin/env python
    to
    #!/usr/bin/env python3

    but i have a error in line 82 :

    root@squeezeplug:/home# ./gpio.sh
    File "./gpio.sh", line 82
    playerdetected = playerId
    ^
    TabError: inconsistent use of tabs and spaces in indentation
    Last edited by TheD6Bel; 2013-05-02 at 11:48.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •