I have 3 files lcdtest.py, lcd.py and alarmfunctionr.py.
I am trying to control the attached lcd display on my raspberry pi with the lcdtest.py script.
!/usr/bin/env python
import paho.mqtt.client as paho
import globals
import time
from alarmfunctionsr import SendToLCD
from lcd import noDisplay
from lcd import message
globals.init()
SendToLCD(12, "test lcd" ,1) #Test
time.sleep(5)
lcd.message("test with message")
time.sleep(5)
noDisplay
The import from alarmfunctionsr seem to work ok but i get an cannot import name error when i try the same for the lcd script.
lcd.py:
#!/usr/bin/python
#
# based on code from lrvick and LiquidCrystal
# lrvic - https://github.com/lrvick/raspi-hd44780/blob/master/hd44780.py
# LiquidCrystal - https://github.com/arduino/Arduino/blob/master/libraries/LiquidCrystal/LiquidCrystal.cpp
#
from time import sleep
class CharLCD(object):
# commands
LCD_CLEARDISPLAY = 0x01
LCD_RETURNHOME = 0x02
LCD_ENTRYMODESET = 0x04
LCD_DISPLAYCONTROL = 0x08
LCD_CURSORSHIFT = 0x10
LCD_FUNCTIONSET = 0x20
LCD_SETCGRAMADDR = 0x40
LCD_SETDDRAMADDR = 0x80
# flags for display entry mode
LCD_ENTRYRIGHT = 0x00
LCD_ENTRYLEFT = 0x02
LCD_ENTRYSHIFTINCREMENT = 0x01
LCD_ENTRYSHIFTDECREMENT = 0x00
# flags for display on/off control
LCD_DISPLAYON = 0x04
LCD_DISPLAYOFF = 0x00
LCD_CURSORON = 0x02
LCD_CURSOROFF = 0x00
LCD_BLINKON = 0x01
LCD_BLINKOFF = 0x00
# flags for display/cursor shift
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00
# flags for display/cursor shift
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00
LCD_MOVERIGHT = 0x04
LCD_MOVELEFT = 0x00
# flags for function set
LCD_8BITMODE = 0x10
LCD_4BITMODE = 0x00
LCD_2LINE = 0x08
LCD_1LINE = 0x00
LCD_5x10DOTS = 0x04
LCD_5x8DOTS = 0x00
def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, 27, 22], GPIO=None):
# Emulate the old behavior of using RPi.GPIO if we haven't been given
# an explicit GPIO interface to use
if not GPIO:
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
self.GPIO = GPIO
self.pin_rs = pin_rs
self.pin_e = pin_e
self.pins_db = pins_db
self.GPIO.setmode(GPIO.BCM)
self.GPIO.setup(self.pin_e, GPIO.OUT)
self.GPIO.setup(self.pin_rs, GPIO.OUT)
for pin in self.pins_db:
self.GPIO.setup(pin, GPIO.OUT)
self.write4bits(0x33) # initialization
self.write4bits(0x32) # initialization
self.write4bits(0x28) # 2 line 5x7 matrix
self.write4bits(0x0C) # turn cursor off 0x0E to enable cursor
self.write4bits(0x06) # shift cursor right
self.displaycontrol = self.LCD_DISPLAYON | self.LCD_CURSOROFF | self.LCD_BLINKOFF
self.displayfunction = self.LCD_4BITMODE | self.LCD_1LINE | self.LCD_5x8DOTS
self.displayfunction |= self.LCD_2LINE
# Initialize to default text direction (for romance languages)
self.displaymode = self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENT
self.write4bits(self.LCD_ENTRYMODESET | self.displaymode) # set the entry mode
self.clear()
def begin(self, cols, lines):
if (lines > 1):
self.numlines = lines
self.displayfunction |= self.LCD_2LINE
def home(self):
self.write4bits(self.LCD_RETURNHOME) # set cursor position to zero
self.delayMicroseconds(3000) # this command takes a long time!
def clear(self):
self.write4bits(self.LCD_CLEARDISPLAY) # command to clear display
self.delayMicroseconds(3000) # 3000 microsecond sleep, clearing the display takes a long time
def setCursor(self, col, row):
self.row_offsets = [0x00, 0x40, 0x14, 0x54]
self.write4bits(self.LCD_SETDDRAMADDR | (col + self.row_offsets[row]))
def noDisplay(self):
""" Turn the display off (quickly) """
self.displaycontrol &= ~self.LCD_DISPLAYON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def display(self):
""" Turn the display on (quickly) """
self.displaycontrol |= self.LCD_DISPLAYON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def noCursor(self):
""" Turns the underline cursor off """
self.displaycontrol &= ~self.LCD_CURSORON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def cursor(self):
""" Turns the underline cursor on """
self.displaycontrol |= self.LCD_CURSORON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def noBlink(self):
""" Turn the blinking cursor off """
self.displaycontrol &= ~self.LCD_BLINKON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def blink(self):
""" Turn the blinking cursor on """
self.displaycontrol |= self.LCD_BLINKON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def DisplayLeft(self):
""" These commands scroll the display without changing the RAM """
self.write4bits(self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVELEFT)
def scrollDisplayRight(self):
""" These commands scroll the display without changing the RAM """
self.write4bits(self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVERIGHT)
def leftToRight(self):
""" This is for text that flows Left to Right """
self.displaymode |= self.LCD_ENTRYLEFT
self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)
def rightToLeft(self):
""" This is for text that flows Right to Left """
self.displaymode &= ~self.LCD_ENTRYLEFT
self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)
def autoscroll(self):
""" This will 'right justify' text from the cursor """
self.displaymode |= self.LCD_ENTRYSHIFTINCREMENT
self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)
def noAutoscroll(self):
""" This will 'left justify' text from the cursor """
self.displaymode &= ~self.LCD_ENTRYSHIFTINCREMENT
self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)
def write4bits(self, bits, char_mode=False):
""" Send command to LCD """
self.delayMicroseconds(1000) # 1000 microsecond sleep
bits = bin(bits)[2:].zfill(8)
self.GPIO.output(self.pin_rs, char_mode)
for pin in self.pins_db:
self.GPIO.output(pin, False)
for i in range(4):
if bits[i] == "1":
self.GPIO.output(self.pins_db[::-1][i], True)
self.pulseEnable()
for pin in self.pins_db:
self.GPIO.output(pin, False)
for i in range(4, 8):
if bits[i] == "1":
self.GPIO.output(self.pins_db[::-1][i-4], True)
self.pulseEnable()
def delayMicroseconds(self, microseconds):
seconds = microseconds / float(1000000) # divide microseconds by 1 million for seconds
sleep(seconds)
def pulseEnable(self):
self.GPIO.output(self.pin_e, False)
self.delayMicroseconds(1) # 1 microsecond pause - enable pulse must be > 450ns
self.GPIO.output(self.pin_e, True)
self.delayMicroseconds(1) # 1 microsecond pause - enable pulse must be > 450ns
self.GPIO.output(self.pin_e, False)
self.delayMicroseconds(1) # commands need > 37us to settle
def message(self, text):
""" Send string to LCD. Newline wraps to second line"""
for char in text:
if char == '\n':
self.write4bits(0xC0) # next line
else:
self.write4bits(ord(char), True)
def DisplayLCD(msg):
lcd = CharLCD()
lcd.clear()
x=msg.find("**")
if x>0:
line1=msg[0:x]
line2=msg[x+2:len(msg)]
else:
line1=msg
line2=""
lcd.message(line1+"\n"+line2)
alarmfunctionsr.py:
#!/usr/bin/env python
"""
import globals
import urllib2
import smtplib
import serial
import time
import sys
import thread
import RPi.GPIO as GPIO
import os, glob, time, operator
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from time import sleep
def find_all(a_str, sub):
start = 0
cnt=0
while True:
start = a_str.find(sub, start)
if start == -1:
return cnt
start += len(sub)
cnt=cnt+1
def isNumber(x):
# Test whether the contents of a string is a number
try:
val = int(x)
except ValueError:
return False
return True
def get_latest_photo(files):
lt = operator.lt
if not files:
return None
now = time.time()
latest = files[0], now - os.path.getctime(files[0])
for f in files[1:]:
age = now - os.path.getctime(f)
if lt(age, latest[1]):
latest = f, age
return latest[0]
def UpdateHostThread(function,opcode):
try:
thread.start_new_thread(UpdateHostThread, (function,opcode, ) )
except:
print "Error: unable to start thread"
def UpdateHost(function,opcode):
# Sends data to the server
script_path = "https://www.privateeyepi.com/alarmhostr.php?u="+globals.user+"&p="+globals.password+"&function="+str(function)
i=0
for x in opcode:
script_path=script_path+"&opcode"+str(i)+"="+str(opcode[i])
i=i+1
if globals.PrintToScreen: print "Host Update: "+script_path
try:
rt=urllib2.urlopen(script_path)
except urllib2.HTTPError:
if globals.PrintToScreen: print "HTTP Error"
return False
time.sleep(.2)
temp=rt.read()
if globals.PrintToScreen: print temp
l = find_all(temp,"/n");
RecordSet = temp.split(',')
c=[]
y=0
c.append([])
for x in RecordSet:
if x=="/n":
y=y+1
if y < l:
c.append([])
else:
if isNumber(x):
c[y].append(int(x))
else:
c[y].append(x)
rt=ProcessActions(c)
if rt==False:
return(False)
else:
return(c)
def ProcessActions(ActionList):
FalseInd=True
for x in ActionList:
if x[0]=="/EMAIL":
SendEmailAlertFromRule(x[1], x[2],0)
x.remove
if x[0]=="/SEMAIL":
SendEmailAlert(x[1])
x.remove
if x[0]=="/CHIME":
StartChimeThread()
x.remove
if x[0]=="/rn588":
exit()
if x[0]=="/FALSE":
FalseInd=False
if x[0]=="/SIREN":
StartSirenThread(x[2])
x.remove
if x[0]=="/PHOTO":
SendEmailAlertFromRule(x[1], x[2],1)
x.remove
if x[0]=="/RELAYON":
SwitchRelay(1)
x.remove
if x[0]=="/RELAYOFF":
SwitchRelay(0)
x.remove
if x[0]=="/WRELAYON":
SwitchRFRelay(1)
x.remove
if x[0]=="/WRELAYOFF":
SwitchRFRelay(0)
x.remove
return(FalseInd)
def StartSirenThread(Zone):
try:
thread.start_new_thread(Siren, (Zone, ) )
except:
print "Error: unable to start thread"
def SwitchRelay(onoff):
GPIO.setmode(GPIO.BOARD)
GPIO.setup(globals.RelayPin, GPIO.OUT)
GPIO.output(globals.RelayPin,onoff)
def SwitchRFRelay(onoff):
# declare to variables, holding the com port we wish to talk to and the speed
port = '/dev/ttyAMA0'
baud = 9600
# open a serial connection using the variables above
ser = serial.Serial(port=port, baudrate=baud)
# wait for a moment before doing anything else
sleep(0.2)
for i in range(0,3):
if (onoff==True):
ser.write('a{}RELAYAON-'.format(globals.WRelayPin))
else:
ser.write('a{}RELAYAOFF'.format(globals.WRelayPin))
time.sleep(2)
ser.close
def SendToLCD(GPIOnumber, Location, status):
import paho.mqtt.client as paho
if status==0:
ActionStr="_"
topic="alarm_activity"
else:
if status==1:
ActionStr="_"
topic="alarm_activity"
else:
topic="temperature"
if status==2:
ActionStr=str(GPIOnumber)+","+Location
else:
ActionStr="Undefined"
#client = mosquitto.Mosquitto('privateeyepi')
client = paho.Client()
client.connect(globals.lcd_ip)
if status <= 1:
if globals.PrintToScreen:
print str(Location)+"**"+str(ActionStr)
client.publish(topic, str(Location)+"**"+str(ActionStr))
else:
if globals.PrintToScreen:
print str(ActionStr)
client.publish(topic, ActionStr)
client.disconnect()
def Siren(Zone):
GPIO.setmode(GPIO.BOARD)
if globals.UseSiren == True:
GPIO.setup(globals.SirenGPIOPin, GPIO.OUT) #Siren pin setup
else:
return
if globals.SirenDelay>0:
globals.SirenStartTime = time.time()
while time.time() < globals.SirenStartTime + globals.SirenDelay:
if globals.BeepDuringDelay:
GPIO.output(globals.SirenGPIOPin,True)
time.sleep(1)
GPIO.output(globals.SirenGPIOPin,False)
time.sleep(4)
GPIO.output(globals.SirenGPIOPin,True)
globals.SirenStartTime = time.time()
if globals.PrintToScreen: print "Siren Activated"
while time.time() < globals.SirenStartTime + globals.SirenTimeout:
time.sleep(5)
if CheckForSirenDeactivation(Zone) == True:
break
GPIO.output(globals.SirenGPIOPin,False)
if globals.PrintToScreen: print "Siren Deactivated"
def CheckForSirenDeactivation(Zone):
# Routine to fetch the location and zone descriptions from the server
RecordSet = GetDataFromHost(16,[Zone])
if globals.PrintToScreen: print RecordSet
ZoneStatus=RecordSet[0][0]
if ZoneStatus=="FALSE":
return (True)
def StartChimeThread():
try:
thread.start_new_thread(SoundChime, ())
except:
print "Error: unable to start thread"
def SoundChime():
if globals.ChimeDuration>0:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(globals.ChimeGPIOPin, GPIO.OUT) #Siren pin setup
GPIO.output(globals.ChimeGPIOPin,True)
time.sleep(globals.ChimeDuration)
GPIO.output(globals.ChimeGPIOPin,False)
def GetDataFromHost(function,opcode):
# Request data and receive reply (request/reply) from the server
script_path = "https://www.privateeyepi.com/alarmhostr.php?u="+globals.user+"&p="+globals.password+"&function="+str(function)
i=0
for x in opcode:
script_path=script_path+"&opcode"+str(i)+"="+str(opcode[i])
i=i+1
if globals.PrintToScreen: print script_path
try:
rt = urllib2.urlopen(script_path)
except urllib2.HTTPError:
return False
temp=rt.read()
if globals.PrintToScreen: print temp
l = find_all(temp,"/n");
RecordSet = temp.split(',')
c=[]
y=0
c.append([])
for x in RecordSet:
if x=="/n":
y=y+1
if y < l:
c.append([])
else:
if isNumber(x):
c[y].append(int(x))
else:
c[y].append(x)
rt=ProcessActions(c)
if rt==False:
return(False)
else:
return(c)
return(c)
def BuildMessage(SensorNumber):
# Routine to fetch the location and zone descriptions from the server
RecordSet = GetDataFromHost(6,[SensorNumber])
if globals.PrintToScreen: print RecordSet
if RecordSet==False:
return
zonedesc=RecordSet[0][0]
locationdesc = RecordSet[0][1]
messagestr="This is an automated email from your house alarm system. Alarm activated for Zone: "+zonedesc+" ("+locationdesc+")"
return messagestr
def BuildMessageFromRule(SensorNumber, smartruleid):
RecordSet = GetDataFromHost(7,[smartruleid, SensorNumber])
if RecordSet==False:
return
numrows = len(RecordSet)
messagestr="This is an automated email from PrivateEyePi. Rule triggered for Zone(s): "+RecordSet[0][3]+", Location: "+RecordSet[0][4]+" and for rule "
for i in range(0,numrows,1):
if RecordSet[i][0]==1:
messagestr=messagestr+"Alarm Activated"
if RecordSet[i][0]==2:
messagestr=messagestr+"Alarm Deactivated"
if RecordSet[i][0]==3:
messagestr=messagestr+"Circuit Open"
if RecordSet[i][0]==4:
messagestr=messagestr+"Circuit Closed"
if RecordSet[i][0]==5:
messagestr=messagestr+"Open for " + str(RecordSet[i][1]) + " Minutes"
if RecordSet[i][0]==6:
messagestr=messagestr+"Closed for " + str(RecordSet[i][1]) + " Minutes"
if RecordSet[i][0]==7:
messagestr=messagestr+"Where sensor value (" + str(RecordSet[i][5]) + ") is between " + str(RecordSet[i][1]) + " " + str(RecordSet[i][2])
if RecordSet[i][0]==8:
messagestr=messagestr+"Tamper"
if RecordSet[i][0]==9:
messagestr=messagestr+"Day Of Week is between " + str(RecordSet[i][1]) + " and " + str(RecordSet[i][2])
if RecordSet[i][0]==10:
messagestr=messagestr+"Hour Of Day is between " + str(RecordSet[i][1]) + " and " + str(RecordSet[i][2])
if RecordSet[i][0]==11:
messagestr=messagestr+"Where secondary sensor value (" + str(RecordSet[i][6]) + ") is between " + str(RecordSet[i][1]) + " " + str(RecordSet[i][2])
if i<numrows-1:
messagestr=messagestr + " AND "
return messagestr
def SendEmailAlertFromRule(ruleid, SensorNumber, photo):
try:
thread.start_new_thread(SendEmailAlertThread, (SensorNumber, ruleid, True, photo, ) )
except:
print "Error: unable to start thread"
def SendEmailAlert(SensorNumber):
try:
thread.start_new_thread(SendEmailAlertThread, (SensorNumber,0 , False, False) )
except:
print "Error: unable to start thread"
def SendEmailAlertThread(SensorNumber, smartruleid, ruleind, photo):
# Get the email addresses that you configured on the server
RecordSet = GetDataFromHost(5,[0])
if RecordSet==False:
return
numrows = len(RecordSet)
if globals.smtp_server=="":
return
if ruleind:
msgtext = BuildMessageFromRule(SensorNumber, smartruleid)
else:
msgtext = BuildMessage(SensorNumber)
for i in range(numrows):
# Define email addresses to use
addr_to = RecordSet[i][0]
addr_from = globals.smtp_user #Or change to another valid email recognized under your account by your ISP
# Construct email
if (photo==1):
files = 0
files = glob.glob(globals.photopath)
latestphoto = get_latest_photo(files)
msg = MIMEMultipart()
else:
msg = MIMEText(msgtext)
msg['To'] = addr_to
msg['From'] = addr_from
msg['Subject'] = 'Alarm Notification' #Configure to whatever subject line you want
#attach photo
if (photo==1):
msg.preamble = 'Multipart message.\n'
part = MIMEText(msgtext)
msg.attach(part)
part = MIMEApplication(open(latestphoto,"rb").read())
part.add_header('Content-Disposition', 'attachment', filename=latestphoto)
msg.attach(part)
# Send the message via an SMTP server
#Option 1 - No Encryption
if globals.email_type==1:
s = smtplib.SMTP(globals.smtp_server)
elif globals.email_type==2:
#Option 2 - SSL
s = smtplib.SMTP_SSL(globals.smtp_server, 465)
elif globals.email_type==3:
#Option 3 - TLS
s = smtplib.SMTP(globals.smtp_server,587)
s.ehlo()
s.starttls()
s.ehlo()
else:
s = smtplib.SMTP(globals.smtp_server)
s.login(globals.smtp_user,globals.smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()
if globals.PrintToScreen: print msg;
def SendCustomEmail(msgText, msgSubject):
# Get the email addresses that you configured on the server
RecordSet = GetDataFromHost(5,[0])
if RecordSet==False:
return
numrows = len(RecordSet)
if globals.smtp_server=="":
return
for i in range(numrows):
# Define email addresses to use
addr_to = RecordSet[i][0]
addr_from = globals.smtp_user #Or change to another valid email recognized under your account by your ISP
# Construct email
msg = MIMEText(msgText)
msg['To'] = addr_to
msg['From'] = addr_from
msg['Subject'] = msgSubject #Configure to whatever subject line you want
# Send the message via an SMTP server
#Option 1 - No Encryption
if globals.email_type==1:
s = smtplib.SMTP(globals.smtp_server)
elif globals.email_type==2:
#Option 2 - SSL
s = smtplib.SMTP_SSL(globals.smtp_server, 465)
elif globals.email_type==3:
#Option 3 - TLS
s = smtplib.SMTP(globals.smtp_server,587)
s.ehlo()
s.starttls()
s.ehlo()
else:
s = smtplib.SMTP(globals.smtp_server)
s.login(globals.smtp_user,globals.smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()
if globals.PrintToScreen: print msg;
Your lcd.py module doesn't define any functions (or other top-level objects) named noDisplay or message, only a class named CharLCD and a function named DisplayLCD. So, when you try to import something that doesn't exist, of course you get an ImportError.
It's true that the CharLCD class has methods named noDisplay and message, but that doesn't mean you can just import them as top-level functions. (And, even if you could, you can't call them that way; you need a CharLCD object to call its methods.)
I suspect you need to read a basic tutorial on classes, like the Classes chapter in the official tutorial.
Meanwhile, I think the code you want is:
from lcd import CharLCD
# ...
char_lcd = CharLCD()
char_lcd.message("test with message")
time.sleep(5)
char_lcd.noDisplay()
(Also note the () in the last line. You need those parentheses to call a function or method; without them, you're just referring to the function or method itself, as a value, which has no more effect than just writing 2 on a line by itself.)
Related
I got an issue with this driver:
LM75_CHIP_ADDR = 0x48
LM75_I2C_SPEED = 100000
LM75_REGS = {
'TEMP' : 0x00,
'CONF' : 0x01,
'THYST' : 0x02,
'TOS' : 0x03,
'PRODID' : 0x07 # TI LM75A chips only?
}
LM75_REPORT_TIME = .8
# Temperature can be sampled at any time but the read aborts
# the current conversion. Conversion time is 300ms so make
# sure not to read too often.
LM75_MIN_REPORT_TIME = .5
class MLM75:
def __init__(self, config):
self.printer = config.get_printer()
self.name = config.get_name().split()[-1]
self.reactor = self.printer.get_reactor()
self.i2c_sen = bus.MCU_I2C_from_config(config, LM75_CHIP_ADDR,
LM75_I2C_SPEED)
self.mcu = self.i2c_sen.get_mcu()
self.report_time = config.getfloat('lm75_report_time',LM75_REPORT_TIME, minval=LM75_MIN_REPORT_TIME)
self.temp = self.min_temp = self.max_temp = 0.0
self.sample_timer = self.reactor.register_timer(self._sample_mlm75)
self.printer.add_object("mlm75 " + self.name, self)
self.printer.register_event_handler("klippy:connect",
self.handle_connect)
############# MUX HANDLER ############
self.gcode = self.printer.lookup_object('gcode')
self.mux = self.printer.load_object(config, "PCA9545A %s" % (self.name,))
self.mux.init_route = config.getint( "mux_ch", 0, minval=0, maxval=3 )
self.mux.address = config.getint( "mux_i2c_address", 112 )
self.mux.change_i2c_addr( self.mux.address )
# _mux_iic_addr = self.mux.get_info()[0]
# _mux_out_chan = self.mux.get_info()[1]
# self.gcode.respond_info('sensor: '+self.name+ '\n' +
# ' addr:'+str(_mux_iic_addr)+
# ' chan:'+str(_mux_out_chan))
self.mux_channel = 0
############# MUX HANDLER ############
def handle_connect(self):
self._init_mlm75()
self.reactor.update_timer(self.sample_timer, self.reactor.NOW)
def setup_minmax(self, min_temp, max_temp):
self.min_temp = min_temp
self.max_temp = max_temp
def setup_callback(self, cb):
self._callback = cb
def get_report_time_delta(self):
return self.report_time
def degrees_from_sample(self, x):
# The temp sample is encoded in the top 9 bits of a 16-bit
# value. Resolution is 0.5 degrees C.
return x[0] + (x[1] >> 7) * 0.5
def _init_mlm75(self):
# Check and report the chip ID but ignore errors since many
# chips don't have it
try:
prodid = self.read_register('PRODID', 1)[0]
logging.info("mlm75: Chip ID %#x" % prodid)
except:
pass
def _sample_mlm75(self, eventtime):
# self.gcode.respond_info( str(self.i) )
self.mux_channel += 1
self.mux_channel %= 4
self.mux.route( self.mux_channel ) # <<<<
# self.gcode.respond_info('mx c:'+str(self.mux.get_info()[1])) # <<<<
try:
sample = self.read_register('TEMP', 2)
self.temp = self.degrees_from_sample(sample)
except Exception:
logging.exception("mlm75: Error reading data")
self.temp = 0.0
return self.reactor.NEVER
if self.temp < self.min_temp or self.temp > self.max_temp:
self.printer.invoke_shutdown(
"MLM75 temperature %0.1f outside range of %0.1f:%.01f"
% (self.temp, self.min_temp, self.max_temp))
measured_time = self.reactor.monotonic()
self._callback(self.mcu.estimated_print_time(measured_time), self.temp)
return measured_time + self.report_time
def read_register(self, reg_name, read_len):
# read a single register
regs = [LM75_REGS[reg_name]]
params = self.i2c_sen.i2c_read(regs, read_len)
return bytearray(params['response'])
def write_register(self, reg_name, data):
if type(data) is not list:
data = [data]
reg = LM75_REGS[reg_name]
data.insert(0, reg)
self.i2c_sen.i2c_write(data)
def get_status(self, eventtime):
return {
'temperature': round(self.temp, 2),
}
def load_config(config):
# Register sensor
pheaters = config.get_printer().load_object(config, "heaters")
pheaters.add_sensor_factory("MLM75", MLM75)
This code is supposed to read, write and change the address of a MUX. For some reason I can't read part of the sensors.
That's the log:
mcu 'mcu': Starting serial connect
Loaded MCU 'mcu' 100 commands (v0.10.0-388-gd9daeb08-dirty-20220429_121230-raspberrypi / gcc: (GCC) 5.4.0 binutils: (GNU Binutils) 2.26.20160125)
MCU 'mcu' config: BUS_PINS_spi=PB3,PB2,PB1 PWM_MAX=255 CLOCK_FREQ=16000000 BUS_PINS_twi=PD0,PD1 MCU=atmega32u4 ADC_MAX=1023 STATS_SUMSQ_BASE=256
mcu 'mcu': got {u'count': 229, '#receive_time': 3173.116210849, u'sum': 315145, u'sumsq': 3550500, '#name': u'stats', '#sent_time': 3173.115847275}
Configured MCU 'mcu' (165 moves)
lm75: Chip ID 0x1e
Starting heater checks for plateHeater1
lm75: Chip ID 0x22
Starting heater checks for plateHeater2
Starting heater checks for blockHeater1
Starting heater checks for blockHeater2
mlm75: Error reading data
Traceback (most recent call last):
File "/home/heater/klipper/klippy/extras/mlm75.py", line 104, in _sample_mlm75
sample = self.read_register('TEMP', 2)
File "/home/heater/klipper/klippy/extras/mlm75.py", line 123, in read_register
params = self.i2c.i2c_read(regs, read_len) #dobaveno ot lm75.py
AttributeError: MLM75 instance has no attribute 'i2c'
mlm75: Error reading data
Traceback (most recent call last):
File "/home/heater/klipper/klippy/extras/mlm75.py", line 104, in _sample_mlm75
sample = self.read_register('TEMP', 2)
File "/home/heater/klipper/klippy/extras/mlm75.py", line 123, in read_register
params = self.i2c.i2c_read(regs, read_len) #dobaveno ot lm75.py
AttributeError: MLM75 instance has no attribute 'i2c'
I am trying to figure this thing out for 2 weeks now and my hair is starting to fall. Can someone tell me what I do wrong?
Thanks for the help
I am trying to implement a simple program in which there are several processes that concurrently communicate with each other by sending and receiving messages. In the program, there are 4 participants (each of which corresponds to a process) and communicate with each other as follows:
P1 sends P2 some_message then P2 sends P3 another_message then P3 sends P4 a_message. Based on the messages each participant receives, they perform a specific action.
Obviously, when, for instance, P1 sends P2 a message, P2 is receiving that message from P1, so they are paired.
I have found different approaches none of which are suitable as they seem to be complicated for I am looking for. For example,
Python MPI which has a restriction of "There are not enough slots available in the system". There are a few ways suggested to sort out the issue but the solutions are a bit complicated.
Socket programming which mostly suits server and client scenario. But my program doesn't have a server. I also checked this answer, which is again based on socket programming.
My question is that isn't there any simpler approach than the above ones so that I can implement what I explained? Is it possible to create communication channels in Python fairly similar to the ones in Golang?
This code I wrote a while ago to get to grips with os.pipe - it is self contained but not "minimally reproducible" since I don't have the time to redo it. It uses tkinter Uis to simulate processes and sends and receives data between them. Note that the code was written only for my private purpose.
"""Test run of the use of pipes between processes.
.. processes are control, startup , send and receive.
.. pipes from control to startup and send
.. pipe from startup to send
.. pipe from send to receive
.. startup, user input of run mode
... prompt, timer (seconds) or number of runs
.. send, user input of data
.. receive, display of data received
. each process operates independently of, and in isolation from, the other processes until data is transferred through pipes
"""
# fr read file descriptor
# fw write file descriptor
# wbs write bytes
# snb string length of output filled with 0 to write as header
# bsnb for number of bytes written, needed for read
# maxbuf number of bytes of header, 4 digits, max 9999 characters in a string/byte literal
# onb output number of bytes
# dbs data read in bytes
import tkinter as tk
from os import pipe as ospipe
from os import read as osread
from os import write as oswrite
from os import close as osclose
from datetime import datetime as dt
from time import monotonic as clock
from functools import partial
BG = '#fa4'
TBG = '#fe8'
SndBG = '#f91'
BLK = '#000'
STOP = '#d30'
START = '#0b0'
start = clock()
def timer(halt):
tm = int(clock())
if int(tm - start) > halt:
return True
else: return False
def piperead(r):
maxbuf = 4
onb = osread(r,maxbuf)
oi = int(onb.decode())
dbs = osread(r,oi).decode() # bytes to string
osclose(r)
return dbs
def pipewrite(w,s):
wbs = bytes(s, encoding='utf-8')
snb = str(len(s)).zfill(4)
bsnb = bytes(snb, encoding='utf-8')
wbs = bsnb + wbs
oswrite(w,wbs)
osclose(w)
def setpipe(process, sub=None, vars=None):
fdr, fdw = ospipe()
if sub: process(fdw,proc=(sub,vars))
else: process(fdw)
return piperead(fdr)
class Sloop():
def __init__(sl, pipewrite=None):
sl.fw = pipewrite
sl.w = tk.Tk()
sl.w.geometry('400x200-100+80')
sl.w.overrideredirect(1)
sl.w['bg'] = BG
uifnt = sl.w.tk.call('font', 'create', 'uifnt', '-family','Consolas', '-size',11)
sl.lvb = tk.Button(sl.w, bg=BLK, activebackground=BG, relief='flat', command=sl.stop)
sl.lvb.pack()
sl.lvb.place(width=15,height=15, x=380,y=10)
sl.sndb = tk.Button(sl.w,bg=SndBG,activebackground=BG,fg=TBG, text=chr(11166), command=sl.send)
sl.sndb.pack()
sl.sndb.place(width=25,height=25, x=20,y=160)
sl.tlbl = tk.Label(sl.w,bg=BG, text='write data to send...')
sl.tlbl.pack()
sl.tlbl.place(x=20,y=20)
sl.t = tk.Text(sl.w,bg=TBG)
sl.t.pack()
sl.t.place(width=300,height=100, x=20,y=45)
sl.t.focus_set()
sl.w.mainloop()
def send(sl):
sl.output = sl.t.get('1.0','end')
if sl.output != '\n':
pipewrite(sl.fw,sl.output)
sl.close()
else:
sl.error()
def error(sl):
def _clearlbl(ev):
sl.erlbl.destroy()
sl.erlbl = tk.Label(sl.w,bg=TBG,text='there is nothing to send')
sl.erlbl.pack()
sl.erlbl.place(x=20,y=160)
sl.t.focus_set()
sl.t.bind('<KeyPress>',_clearlbl)
def stop(sl):
pipewrite(sl.fw,'stop')
sl.close()
def close(sl):
sl.w.destroy()
class Rloop():
def __init__(rl, pipefread=None):
rl.fr = pipefread
rl.w = tk.Tk()
rl.w.geometry('400x200-100+320')
rl.w.overrideredirect(1)
rl.w['bg'] = BG
uifnt = rl.w.tk.call('font', 'create', 'uifnt', '-family','Consolas', '-size',10)
rl.lvb = tk.Button(rl.w, bg=BLK, activebackground=BG, relief='flat', command=rl.close)
rl.lvb.pack()
rl.lvb.place(width=15,height=15, x=380,y=10)
rl.tlbl = tk.Label(rl.w,bg=BG, text='received...')
rl.tlbl.pack()
rl.tlbl.place(x=20,y=20)
rl.t = tk.Text(rl.w,bg=TBG)
rl.t['font'] = uifnt
rl.t.pack()
rl.t.place(width=300,height=100, x=20,y=45)
rl.t.focus_set()
rl.receive()
rl.w.mainloop()
def receive(rl):
rec = piperead(rl.fr)
if rec != 'stop':
rl.t.insert('end', '\n'.join([str(dt.now()), rec]))
else: rl.close()
def close(rl):
rl.w.destroy()
class Startup():
def __init__(su, pipefwrite=None):
su.fw = pipefwrite
su.mode = ''
su.w = tk.Tk()
su.w.geometry('400x200-100+500')
su.w.overrideredirect(1)
su.w['bg'] = BG
uifnt = su.w.tk.call('font', 'create', 'uifnt', '-family','Consolas', '-size',11)
su.lvb = tk.Button(su.w, bg=BLK, activebackground=BG, relief='flat', command=su.stop)
su.lvb.pack()
su.lvb.place(width=15,height=15, x=380,y=10)
su.sndb = tk.Button(su.w,bg=SndBG,activebackground=BG,fg=TBG, text=chr(11166), command=su.send)
su.sndb.pack()
su.sndb.place(width=25,height=25, x=20,y=160)
su.title = tk.Label(su.w,bg=BG, text='Modes to continue data input')
su.title.pack()
su.titley = 10
su.title.place(x=20,y=su.titley)
su.ysp = 20
su.margin = 200
ptxt = 'prompt'
su.pb = tk.Button(su.w,bg=BG, activebackground=BG, text=ptxt, relief='flat', cursor='hand2', command=partial(su._get,e=None, nm='su.pb', ent=None))
tmtxt = ' timer '
su.tmb = tk.Button(su.w,bg=BG, activebackground=BG, text=tmtxt, relief='flat', cursor='hand2', command=partial(su._enter,ent='su.tmb'))
rntxt = ' runs '
su.rnb = tk.Button(su.w,bg=BG, activebackground=BG, text=rntxt, relief='flat', cursor='hand2', command=partial(su._enter,ent='su.rnb'))
su.pb.pack()
su.pby = su.titley + 1.5*su.ysp
su.pb.place(x=25,y=su.pby)
su.tmb.pack()
su.tmby = su.pby + 2*su.ysp
su.tmb.place(x=25,y=su.tmby)
su.rnb.pack()
su.rnby = su.pby + 4*su.ysp
su.rnb.place(x=25,y=su.rnby)
su.formd = {'su.pb':su.pb, 'su.tmb':su.tmb, 'su.rnb':su.rnb}
su.w.mainloop()
def _able(su,nm):
for key in su.formd:
if nm[0:4] not in key:
su.formd[key]['state'] = 'disabled'
else:
su.formd[key]['state'] = 'normal'
def _enter(su,ent):
if ent == 'su.tmb':
tmtxt = 'seconds'
su.tmlbl = tk.Label(su.w,bg=BG, text=tmtxt)
su.tment = tk.Entry(su.w,bg=TBG)
su.tmlbl.pack()
su.tment.pack()
tmlbly = su.tmby
su.tmlbl.place(x=su._margin(tmtxt), y=tmlbly)
su.tment.place(x=su.margin, y=tmlbly)
su.tment.focus_set()
su.tment.bind('<Return>', partial(su._get,nm='su.tment', ent=su.tment))
su.formd = su.formd | {'su.tmlbl':su.tmlbl, 'su.tment':su.tment}
elif ent == 'su.rnb':
rntxt = 'number'
su.rnlbl = tk.Label(su.w,bg=BG, text=rntxt)
su.rnent = tk.Entry(su.w,bg=TBG)
su.rnlbl.pack()
su.rnent.pack()
rnlbly = su.rnby
su.rnlbl.place(x=su._margin(rntxt), y=rnlbly)
su.rnent.place(x=su.margin, y=rnlbly)
su.rnent.focus_set()
su.rnent.bind('<Return>', partial(su._get,nm='su.rnent', ent=su.rnent))
su.formd = su.formd | {'su.rnlbl':su.rnlbl, 'su.rnent':su.rnent}
def _get(su,e,nm,ent):
if nm == 'su.pb':
su._able('su.pb')
su.mode = 'prompt,'+'1'
else:
su._able(nm)
for key in su.formd:
if key == nm:
if 'tm' in key: modestr = 'timer'
elif 'rn' in key: modestr = 'runs'
su.formd[key]['bg']=BG
su.mode = ','.join([modestr,str(ent.get())])
break
def _margin(su,txt):
return su.margin-(len(txt)*8)
def send(su):
pipewrite(su.fw,su.mode)
su.close()
def stop(su):
pipewrite(su.fw,'stop')
su.close()
def close(su):
su.w.destroy()
class Control():
def __init__(c, pipefwrite=None, proc=None):
c.fw = pipefwrite
c.proc = proc
if c.proc:
c.proc = proc[0]
if proc[1]:
c.procv = proc[1]
else:
c.procvl = None
c.procd = {'start':c._strtui, 'prompt':c._prui, 'timer':c._tmui, 'runs':c._rnui}
c.w = tk.Tk()
c.w.geometry('100x200-60+80')
c.w.overrideredirect(1)
c.w['bg'] = BG
uifnt = c.w.tk.call('font', 'create', 'uifnt', '-family','Consolas', '-size',11)
c.lvb = tk.Button(c.w, bg=BLK, activebackground=BG, relief='flat', command=c.stop)
c.lvb.pack()
c.lvb.place(width=15,height=15, x=80,y=10)
c.title = tk.Label(c.w,bg=BG, text='pipe test\nControl')
c.title.pack()
c.title.place(x=5,y=5)
c.stpclr = tk.Label(c.w,bg=STOP)
c.stpclr.pack()
stpy = 160
c.stpclr.place(width=7,height=7,x=2,y=stpy+10)
c.stopb = tk.Button(c.w, bg=BG, text='stop', cursor='hand2', relief='flat', activebackground=BG, command=c.stop)
c.stopb.pack()
c.stopb.place(x=10,y=160)
c.procd[c.proc]()
c.w.mainloop()
def _strtui(c):
c.strtclr = tk.Label(c.w,bg=START)
c.strtclr.pack()
strty = 60
c.strtclr.place(width=7,height=7,x=2,y=strty+10)
c.startb = tk.Button(c.w, bg=BG, text='start', cursor='hand2', relief='flat', activebackground=BG, command=c.strtup)
c.startb.pack()
c.startb.place(x=10,y=strty)
def __write(c,s):
pipewrite(c.fw,s)
c.close()
def _prui(c):
prb = tk.Button(c.w,bg=TBG, text='--- next ---', activebackground=BG, relief='flat',cursor='hand2', command=partial(c.__write,'prompt'))
prb.pack()
prb.place(x=10,y=80)
def __confirm(c):
cb = tk.Button(c.w, bg=TBG, text='confirm', activebackground=BG, relief= 'flat', cursor='hand2', command=partial(c.__write,'confirm'))
cb.pack()
cb.place(x=20,y=120)
def _tmui(c):
tmt = ''.join(['run for\n',str(c.procv),' seconds'])
tmlbl = tk.Label(c.w,bg=BG, text=tmt)
tmlbl.pack()
tmlbl.place(x=10,y=80)
c.__confirm()
def _rnui(c):
rnt = ''.join(['run\n ',str(c.procv),' times'])
rnlbl = tk.Label(c.w,bg=BG, text=rnt)
rnlbl.pack()
rnlbl.place(x=10,y=80)
c.__confirm()
def strtup(c):
pipewrite(c.fw,'startup')
c.close()
def stop(c):
pipewrite(c.fw,'stop')
c.close()
def close(c):
c.w.destroy()
def once():
fr, fw = ospipe()
Sloop(fw)
Rloop(fr)
def many(mkey,mint=1):
"""modes are ('prompt',1), ('timer',secs), ('runs',runs)
"""
if mkey == 'timer':
rec = setpipe(Control,sub='timer',vars=mint)
if rec == 'confirm':
while not timer(mint):
once()
return True
elif rec == 'stop':
return False
elif mkey == 'runs':
rec = setpipe(Control,sub='runs',vars=mint)
if rec == 'confirm':
for r in range(mint):
once()
return True
elif rec == 'stop':
return False
elif mkey == 'prompt':
quit = False
while not quit:
once()
rec = setpipe(Control,sub='prompt')
if rec != 'prompt':
quit = True
return True
def testui():
incontrol = True
while incontrol:
rec = setpipe(Control,sub='start')
if rec == 'startup':
rec = setpipe(Startup)
if rec != 'stop':
modes, p, ns = rec.partition(',')
incontrol = many(modes,int(ns))
else:
incontrol = False
if __name__ == '__main__':
testui()
I am new to python and I am trying to write a code to send hex serial data to a radio and receive hex data in response. radio_init_buf variable store the hex data to be sent. The last two bytes with store checksum. radio_init_buf[3] tells the size.
import sys
import glob
import numpy as np
import serial
class serial_communication():
PORT = 'COM2'
# RETURN_VALUE = None
def list_serial_ports(self):
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(0,10)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
def serial_open(self):
self.ser = serial.Serial()
self.ser.baudrate = 9600
self.ser.port = sc.PORT
self.ser.parity = serial.PARITY_NONE
self.ser.stopbits = serial.STOPBITS_ONE
self.ser.bytesize = serial.EIGHTBITS
self.ser.writeTimeout = 1000
self.ser.timeout = 1000
try:
self.ser.open()
print("Port OPENED")
self.initialize(self.ser)
except Exception as e:
print("error opening serial port: " + str(e))
exit()
return self.ser
def checksum(self, crc_packet, crc_packet_length):
crc_table= np.array([0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040],dtype=np.uint16)
saved_crc_byte1 = crc_packet[crc_packet_length - 1]
saved_crc_byte2 = crc_packet[crc_packet_length - 2]
crc_packet[crc_packet_length - 1] = 0
crc_packet[crc_packet_length - 2] = 0
crc = 0
for crc_loop in range(0,crc_packet_length):
crc = (crc >> 8) ^ crc_table[(crc ^ crc_packet[crc_loop]) & 0xFF]
def initialize(self,serial_port):
ser = serial_port
if ser.isOpen():
print("Initialising...")
try:
ser.flushInput() # flush input buffer, discarding all its contents
ser.flushOutput() # flush output buffer, aborting current output
# and discard all that is in buffer
# write data
#f = open('F:/output.txt', 'wb')
radio_init_buf = np.array([0xAA, 0x00, 0x00, 0x08, 0x09, 0x32, 0x0, 0x0],dtype=np.uint8)
#radio_init_buf="\xAA\x00\x00\x08\x09\x32\x00\x00"
print(radio_init_buf)
self.checksum(radio_init_buf,radio_init_buf[3])
print(radio_init_buf)
ser.write(radio_init_buf)
serial.time.sleep(0.5) # give the serial port sometime to receive the data
#return_value = ser.read(7)
print(return_value)
print("Initialisation Complete")
#comm Link Check
print("Communication Link Checking..")
comm_check_buf = np.array([0xAA, 0x06, 00, 6, 0x0B, 0x70],dtype=np.uint8)
ser.write(comm_check_buf)
print("Link Check Complete")
#clear non-volatile memory
clear_nvm_buf = np.array([0xAA, 0x82, 00, 7, 1, 0, 0],dtype=np.uint8)
self.checksum(clear_nvm_buf, clear_nvm_buf[3])
ser.write(clear_nvm_buf)
#ser.close()
except Exception as e1:
print ("error communicating...: " + str(e1))
ser.close()
else:
print("cannot open serial port ")
sc = serial_communication()
print(sc.list_serial_ports())
sc.serial_open()
When i run the code i get:
['COM1', 'COM2', 'COM3']
Port OPENED
Initialising...
[170 0 0 8 9 50 0 0]
[170 0 0 8 9 50 0 0]
b'\xaa\x90\x00\x12\x01\x0c\x00'
Initialisation Complete
Communication Link Checking..
Link Check Complete
Instead of [170 0 0 8 9 50 0 0], i want the hex data.
Also, it is not returning radio_init_buf with checksum. The result after calling checksum is same.
Displaying in hex:
for n in radio_init_buf:
print("{:#x}".format(n), end='')
print()
{:#x} - a format string, #: adds the 0x prefix, x: presentation will be in hex,
In one line:
print(("{:#x} "*len(radio_init_buf)).format(*radio_init_buf))
It creates a string of length len(radio_init_buf).
In *radio_init_buf , '*' unpacks the list.
I have a matrix keypad and a hd44780 lcd connected into raspberry pi.
The below code are in python. It will take 4 digit password from the user, but when the user enter the digit through the keypad, nothing was display on the lcd. I would like when the user enter a digit a * display on the lcd. I can only manage to get the * print in the same place,but not in 4 separate place.
Code
import RPi.GPIO as GPIO
import time
import lcd
import os
import subprocess
from subprocess import call
mylcd = lcd.lcd()
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
MATRIX = [['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']]
ROW = [5,6,13,19]
COL = [26,16,20,21]
for j in range(4):
GPIO.setup(COL[j], GPIO.OUT)
GPIO.output(COL[j], 1)
for i in range(4):
GPIO.setup(ROW[i], GPIO.IN, pull_up_down=GPIO.PUD_UP)
password = "1234"
attempt = ""
try:
while (True):
mylcd.lcd_display_string("Enter pw",1)
for j in range(4):
GPIO.output(COL[j], 0)
for i in range(4):
if GPIO.input(ROW[i]) == 0:
mylcd.lcd_display_string("*",2,0)
time.sleep(0.01)
while (GPIO.input(ROW[i]) == 0):
pass
attempt += MATRIX[i][j]
if len(attempt) == len(password):
if attempt == password:
mylcd.lcd_clear()
print "Password OK"
mylcd.lcd_display_string("Password",1 ,4 )
mylcd.lcd_display_string("Ok!",2 ,6 )
time.sleep(2)
mylcd.lcd_clear()
os.chdir('/home/pi/nfc/py532lib')
call('./nfc.sh')
mylcd.lcd_clear()
else:
print(attempt)
print "Password incorrect"
mylcd.lcd_display_string("Password",1,4)
mylcd.lcd_display_string("Incorrect!",2,3)
time.sleep(2)
mylcd.lcd_clear()
attempt = ""
time.sleep(0.01)
GPIO.output(COL[j], 1)
except KeyboardInterrupt:
GPIO.cleanup()
LCD Library
# -*- coding: utf-8 -*-
# Original code found at:
# https://gist.github.com/DenisFromHR/cc863375a6e19dce359d
"""
Compiled, mashed and generally mutilated 2014-2015 by Denis Pleic
Made available under GNU GENERAL PUBLIC LICENSE
# Modified Python I2C library for Raspberry Pi
# as found on http://www.recantha.co.uk/blog/?p=4849
# Joined existing 'i2c_lib.py' and 'lcddriver.py' into a single library
# added bits and pieces from various sources
# By DenisFromHR (Denis Pleic)
# 2015-02-10, ver 0.1
"""
# i2c bus (0 -- original Pi, 1 -- Rev 2 Pi)
I2CBUS = 0
# LCD Address
ADDRESS = 0x27
import smbus
from time import sleep
class i2c_device:
def __init__(self, addr, port=I2CBUS):
self.addr = addr
self.bus = smbus.SMBus(port)
# Write a single command
def write_cmd(self, cmd):
self.bus.write_byte(self.addr, cmd)
sleep(0.0001)
# Write a command and argument
def write_cmd_arg(self, cmd, data):
self.bus.write_byte_data(self.addr, cmd, data)
sleep(0.0001)
# Write a block of data
def write_block_data(self, cmd, data):
self.bus.write_block_data(self.addr, cmd, data)
sleep(0.0001)
# Read a single byte
def read(self):
return self.bus.read_byte(self.addr)
# Read
def read_data(self, cmd):
return self.bus.read_byte_data(self.addr, cmd)
# Read a block of data
def read_block_data(self, cmd):
return self.bus.read_block_data(self.addr, cmd)
# commands
LCD_CLEARDISPLAY = 0x01
LCD_RETURNHOME = 0x02
LCD_ENTRYMODESET = 0x04
LCD_DISPLAYCONTROL = 0x08
LCD_CURSORSHIFT = 0x10
LCD_FUNCTIONSET = 0x20
LCD_SETCGRAMADDR = 0x40
LCD_SETDDRAMADDR = 0x80
# flags for display entry mode
LCD_ENTRYRIGHT = 0x00
LCD_ENTRYLEFT = 0x02
LCD_ENTRYSHIFTINCREMENT = 0x01
LCD_ENTRYSHIFTDECREMENT = 0x00
# flags for display on/off control
LCD_DISPLAYON = 0x04
LCD_DISPLAYOFF = 0x00
LCD_CURSORON = 0x02
LCD_CURSOROFF = 0x00
LCD_BLINKON = 0x01
LCD_BLINKOFF = 0x00
# flags for display/cursor shift
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00
LCD_MOVERIGHT = 0x04
LCD_MOVELEFT = 0x00
# flags for function set
LCD_8BITMODE = 0x10
LCD_4BITMODE = 0x00
LCD_2LINE = 0x08
LCD_1LINE = 0x00
LCD_5x10DOTS = 0x04
LCD_5x8DOTS = 0x00
# flags for backlight control
LCD_BACKLIGHT = 0x08
LCD_NOBACKLIGHT = 0x00
En = 0b00000100 # Enable bit
Rw = 0b00000010 # Read/Write bit
Rs = 0b00000001 # Register select bit
class lcd:
#initializes objects and lcd
def __init__(self):
self.lcd_device = i2c_device(ADDRESS)
self.lcd_write(0x03)
self.lcd_write(0x03)
self.lcd_write(0x03)
self.lcd_write(0x02)
self.lcd_write(LCD_FUNCTIONSET | LCD_2LINE | LCD_5x8DOTS | LCD_4BITMODE)
self.lcd_write(LCD_DISPLAYCONTROL | LCD_DISPLAYON)
self.lcd_write(LCD_CLEARDISPLAY)
self.lcd_write(LCD_ENTRYMODESET | LCD_ENTRYLEFT)
sleep(0.2)
# clocks EN to latch command
def lcd_strobe(self, data):
self.lcd_device.write_cmd(data | En | LCD_BACKLIGHT)
sleep(.0005)
self.lcd_device.write_cmd(((data & ~En) | LCD_BACKLIGHT))
sleep(.0001)
def lcd_write_four_bits(self, data):
self.lcd_device.write_cmd(data | LCD_BACKLIGHT)
self.lcd_strobe(data)
# write a command to lcd
def lcd_write(self, cmd, mode=0):
self.lcd_write_four_bits(mode | (cmd & 0xF0))
self.lcd_write_four_bits(mode | ((cmd << 4) & 0xF0))
# write a character to lcd (or character rom) 0x09: backlight | RS=DR<
# works!
def lcd_write_char(self, charvalue, mode=1):
self.lcd_write_four_bits(mode | (charvalue & 0xF0))
self.lcd_write_four_bits(mode | ((charvalue << 4) & 0xF0))
# put string function with optional char positioning
def lcd_display_string(self, string, line=1, pos=0):
if line == 1:
pos_new = pos
elif line == 2:
pos_new = 0x40 + pos
elif line == 3:
pos_new = 0x14 + pos
elif line == 4:
pos_new = 0x54 + pos
self.lcd_write(0x80 + pos_new)
for char in string:
self.lcd_write(ord(char), Rs)
# clear lcd and set to home
def lcd_clear(self):
self.lcd_write(LCD_CLEARDISPLAY)
self.lcd_write(LCD_RETURNHOME)
# define backlight on/off (lcd.backlight(1); off= lcd.backlight(0)
def backlight(self, state): # for state, 1 = on, 0 = off
if state == 1:
self.lcd_device.write_cmd(LCD_BACKLIGHT)
elif state == 0:
self.lcd_device.write_cmd(LCD_NOBACKLIGHT)
# add custom characters (0 - 7)
def lcd_load_custom_chars(self, fontdata):
self.lcd_write(0x40);
for char in fontdata:
for line in char:
self.lcd_write_char(line)
Your code may be not correct. For each output you test all inputs:
for i in range(4):
if GPIO.input(ROW[i]) == 0:
Check if for sure exactly one proper input is active. If not, you have to rewrite it.
Moreover, the number of * should depend on external counter j, not i (my mistake in the comment, sorry):
mylcd.lcd_display_string((j+1) * "*", 2, 0)
I created a simple network in the mininet environment with the following command:
$ sudo mn --topo single,3 --mac --controller remote --switch ovsk
I want use RYU CONTROLLER to calculate bandwidth traffic on special port of switch. I'm thinking of using an OFPEVENTPacketIn event for the incoming packet, but I do not any idea for out coming packet form port.
My code:
from operator import attrgetter
from ryu.app import simple_switch_13
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.lib import hub
class SimpleMonitor(simple_switch_13.SimpleSwitch13):
def __init__(self, *args, **kwargs):
super(SimpleMonitor, self).__init__(*args, **kwargs)
self.datapaths = {}
self.monitor_thread = hub.spawn(self._monitor)
#set_ev_cls(ofp_event.EventOFPStateChange,
[MAIN_DISPATCHER, DEAD_DISPATCHER])
def _state_change_handler1(self, ev):
datapath = ev.datapath
if ev.state == MAIN_DISPATCHER:
if not datapath.id in self.datapaths:
self.logger.debug('register datapath: %016x', datapath.id)
self.datapaths[datapath.id] = datapath
elif ev.state == DEAD_DISPATCHER:
if datapath.id in self.datapaths:
self.logger.debug('unregister datapath: %016x', datapath.id)
del self.datapaths[datapath.id]
def _monitor(self):
while True:
for dp in self.datapaths.values():
self._request_stats(dp)
hub.sleep(10)
def _request_stats(self, datapath):
self.logger.debug('send stats request: %016x', datapath.id)
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
req = parser.OFPFlowStatsRequest(datapath)
datapath.send_msg(req)
req = parser.OFPPortStatsRequest(datapath, 0, ofproto.OFPP_ANY)
datapath.send_msg(req)
#set_ev_cls(ofp_event.EventOFPFlowStatsReply, MAIN_DISPATCHER)
def _flow_stats_reply_handler(self, ev):
body = ev.msg.body
self.logger.info('datapath '
'in-port eth-dst '
'out-port packets bytes')
self.logger.info('---------------- '
'-------- ----------------- '
'-------- -------- --------')
for stat in sorted([flow for flow in body if flow.priority == 1],
key=lambda flow: (flow.match['in_port'],
flow.match['eth_dst'])):
# self.logger.info('%016x %8x %17s %8x %8d %8d',
if stat.match['in_port']==1:
self.logger.info('%x %x %s %x %d %d',
ev.msg.datapath.id,
stat.match['in_port'], stat.match['eth_dst'],
stat.instructions[0].actions[0].port,
stat.packet_count, stat.byte_count)
#for stat in [1234]#sorted([flow for flow in body if flow.priority == 1],
# key=lambda flow: (flow.match['in_port'],
# flow.match['eth_dst'])):
# self.logger.info('%016x %8x %17s %8x %8d %8d',
# if stat.match['in_port']==1:
# self.logger.info('%x %x %s %x %d %d',
# ev.msg.datapath.id,
# stat.match['in_port'], stat.match['eth_dst'],
# stat.instructions[0].actions[0].port,
# stat.packet_count, stat.byte_count)
#set_ev_cls(ofp_event.EventOFPPortStatsReply, MAIN_DISPATCHER)
def _port_stats_reply_handler(self, ev):
body = ev.msg.body
self.logger.info('datapath port '
'rx-pkts rx-bytes rx-error '
'tx-pkts tx-bytes tx-error')
self.logger.info('---------------- -------- '
'-------- -------- -------- '
'-------- -------- --------')
for stat in sorted(body, key=attrgetter('port_no')):
if stat.port_no==1:
self.logger.info('%016x %8x %8d %8d %8d %8d %8d %8d',
ev.msg.datapath.id, stat.port_no,
stat.rx_packets, stat.rx_bytes, stat.rx_errors,
stat.tx_packets, stat.tx_bytes, stat.tx_errors)
Please help me edit this code to answer my question. Thanks.
You have to add two method in your controller:
1) a method that requests stats
2) a method that captures the answers from switches.
The method for answering stats is the following:
def send_flow_stats_request(self, datapath):
ofp = datapath.ofproto
ofp_parser = datapath.ofproto_parser
cookie = cookie_mask = 0
match = ofp_parser.OFPMatch(in_port=1)
req = ofp_parser.OFPFlowStatsRequest(datapath, 0,
ofp.OFPTT_ALL,
ofp.OFPP_ANY, ofp.OFPG_ANY,
cookie, cookie_mask,
match)
datapath.send_msg(req)
The method for capturing answers is this one:
#set_ev_cls(ofp_event.EventOFPFlowStatsReply, MAIN_DISPATCHER)
def flow_stats_reply_handler(self, ev):
flows = []
for stat in ev.msg.body:
flows.append('table_id=%s '
'duration_sec=%d duration_nsec=%d '
'priority=%d '
'idle_timeout=%d hard_timeout=%d flags=0x%04x '
'cookie=%d packet_count=%d byte_count=%d '
'match=%s instructions=%s' %
(stat.table_id,
stat.duration_sec, stat.duration_nsec,
stat.priority,
stat.idle_timeout, stat.hard_timeout, stat.flags,
stat.cookie, stat.packet_count, stat.byte_count,
stat.match, stat.instructions))
self.logger.debug('FlowStats: %s', flows)
Once you capture stats you can compute bandwidth usage.
However you have also other kind of requests you can perform so i suggest you to read the rye doc.
http://ryu.readthedocs.io/en/latest/