远程控制led灯python程序,树莓派学习笔记2: 用python实现C/S方式远程控制双色LED灯...

# -*- coding:utf-8 -*-

# Socket Server example in python 3.6

# 文件名:Socket_server_test.py

import socket

import sys

import RPi.GPIO as GPIO

import time

# ------------------------------------------------------------------

HOST = '' # Symbolic name meaning all available interfaces

PORT = 8888 # Arbitrary non-privileged port

timeout_limit=120 # unit-sec,建立连接后如果超过xx 秒,将断开连接

connect_times_limit=5 # unit-times,连接中断次数达到xx 次,将关闭socket和中止服务端程序。

#------------------------------------------------------------------

pins = {'pin_R':11, 'pin_G':12} # pins is a dict

sleep_time = 5

GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location

for i in pins:

GPIO.setup(pins[i], GPIO.OUT) # Set pins' mode is output

GPIO.output(pins[i], GPIO.LOW) # Set pins to low(0V) to off led

print("i is ",i,pins[i])

def Let_Led_on(pin):

print('The pin is',pin)

if pin=='pin_R' :

other_pin='pin_G'

elif pin=='pin_G' :

other_pin='pin_R'

else :

print('Input error.\r\n')

GPIO.output(pins[other_pin], GPIO.LOW) # Set pins to low(0V) to off led

GPIO.output(pins[pin], GPIO.HIGH) # Set pins to high(+3.3V) to on led

print(pins[pin]," Red Led is On...")

time.sleep(sleep_time)

# ---Let_led_on----------------------------------

def Let_Led_off():

GPIO.output(pins['pin_R'], GPIO.LOW) # Set pins to low(0V) to off led

time.sleep(1)

GPIO.output(pins['pin_G'], GPIO.LOW) # Set pins to low(0V) to off led

print(" Red and Green LEDs is off.")

# ---Let_led_off----------------------------------

#------------------------------------------------------------------

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print('1.Socket created')

try:

s.bind((HOST, PORT))

except socket.error as msg:

print('>> Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])

sys.exit()

print('2.Socket bind complete')

s.listen(10)

print('3.Socket now listening')

quit_count=0 # initial

while 1:

# wait to accept a connection - blocking call

conn, addr = s.accept()

quit_count = quit_count + 1

print('4.Connected with ' + addr[0] + ':' + str(addr[1]),',now is ',quit_count,' times connect')

welcome_str='Hello, Welcome to here..The input value must be :\r\n' \

+' r : red led on\r\n'\

+' g : green led on\r\n'\

+' o : Two leds off\r\n'\

+' q : quit the connection\r\n'

conn.sendall(welcome_str.encode())

try:

conn.settimeout(timeout_limit)

# 获得一个连接,然后开始循环处理这个连接发送的信息

while True:

try:

data = conn.recv(1024)

except IOError as rcv_msg:

print(">> Failed to recv() data.: %s: %s\n" % (rcv_msg.errno, rcv_msg.strerror))

break

buf = data.decode()

print( "<< Get value " + buf)

if buf == 'r':

print("<< Red LED is on")

conn.sendall('>> Red LED is on...\r\n'.encode())

'''

do something...

'''

Let_Led_on('pin_R')

elif buf == 'g':

print("<< Green LED is on")

conn.sendall('>> Green LED is on...\r\n'.encode())

'''

do something...

'''

Let_Led_on('pin_G')

elif buf =='o':

print("<< Two LEDs turn off.")

conn.sendall('>> Green and Red LED turn off!\r\n'.encode())

'''

do something...

'''

Let_Led_off()

elif buf =='q':

Let_Led_off()

print("<< The Connection Close")

conn.sendall('>> The Connection will Close in 3 sec, Rerun again.\r\n'.encode())

break

else:

print("<< Invalid command, try again!")

conn.sendall('>> Invalid command, pls try again!\r\n'.encode())

except socket.timeout: # 如果建立连接后,该连接在设定的时间内无数据发来,则time out

print('time out')

conn.close()

print("5.This Connection ",addr[0]," has disconnected.")

if quit_count ==connect_times_limit : # 如果q(quit),即断开连接次数达到一定次数后,将关闭socket.

break

print("6.Socket close,When quit times = ",quit_count)

s.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值