Why does AT86RF231 not send my data? - python

I've been searching the web for days now and neither the web nor the manual helped me.
In fact I want a simple send and receive routine in Python for the AT86RF231. Both radios are plugged on a raspberry pi.
I think all the registers are set up properly but when trying to send a packet, there is nothing received on the receiver side and the IRQ TRX_END is not raised as well.
The implemented "test mode" does not work for me as well and I can't figure out why.
The datasheet is available here.
# -*- coding: utf-8 -*-
import spidev
import time
import RPi.GPIO as GPIO
import binascii
import string
import random
#Definitions
dont_care = 0
nRST = 27
#Abkürzung
spi=spidev.SpiDev()
#make sure /RST is high
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#GPIO 27 als Output konfigurieren
GPIO.setup(nRST, GPIO.OUT)
GPIO.output(nRST,GPIO.HIGH)
#Reset
def reset():
GPIO.output(nRST,GPIO.LOW)
time.sleep(0.001)
GPIO.output(nRST,GPIO.HIGH)
while (read(0x01,0)[1]!= 0 | read(0x01,0)[1]!= 8):
time.sleep(0.001)
print "Reset complete"
# get Device ID
def DevID():
ID = spi.xfer2([0x9C,0])
print "ID:"
print ID
#write data
def write(addr, value):
spi.xfer2([addr | 0xC0, value])
#read data
def read(addr, value):
data = spi.xfer2([addr | 0x80, value])
return data
#read framebuffer
def frameread():
output = spi.xfer2([0x20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
return output
#read transmissionstatus
def transstatus():
status = read(0x01,0)[1]
print status
if (status == 0):
print "P_ON"
elif (status == 1):
print "Busy_RX"
elif (status== 2):
print "Busy_TX"
elif (status == 6):
print "RX_ON"
elif (status==8):
print "TRX_Off"
else :
print "Kontrolle des Status nötwendig"
#?
def status():
status = spi.xfer2([0x81, 0])
if (status[1]==0):
print "Status: default"
elif (status[1]==1):
print "Status: monitor TRX_Status"
elif (status[1]==2):
print "Status: monitor PHY_RSSI"
elif (status[1]==3):
print "Status: monitor IRQ_Statis"
return status[1]
#Continuous Transmission Test Mode
#Register werden in der Anleitung beschrieben
def testmode():
reset()
DevID()
write(0x0E, 0x01)
write(0x04, 0x00)
write(0x02, 0x03)
write(0x03, 0x01)
write(0x08, 0x33)
write(0x05, 0x00)
status()
while(read(0x01, 0x00) == 8):
time.sleep(0.1)
print "Transmission in progress - waiting"
write(0x036, 0x0F)
# hier muss der Inhalt beschrieben werden
#0x60 Frame write Acess,10 Frames, Inhalt
spi.xfer2([0x60,0x0A,1,2,6,4,5,6,7,8,9,10])
write(0x1C, 0x54)
write(0x1C, 0x46)
write(0x02, 0x09)
print read(0x0F, 0x01)
while(read(0x0F, 0x01)[1]!=0):
time.sleep(0.1)
print "Waiting for PLL_Lock"
write(0x02, 0x02)
#Messung
transstatus()
print "Messung durchführen"
time.sleep(10)
write(0x1C, 0x00)
#Reset machen
reset()
#enable receiver
def receiver_enable():
write(0x02,0x08)
write(0x02,0x06)
# make randomisierte Pakete
def id_generator(size,chars=string.digits):
return ''.join(random.choice(chars) for _ in range(size))
#generate Frame
def make_frame(length, power, transmission_type):
data = id_generator(length)
dataframe = []
dataframe.append(length + 2)
dataframe.append(power)
dataframe.append(transmission_type)
for i in range(0,len(data),1):
dataframe.append(data[i])
return dataframe
# send frame
def send_frame(frame):
write(0x0E, 0x01)
write(0x04, 0x00)
write(0x02, 0x03)
write(0x08, 0x33)
write(0x05, 0x00)
write_frame(frame)
while (read(0x01,0)[1] != 8):
time.sleep(0.1)
print "Waiting for TRX_OFF"
write(0x02, 0x09)
time.sleep(.1)
while(read(0x01,0)[1] != 9):
time.sleep(0.1)
print "Waiting for PLL_Lock"
#TX start
write(0x02, 0x02)
while(read(0x01, 0)[1] == 2):
time.sleep(0.1)
print "Busy TX"
#set transmit power 1-16
def set_power(power):
write(0x05, power)
# Framebuffer write
def write_frame(data):
if isinstance(data, basestring):
spi.xfer2([0x60,len(data)] + [int(ord(i)) for i in list(data)])
else:
print "bin heir"
dataframe = []
dataframe.append(0x60)
dataframe.append(len(data))
for i in range(0,len(data),1):
dataframe.append(int(data[i]))
print dataframe
spi.xfer2(dataframe)
sender routine
spi.open(0,0)
reset()
while(1):
testmode()
time.sleep(1)
spi.close()
receiver routine
spi.open(0,0)
reset()
receiver_enable()
while(1):
print frameread()
spi.close()

Found a solution by myself. The selected Channel was actually wrong. 0x33 was in the manual given but this Channel does not exist. Change this in transmitter and receiver register and everything will work like charm.

Related

How can i use TCP/IP communication routine in a different thread for continuous operation

I am working in a project where I interfaces two rotary encoder with Raspberry pi and at same time read two sensor values and shown them on tkinter window and now as per project I need to send these values to PC whenever a query command receive from PC .I read from google that if we want two continuous loop then we cab achieve via thread method. But I don't have enough knowledge about threading.
Below I am providing tkinter code as well as TCP/IP code.
import pigpio
import tkinter as tk
from PIL import ImageTk,Image
import time
from RPi import GPIO
import serial
i="*00T%"
j="*01T%"
s=serial.Serial(port='/dev/ttyS0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1)
class decoder: # class for decoding rotary encoder
def __init__(self, pi, gpioA, gpioB, callback):
----------
---------------
----------------
if __name__ == "__main__":
rpm=0
tor=0
pow=0
pi = pigpio.pi()
st=1
pos=0
def callback(way): # interrupt event sense on pin no 17,18
global pos
global st
if st ==1:
pos += way
if pos >= 9999:
pos=9999
if pos <= 0:
pos=0
var.set(pos)
print("pos={}".format(pos))
def rpm_update():
--------------
rpm read code
---------------
def tor_update():
-------------------
torque read code
---------------------
def pow_update():
------------------------
power Calculation
--------------------------
def update():
--------------------
root.after(200,update)
path="/home/pi/logo.png"
root=tk.Tk()
img=ImageTk.PhotoImage(Image.open(path))
panel=tk.Label(root,image=img)
panel.pack()
panel.place(x=195,y=10,height=50,width=80)
root.title("Dynalec")
root.geometry("500x600")
{
body of tkinter screen
}
decoder=decoder(pi, 17, 18, callback)
root.after(200,update)
root.mainloop()
and my server code which is working perfectly in while loop.
I want to merge this two code two achieve desire result perfectly.
import socket
import encodings
rpm = 2000
tor = 35
pow = 7.33
HOST = '169.254.29.78'
PORT = 65432
def data():
global rpm, tor, pow
my_sensor = "{},{},{}".format(rpm,tor,pow)
return my_sensor # return data seperated by comma
def my_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print("Server Started waiting for client to connect ")
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024).decode('utf-8')
if str(data) == "Data":
print("Ok Sending data ")
my_data = data()
x_encoded_data = my_data.encode('utf-8')
conn.sendall(x_encoded_data)
elif str(data) == "Quit":
print("shutting down server ")
break
if not data:
break
else:
pass
if __name__ == '__main__':
while 1:
my_server()

RFID scanner doesn't scan afterwards

I am very new to coding and I'm working on this project that I have no idea why is it not running as expected. I am sorry if I'm not posting this correctly because this is my first time posting on stackoverflow. Pardon my English if there's any point where I didn't explain it correctly.
This is a project supposed to be a security system one, where we work with RFID Scanner, Camera, LED, Servo and PIR Sensor.
The conditions are as, when the time is 7am to 11pm, the pir sensor would be off and when time is 11pm onwards to 7am in the morning, the PIR sensor and camera will be turned on. Where during anytime, as long as the number of people in the house is = 0 (determined by the RFID), the camera and PIR Sensor would turn on too.
I haven't got a chance to even test out my code's logic, because when I tried to run the code, an error occurs at the loop part. "Scan a registered card to skip registration" would print and "checkpoint" would print, but afterward the code just stops there. It is supposed to be listening to the RFID scanner to read for scans, but when I tapped my card on the RFID scanner there was no response. And my code just dies there. As I'm very new to coding and python, I don't know where the errors could be. Would appreciate the help given!!
import RPi.GPIO as GPIO
from time import sleep
import sys
import requests
from datetime import datetime
from mfrc522 import SimpleMFRC522 #RFID
import os
import pygame, sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from pygame.locals import *
import pygame.camera
width = 640
height = 480
#initialise pygame
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(width,height))
no=0
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(24,GPIO.OUT) #LED
GPIO.setup(26,GPIO.OUT) #Servo
GPIO.setup(17,GPIO.IN) #PIR Sensor
current_time =datetime.now() #Current time
sleep(5)
reader = SimpleMFRC522() #RFID reader
auth = []
in_house =[]
p = open("presentlist.txt","a+")
p = open("presentlist.txt","r+")
present = 0
PIR_state =0
PWM=GPIO.PWM(26,50) #Set 50hz PWM output at GPIO26
PWM.start(12) #To edit to actual 3oclock (Locked)
fromaddr = "pythonprogramtest123#gmail.com" # change the email address accordingly
toaddr = "pythonprogramtest123#gmail.com" # Same email
#password: abcdefgpython
mail = MIMEMultipart()
mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "Attachment"
body = "Unusual movement detected"
print('Door Locked')
print("Hold card near the reader to register it in the database.")
print("Registration up to 10 cards")
print("Scan a registered card to skip registration")
for count in range (0,11):
print("checkpoint1")
id = reader.read_id()
id = str(id)
f = open("authlist.txt", "a+")
f = open("authlist.txt", "r+")
print("checkpoint2")
if f.mode == "r+":
auth=f.read()
if id not in auth:
f.write(id)
f.write('\n')
f.close()
pos = auth.count('\n')
print("New card with UID", id, "detected: registered as entry #",pos)
count = count +1
else:
number = auth.split('\n')
pos = number.index(id)
print("Card with UID", id, "already registered as entry #", pos)
count = 11
break
while (True):
id = reader.read_id()
id = str(id)
f = open("authlist.txt", "a+")
f = open("authlist.txt", "r+")
if current_time.hour >= 7 or current_time.hour <= 23 or present == 0: #awake or nobody in house
#RFID is on
if f.mode == "r+":
auth=f.read()
if id in auth and id not in in_house:
p.write(id)
p.write('\n')
p.close()
present = in_house.count('\n')
print("Recognition successful \n Allowing Access")
PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Unlocking door for 1 minute")
sleep(60)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
else: #no tap detected
sleep(30)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
break
elif id in auth and id in in_house:
p.remove(id)
print("Recognition successful \n Allowing Access")
PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Unlocking door for 1 minute")
sleep(60)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
else: #no tap detected
sleep(30)
PWM.start(12) #To edit to actual 3oclock (Locked)
f.close()
break
else:
print("Card not recognised \n Access Denied")
break
elif current_time.hour < 7 or current_time.hour > 23: #sleeping
id = reader.read_id()
id = str(id)
f = open("authlist.txt", "a+")
f = open("authlist.txt", "r+")
#RFID is on
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Recognition successful \n Allowing Access")
PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
if f.mode == "r+":
auth=f.read()
if id in auth:
print("Unlocking door for 1 minute")
sleep(60)
PWM.start(12) #To edit to actual 3oclock (Locked)
else: #no tap detected
sleep(30)
PWM.start(12) #To edit to actual 3oclock (Locked)
break
else:
print("Card not recognised \n Access Denied")
break
#Camera
if GPIO.input(17): #read a HIGH i.e. motion is detected
#LED Blink
GPIO.output(24,1)
sleep(1)
GPIO.output(24,0)
sleep(1)
GPIO.output(24,1)
sleep(1)
GPIO.output(24,0)
if PIR_state==0:
print('detected HIGH i.e. motion detected')
PIR_state=1
#Camera
cam.start() #start
image = cam.get_image() #take pic
cam.stop()
no = no + 1
saved_img=pygame.image.save(windowSurfaceObj,'picture' + "{:03d}".format(no) + '.jpg')
#Thingspeak
print("Updating Thingpseak")
resp = requests.get("GET https://api.thingspeak.com/update?api_key=PQ44ZG5JR49ABODY&field1=0")
#Email
def sendMail(data):
mail.attach(MIMEText(body, 'plain'))
print (data)
dat='%s.jpg'%data
print (dat)
attachment = open(dat, 'rb')
image=MIMEImage(attachment.read())
attachment.close()
mail.attach(image)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "abcdefgpython")
text = mail.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
else: #read a LOW i.e. no motion is detected
if PIR_state==1:
print('detected LOW i.e. no motion detected')
PIR_state=0
sleep(1)
print("...")
break
sleep(2)

Socket.close() doesn't close the Socket

I'm trying to develop a very simple client/server program, the server part is working properly but I've a problem with the client part but I can't understand why.
The client's work is very simple, just retrive the counter value from a external device, then I'm trying to send the retrieved data to the server part.
At the beginning the socket is working well, but some time when I should send the data I've got the server exception and after that the Client is not working.
I can't understand if the s.close() function is working properly.
UPDATE: the exception that I got is "errno 110 connection timed out"
Client:
import time, socket, struct, array, json
import Client_Axis
import sys
import serial
import os
import datetime
import re
import packet
import Config_mio
usbport = '/dev/ttyAMA0'
h = "/r/n"
if __name__=="__main__":
"""Main function that starts the server"""
curr_value = "0000000000"
prev_value = ""
line = '111111111111111'
error_counter = 0
people_in = 0
people_out = 0
txtDate = ""
no_updates_counter = 0
while True:
ser = None
try:
# print('1')
ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1)
# ser.open()
# print('2')
for line in ser.read():
line = ser.readline()
print(line[6:10])
curr_value = line
except:
print('Serial error')
# print('3')
pass
finally:
if ser:
ser.close()
try:
error_counter += 1
# print('1')
response = Client_Axis.Read_Axis_Camera_Occupancy()
content = response.split(",")
people_in_refresh = int(re.search(r'\d+', content[3]).group())
people_out_refresh = int(re.search(r'\d+', content[4]).group())
# print('2')
error_flag = 0
if people_in != people_in_refresh or people_out != people_out_refresh:
people_in = people_in_refresh
people_out = people_out_refresh
try:
# Creates TCP socket in the specified IP address and port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect client to the server
s.connect((Config_mio.IP_Server_Add, Config_mio.ws_port))
# Create message and send it to server
timestamp = str(time.time())
# msg = packet("c", timestamp, Config_mio.RbPi_Id, content[3], content[4], None)
msg = "c"+","+str(timestamp)+","+str(Config_mio.RbPi_Id)+","+str(people_in)+","+str(people_out)+","+"None"
# json_message = json.dumps(msg)
# s.send(json_message)
s.send(msg)
print "messaggio INVIATO"
# Close connection when data is sent
#s.close()
except:
print('Server connection error 1')
pass
finally:
s.close()
#AXIS_occup_old = AXIS_occup
#AXIS_occup = response.read()
#my_dict = json.loads(AXIS_occup)
# print(AXIS_occup)
# print(my_dict)
#del my_dict["timestamp"]
#AXIS_occup = my_dict
#error_counter = 0
# print('3')
except:
error_msg = "Error retrieving occupancy from: " + Config_mio.IP_AXIS_Add
error_flag = 1
if (error_flag == 1):
no_updates_counter = 0
print "Error detected: %s \r\n" % error_msg
print error_counter
if (error_counter > 200):
os.system("sudo reboot")
elif (line[6:10] != '1111' and prev_value != curr_value):
try:
# Creates TCP socket in the specified IP address and port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect client to the server
s.connect((Config_mio.IP_Server_Add, Config_mio.ws_port))
# Create message and send it to server
timestamp = str(time.time())
msg = "r"+","+str(timestamp)+","+str(Config_mio.RbPi_Id)+","+"None"+","+"None"+","+str(line[6:10])
#msg = {"Id": raspberry_id,
# "Ranging": line[6:10],
# "timestamp": timestamp}
#json_message = json.dumps(msg)
#s.send(json_message)
s.send(msg)
print "Message : %s" % msg
# Close connection when data is sent
s.close()
except:
print('Server connection error 2')
pass
else:
no_updates_counter += 1
# Send message despite there are no changes in value
# This is a heartbeat message of 10 min
if (no_updates_counter > 200):
no_updates_counter = 0
AXIS_occup = ""
prev_value = curr_value
# Reboot device every day - routine
# We have 4 cases incase we miss few seconds
txtDate = str(datetime.datetime.fromtimestamp(time.time()))
if (txtDate[11:19] == "00:00:00"):
os.system("sudo reboot")
if (txtDate[11:19] == "00:00:01"):
os.system("sudo reboot")
if (txtDate[11:19] == "00:00:02"):
os.system("sudo reboot")
if (txtDate[11:19] == "00:00:03"):
os.system("sudo reboot")
# Kill time - 1 sec: Remove it for high speed localisation
time.sleep(1)
Server:
import socket
import json
import time
import Config_mio
import packet
import sqlite3 as lite
if __name__ == "__main__":
"""Main function that starts the server"""
# Creates TCP socket in the specified IP address and port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((Config_mio.IP_Server_Add, Config_mio.ws_port))
# Starts server, up to 10 clients are queued
s.listen(Config_mio.Max_Num_Clients)
while True:
conn, addr = s.accept()
#print "sono dopo ascolto"
msg = conn.recv(1024)
print "Data value:",msg
msg = msg.split(",")
if msg[0] == "c":
print "counter msg"
elif msg[0] == "r":
print "range msg",msg[1],msg[2],msg[5]
conn.close()

Why does this python program not work in IDLE, when using a raspberry pi?

The following code communicates with multiple pH modules, via the serial port. The pH modules are selected via a multiplexer via the i2c bus using an 8574N chip. When the raspberry pi has booted up the program works correctly in the terminal however, if the program was to be stop and be restarted it fails to initialize correctly. Also, this program does not work correctly in the python IDLE (selecting random devices on the multiplexer). It seems like the i2c or serial comms on the pi is not initializing correctly. For example, in IDLE when selecting a module, It brings up the incorrect module to the one that you have chosen spits out incorrect data. However, this all works fine in the terminal.
Does any one have any ideas??
Any help would be much appreciated!
from smbus import SMBus
# from itertools import cycle
import time
import serial
usbport = '/dev/ttyAMA0'
ser = serial.Serial(usbport, 9600, timeout = 2)#
line = ""
data = ""
bus = SMBus(1) # Port 1 used on REV2
print "Electronics Workshop PH Reader."
print "=========================="
global count
count = 0 #init count to 0
probevalue = ""
def inputsel(count):
bus.write_byte(0x38, 0x00)
# count = input(" Select ph unit '0 to 23'") # count now incremented during program
count = input(" Select ph unit '0 to 23'")
if (count< 16):
data_sel = count
data_sel = data_sel | 32 # or the 2 numbers together
else:
data_sel = count - 16
data_sel = data_sel | 16 # or the 2 numbers together
bus.write_byte(0x38, data_sel) # send "count"Varable out to I2c Bus
print str(data_sel)
time.sleep (1)
data_sel = 0
print "Reading Channel:" + str(count)
def write_serial(serial_data):
global ser
data = ""
line = ""
status = ""
ser.write(serial_data) # set ph unit to take one reading at a time
ser.write("\r") # set ph unit to take one reading at a time
time.sleep (1)
ser.write(serial_data) # set ph unit to take one reading at a time
ser.write("\r")
time.sleep (1)
while status != "done":
data = ser.read(1) # gets data from PH module '
if(data == "\r"): # check each bite of data to see if its a carriage return expecting "XX.XXr"
#carriage return sent diplay message and data
print "Received from sensor:" + line
status = "done"
probevalue = line
line =" "
ser.flushInput()
ser.flushOutput()
else:
# all 5 bytes of data have not been received
line = line + data # add one to the varable line
#if(data == " "):
# write_serial()
return probevalue
def main():
global serial_data
serial_data = " "
global count
probevalue = " "
count = 0
bus.write_byte(0x38, 0)
while 1:
inputsel(count) #select the input based off count variable
loop = range(0,7)
for loopcount in loop:
if ((loopcount == 0) | (loopcount == 1)): #set command to #?
serial_data = "#?\r" #set command to request id
if (loopcount == 0): #if buffer needs clearing
print "Clearing Buffer....."
else: print "Requesting ID....."
probevalue = write_serial(serial_data) #call write_serial with #? command put value into probevalue
elif (loopcount >= 2): #set r command once buffer clear and ID obtained
serial_data = "r\r" #set command to read value
if (loopcount == 2): print "Reading pH:" #output reaidng pH when loopcounter at 2
probevalue = write_serial(serial_data) #call write_serial with r command put value into probevalue
print "=========================="

Python : thread shuts down after receiving 0f byte over serial port

I am making program for communication with cash register, and while i was testing printer on it (printing numbers from 0 to 100), I noticed that every time i get this byte (0f in hex) and my thread either blocks or shuts down. My project is made of 2 programs, one is for communication with cash register and tcp, and other is just sitting on tcp port (will add DB later)
So here is the 4 threaded program:
#!/usr/bin/env python
import thread
import crcmod
import Queue
import serial
import socket
import time
#portovi
TCP_IP = '127.0.0.1'
TCP_PORT=5007
v =0
lockSerial = thread.allocate_lock()
lockTcp = thread.allocate_lock()
lockPrn = thread.allocate_lock()
serialBuff = []
tcpBuff = []
prnBuff = []
prnReady=1
stx = chr(0x02)
etx = chr(0x03)
ack = chr(0x06)
nack = chr(0x15)
prnCmd = ('PB','PD','PF','P'+chr(0xc2))
crc8 = crcmod.mkCrcFun(0x131, 0x00)
ser = serial.Serial( 0 , baudrate=19200, bytesize=8, parity='N', stopbits=2, timeout=None, xonxoff=0, rtscts=0, writeTimeout=None, dsrdtr=None)
ser.open()
ser.sendBreak()
sl = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sl.bind((TCP_IP, TCP_PORT))
sl.listen(1)
connl, addr = sl.accept()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT+1))
s.listen(1)
conn, addr = s.accept()
def toHex(s):
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0'+hv
lst.append(hv)
return reduce(lambda x,y:x+y, lst)
#hex2bit
def hex2bit(string):
novi = bin(int(string, 16))[2:]
if len(novi)<8:
pom=8-len(novi)
while pom!=0:
novi = str(0)+novi
pom=pom-1
return novi
def serialRecv():
messageSerRec = ''
global prnReady
while 1:
byte = ser.read()#shuts down here
if not toHex(byte)=='0f':#even if I change it it shuts down
if byte == ack:
print 'ACK'
elif byte == nack:
print 'NACK'
else:
if byte == stx:
messageSerRec = ''
elif byte == etx:
messageSerRecFin = messageSerRec[:-2]
chSum = int ('0x%s'%messageSerRec[-2:],0)
if chSum == crc8(messageSerRecFin):
lockSerial.acquire()
serialBuff.append(messageSerRecFin)
print "Serial Recv: ", messageSerRecFin
lockSerial.release()
ser.write(ack)
prnReady = 1
else: ser.write(nack)
else: messageSerRec = messageSerRec+byte
time.sleep(0.01)
def tcpSend():
while 1:
if serialBuff:
lockSerial.acquire()
conn.send(serialBuff[0])
print "Tcp Send: ", serialBuff[0]
serialBuff.remove(serialBuff[0])
lockSerial.release()
time.sleep(0.01)
def tcpRecv():
pom=""
while 1:
messageTcpRec = connl.recv(25)
i=0
if len(messageTcpRec)>0:
while i<len(messageTcpRec):
if not messageTcpRec[i]==';':
pom=pom+messageTcpRec[i]
else:
prnBuff.append(pom)
pom=""
i=i+1
print prnBuff
#if not messageTcpRec=="":
# print "Tcp Recv: ", messageTcpRec
# if messageTcpRec[:2] in prnCmd:
# lockPrn.acquire()
# prnBuff.append(messageTcpRec)
# lockPrn.release()
# elif tcpBuff:
# lockTcp.acquire()
# tcpBuff.append(messageTcpRec)
# lockTcp.release()
time.sleep(0.01)
def serialSend():
global prnReady
while 1:
#print "prnRdy=", prnReady
if tcpBuff:
print "tcpBuff:", tcpBuff[0]
lockTcp.acquire()
ser.write(stx+tcpBuff[0]+hex(crc8(tcpBuff[0]))[-2:].upper()+etx)
print "Serial Send: ", (tcpBuff[0])
tcpBuff.remove(tcpBuff[0])
lockTcp.release()
if prnBuff:
if prnReady == 1:
lockPrn.acquire()
ser.write(stx+prnBuff[0]+hex(crc8(prnBuff[0]))[-2:].upper()+etx)
print "Serial Send(prn): ", (prnBuff[0])
prnBuff.remove(prnBuff[0])
lockPrn.release()
prnReady = 0
time.sleep(0.01)
thread.start_new_thread(serialRecv,())
thread.start_new_thread(tcpSend,())
thread.start_new_thread(tcpRecv,())
thread.start_new_thread(serialSend,())
while 1:pass
s.close()
So thread serialRecv shuts of when it receives that byte
I've been trying to work this out for last 2-3 days and can't find solution.

Categories