I am trying to send data continuously from raspberry pi to a windows pc using MQTT,
I am trying to send 5 data to mosquitto, but the mosquitto seems to get only one value
coding in raspberry pi
import paho.mqtt.client as mqtt
client=mqtt.Client()
client.connect("192.168.0.104",1883,60)
for i in range(0,5):
data={"protocol":"mqtt"}
client.publish("/test",str(data))
coding at the broker to receive data is
import paho.mqtt.client as mqtt
print("attempting to connect...")
def on_connect(client, userdata, flags, rc):
if(rc==0):
print("connection successful broker linked")
elif(rc==1):
print("connection refused - incorrect protocol version")
elif(rc==2):
print("connection refused - invalid client identifier")
elif(rc==3):
print("connection refused- server unavailable")
elif(rc==4):
print("connection refused- bad username or password")
elif(rc==5):
print("connection refused- not authorised")
else:
print("currently unused")
client.subscribe("s/test")
def on_message(client, userdata, msg):
data=eval(msg.payload)
print(data)
client = mqtt.Client()
client.connect("localhost",1883,60)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
Have you thought about following the answer I posted here?
https://github.com/eclipse/mosquitto/issues/972
You need to make sure the network loop runs for the publishing client as well a the subscriber. The network loop actually handles sending the messages.
The following is the simplest modification to your code.
import paho.mqtt.client as mqtt
client=mqtt.Client()
client.connect("192.168.0.104",1883,60)
for i in range(0,5):
data={"protocol":"mqtt"}
client.publish("/test",str(data))
client.loop()
Related
I'm trying to send command to my Flir camera TAU2 using USB and normally i should receive a respond from it, so what i'm doing first is that i'm configuring my serial port
and then i'm sending my command via the serial port:
and then listening to the serial for a respond :
this is a part of my code:
def __init__(self):
self.serCam = serial.Serial(port='/dev/ttyUSB0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=1,
xonxoff=False
)
def close_connection(self):
if self.serCam.isOpen():
self.serCam.close()
def serial_Read(self):
while self.serCam.inWaiting():
try:
self.state=serCam.readline()
return state
print state
except:
pass
def control(self):
self.len= self.serCam.write(serial.to_bytes([0x6E,0x00,0x00,0x0B,
0x00,0x00,0x2F,0x4A,0x00,
0x00,0x00]))
print ('commande envoye' )
return len
i don't receive anything from my camera, do you have any idea please from where it can be ?
I have a siddhi cep application running on Android. Now I want to send events from event simulator from stream processing editor to android app via a socket connection. Till now I have been successful in making android server socket which listens to python client simulator made by me. But to ease the process, is it possible that I can use event simulator to send events to android siddhi app?
I was wondering if I can change some configurations such that event simulator sends events to android socket, so I looked at setting in deployment.yaml file
but the sending configurations are defined for HTTP
senderConfigurations:
-
id: "http-sender"
# Configuration used for the databridge communication
databridge.config:
# No of worker threads to consume events
# THIS IS A MANDATORY FIELD
workerThreads: 10
# Maximum amount of messages that can be queued internally in MB
# THIS IS A MANDATORY FIELD
maxEventBufferCapacity: 10000000
# Queue size; the maximum number of events that can be stored in the queue
# THIS IS A MANDATORY FIELD
eventBufferSize: 2000
# Keystore file path
# THIS IS A MANDATORY FIELD
keyStoreLocation : ${sys:carbon.home}/resources/security/wso2carbon.jks
# Keystore password
# THIS IS A MANDATORY FIELD
keyStorePassword : wso2carbon
# Session Timeout value in mins
# THIS IS A MANDATORY FIELD
clientTimeoutMin: 30
# Data receiver configurations
# THIS IS A MANDATO
Thanks in advance. If you need some more details please let me know
Edit 1
I actually found a way around to do it but it's having some issues. So basically I redirected output sink of event generator to port such that sink has all the data streams. The code for Stream Processor Studio editor is
#App:name("PatternMatching")
#App:description('Identify event patterns based on the order of event arrival')
define stream RoomTemperatureStream(roomNo string, temp double);
#sink(type="tcp", url='tcp://localhost:5001/abc', sync='false', tcp.no.delay='true', keep.alive='true', worker.threads="10", #map(type='text'))
define stream RoomTemperatureAlertStream(roomNo string, initialTemp double, finalTemp double);
--Capture a pattern where the temperature of a room increases by 5 degrees within 2 minutes
#info(name='query1')
from RoomTemperatureStream
select e1.roomNo, e1.temp as initialTemp, e2.temp as finalTemp
insert into RoomTemperatureAlertStream;
it sends the streams as text to python server, which needs to be started first, code of which is
#!/usr/bin/env python
# Author : Amarjit Singh
import pickle
import socket
import pandas
from pandas import json
if __name__ == "__main__":
# ------------------ create a socket object-----------------------#
try:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
serversocket.close()
print("socket creation failed with error %s" % (err))
except KeyboardInterrupt:
serversocket.close()
print("KeyboardInterrupt - but server socket was closed ")
host = "127.0.0.1"
Server_port = 5001
# ------------------ binding to the port -----------------------#
try:
serversocket.bind((host, Server_port))
serversocket.listen(50) # queue up to 5 requests
print("\n Server has started and waiting for connection request ..... ")
# bind to the port
while True: # extra while is created so that server runs even if there is no data
running = True
clientsocket, addr = serversocket.accept() # accept a connection from client
print("Got a connection from Server%s" % str(addr)) # show connection success message
while running:
receivedData = clientsocket.recv(2048)
# json = receivedData
if receivedData:
print(receivedData)
print(receivedData[0])
print(receivedData[1])
print(receivedData[2])
# roomNo = str(receivedData[0])
# temp = int(client_tuple[1]) # from unicode to int
#
# print(" roomNo = %d: UUID = %s temp = %d" % (roomNo, temp))
except socket.error as err:
serversocket.close()
print("socket creation failed with error %s" % (err))
except KeyboardInterrupt:
serversocket.close()
print("KeyboardInterrupt - but server socket was closed ")
Initially, I was sending json data from simulator, but pickle.loads and json.loads did not work. but the problem with text is that data is displayed as
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"X0ZYp",\ninitialTemp:15.97,\nfinalTemp:17.22'
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"2X951",\ninitialTemp:13.42,\nfinalTemp:10.76'
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"PUaJA",\ninitialTemp:15.46,\nfinalTemp:16.26'
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"pnz0i",\ninitialTemp:10.42,\nfinalTemp:15.82'
how to remove this extra data?
Siddhi has a WebSocket connector[1] and it's still WIP. Using this dependency you will be able to add a WebSocket sink to your app and send events from that.
Unfortunately, you cannot directly send events from Stream Processor[2] Studio/Editor but if you have an app running in Stream Processor Editor and if it has a WebSocket sink then you can send events to App's sink stream from the Simulator which will intern send that message via WebSocket to the Siddhi app in android.
You can only simulate apps running inside the editor via the Event Simulator or simulate apps deployed in Stream Processor worker nodes via Event Simulator API.
[1]https://github.com/wso2-extensions/siddhi-io-websocket
[2]https://wso2.com/analytics
As you can see in images below i cannot reciveve anything from client and server keeps waiting! I have tried it without firewall and no result.. :(
cmd info
Client
import socket
sock1 = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock1.sendto("HOLA",('192.168.0.159',25585))
sock1.close()
del sock1
Server
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('0.0.0.0',25585))
while True:
data , c = sock.recvfrom(1024);
print data
sock.close()
del sock
Your client and your server are not connected. Try this:
client:
import socket
sock1 = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock1.connect(('192.168.0.159',25585))
sock1.sendto("HOLA",('192.168.0.159',25585))
sock1.close()
del sock1
Your server code is good
Otherwise UDP sockets are mostly known for packets dropping
I'm trying to connect to sftp server with pysftp library. Here is my code:
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection("sftp://host", "login", "password", cnopts=cnopts) as sftp:
sftp.listdir()
It gives me exception:
pysftp.exceptions.ConnectionException: ('host', port)
But I have no clue what this exception means and what the problem is.
You don't have much explanation because this library has bugs. See the source code on BitBucket.
The ConnectionException class is not well implemented:
class ConnectionException(Exception):
"""Exception raised for connection problems
Attributes:
message -- explanation of the error
"""
def __init__(self, host, port):
# Call the base class constructor with the parameters it needs
Exception.__init__(self, host, port)
self.message = 'Could not connect to host:port. %s:%s'
As you can see, the format 'Could not connect to host:port. %s:%s' is not filled with the host and port values.
However, the name of the exception is clear: you have a connection error.
The details of the error are, unfortunately, lost:
def _start_transport(self, host, port):
'''start the transport and set the ciphers if specified.'''
try:
self._transport = paramiko.Transport((host, port))
# Set security ciphers if set
if self._cnopts.ciphers is not None:
ciphers = self._cnopts.ciphers
self._transport.get_security_options().ciphers = ciphers
except (AttributeError, socket.gaierror):
# couldn't connect
raise ConnectionException(host, port)
You can try to get the last error (not sure):
import sys
sys.exc_info()
note: I suggest you to use another library (for instance Paramiko).
I am trying to send mail using python via my own setup mail server
import smtplib
SERVER='myserverdomain.com'
server = smtplib.SMTP(SERVER,587)
server.starttls()
server.login(USER,PASS)
server.sendmail(FROM, TO, message)
server.quit()
But when I run the above code after line 3 it is not executing.Kind of like goes into an infinite loop.Why could this be
I am able to ping my server successfully.
import smtplib
SERVER='myserverdomain.com'
server = smtplib.SMTP_SSL(SERVER,587)
server.login(USER,PASS)
server.sendmail(FROM, TO, message)
server.quit()
This answer worked