I using PJSUA2 to make a python3 script for calling, my script is making the registration and calling but i'm getting "zsh: segmentation fault" I wonder if anyone can help me out, here is my code.
python
import time
import pjsua2 as pj
distAddrs = "192.168.1.202"
port = 5060
ext = "101"
passwd = "123456"
# Create my endpoint
endPoint = pj.Endpoint()
endPointConfig = pj.EpConfig()
endPoint.libCreate()
endPoint.libInit(endPointConfig)
# Create SIP transport
sipTransportConfig = pj.TransportConfig()
sipTransportConfig.port = port
endPoint.transportCreate(pj.PJSIP_TRANSPORT_UDP, sipTransportConfig)
# Setting my audio device
endPoint.audDevManager().setNullDev()
for codec in endPoint.codecEnum2():
priority = 0
if "PCMA/8000" in codec.codecId:
priority = 255
endPoint.codecSetPriority(codec.codecId, priority)
# Start the library
endPoint.libStart()
# Subclass to extend the Call and get notifications etc.
class Call(pj.Call):
def onRegState(self, prm):
print("***onRegState == " + prm.reason)
# pjsua2 registration and calling function
def pbxReg(distAddrs, ext, passwd):
accountConfig = pj.AccountConfig()
accountConfig.idUri = "sip:%s#%s" % (ext,distAddrs,)
accountConfig.regConfig.registrarUri = "sip:%s" % (distAddrs,)
credentials = pj.AuthCredInfo("digest","*",ext,0,passwd,)
accountConfig.sipConfig.authCreds.append(credentials)
# Creating the account
account = pj.Account()
account.create(accountConfig)
time.sleep(1)
if account.getInfo().regIsActive == True:
call = Call(account)
prm = pj.CallOpParam(True)
prm.opt.audioCount = 1
prm.opt.videoCount = 0
call.makeCall("sip:103#192.168.1.202", prm)
time.sleep(1)
prm = pj.CallOpParam()
call.hangup(prm)
endPoint.hangupAllCalls()
# Destroy the library
def libDestroy():
endPoint.libDestroy()
def main():
pbxReg(distAddrs, ext, passwd)
libDestroy()
main()
The first obvious thing I can see is that you are using time.sleep(1) instead of endPoint.libHandleEvents(1000) which was an issue for me.
# your code
time.sleep(1)
# possible fix
endPoint.libHandleEvents(1000)
Related
Re-implementation of Secured Lightweight Link Discovery Protocol
Kindly help debug the code below.
The helps provided in the private post have been noted. But i still have new challenges.
Thanks
#Re-implementation of SLDP
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import ether_types
from ryu.lib.packet import ipv4
from ryu.topology import switches
from ryu.lib.packet import lldp
import logging
import time
from ryu.lib import hub
LOG = logging.getLogger(__name__)
class SimpleSwitch13(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
_CONTEXTS = {
'switches': switches.Switches,
}
def __init__(self, *args, **kwargs):
super(SimpleSwitch13, self).__init__(*args, **kwargs)
self.mac_to_port = {}
self.is_active = True
#set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_handler(self, ev):
datapath = ev.msg.datapath
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
# install table-miss flow entry
#
# We specify NO BUFFER to max_len of the output action due to
# OVS bug. At this moment, if we specify a lesser number, e.g.,
# 128, OVS will send Packet-In with invalid buffer_id and
# truncated packet data. In that case, we cannot output packets
# correctly. The bug has been fixed in OVS v2.1.0.
match = parser.OFPMatch()
actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
ofproto.OFPCML_NO_BUFFER)]
self.add_flow(datapath, 0, match, actions)
def add_flow(self, datapath, priority, match, actions, buffer_id=None):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
actions)]
if buffer_id:
mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
priority=priority, match=match,
instructions=inst)
else:
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
match=match, instructions=inst)
datapath.send_msg(mod)
#set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
msg = ev.msg
datapath = msg.datapath
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
in_port = msg.match['in_port']
pkt = packet.Packet(msg.data)
eth = pkt.get_protocols(ethernet.ethernet)[0]
if eth.ethertype == ether_types.ETH_TYPE_LLDP:
# ignore lldp packet
#print("lldp packet")
return
#dst = eth.dst
dst = 'ff:ff:ff:ff:ff:ff'
src = eth.src
#print("not lldp packet")
dpid = datapath.id
self.mac_to_port.setdefault(dpid, {})
self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)
# learn a mac address to avoid FLOOD next time.
self.mac_to_port[dpid][src] = in_port
if dst in self.mac_to_port[dpid]:
out_port = self.mac_to_port[dpid][dst]
else:
out_port = ofproto.OFPP_FLOOD
actions = [parser.OFPActionOutput(out_port)]
# install a flow to avoid packet_in next time
# eth_type=0xabcd, eth_dst='ff:ff:ff:ff:ff:ff',
if out_port != ofproto.OFPP_FLOOD:
match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
self.add_flow(datapath, 1, match, actions)
self.logger.info("not Flood")
data = None
if msg.buffer_id == ofproto.OFP_NO_BUFFER:
data = msg.data
match = parser.OFPMatch(in_port=in_port, eth_type=0xabcd, eth_dst='ff:ff:ff:ff:ff:ff', eth_src=src)
self.add_flow(datapath, 1, match, actions)
self.logger.info("Flood")
out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
in_port=in_port, actions=actions, data=data)
datapath.send_msg(out)
#set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
msg = ev.msg
datapath = msg.datapath
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
in_port = msg.match['in_port']
#set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def lldp_packet_in_handler(self, ev):
if not self.link_discovery:
return
msg = ev.msg
try:
src_dpid, src_port_no = LLDPPacket.lldp_parse(msg.data)
except LLDPPacket.LLDPUnknownFormat:
# This handler can receive all the packets which can be
# not-LLDP packet. Ignore it silently
return
dst_dpid = msg.datapath.id
if msg.datapath.ofproto.OFP_VERSION == ofproto_v1_0.OFP_VERSION:
dst_port_no = msg.in_port
elif msg.datapath.ofproto.OFP_VERSION >= ofproto_v1_2.OFP_VERSION:
dst_port_no = msg.match['in_port']
else:
LOG.error('cannot accept LLDP. unsupported version. %x',
msg.datapath.ofproto.OFP_VERSION)
src = self._get_port(src_dpid, src_port_no)
print("im in here")
if not src or src.dpid == dst_dpid:
return
try:
self.ports.lldp_received(src)
except KeyError:
# There are races between EventOFPPacketIn and
# EventDPPortAdd. So packet-in event can happend before
# port add event. In that case key error can happend.
# LOG.debug('lldp_received error', exc_info=True)
pass
dst = self._get_port(dst_dpid, dst_port_no)
if not dst:
return
old_peer = self.links.get_peer(src)
# LOG.debug("Packet-In")
# LOG.debug(" src=%s", src)
# LOG.debug(" dst=%s", dst)
# LOG.debug(" old_peer=%s", old_peer)
if old_peer and old_peer != dst:
old_link = Link(src, old_peer)
del self.links[old_link]
self.send_event_to_observers(event.EventLinkDelete(old_link))
link = Link(src, dst)
if link not in self.links:
self.send_event_to_observers(event.EventLinkAdd(link))
# remove hosts if it's not attached to edge port
host_to_del = []
for host in self.hosts.values():
if not self._is_edge_port(host.port):
host_to_del.append(host.mac)
for host_mac in host_to_del:
del self.hosts[host_mac]
if not self.links.update_link(src, dst):
# reverse link is not detected yet.
# So schedule the check early because it's very likely it's up
self.ports.move_front(dst)
self.lldp_event.set()
if self.explicit_drop:
self._drop_packet(msg)
I got the protocol setup nicely. The host-switch linking was successful
I have imported all the needed modules, yet it couldnt find link_discovery
The helps provided in the private post have been noted. But i still have new challenges.
Thanks
I am currently working on a server / client chat program which works fine on terminal but in trying to migrate it into a windowed program I've come across a few errors which I have managed to solve except for this one, for whatever reason, in the GUI class running on the main thread seems to lag considerably whenever the user focuses their attention on it or whenever they try to interact with it, I've tried to use threading but I'm not sure what the problem is.
...
class GUI():
def __init__(self):
self.txtval = []
self.nochngtxtval = []
self.root = tk.Tk()
self.root.title("Chatroom")
self.root.geometry("400x200")
self.labl = tk.Label(self.root, text="", justify=tk.LEFT, anchor='nw', width=45, relief=tk.RIDGE, height=8)
self.labl.pack()
count = 1
while events["connected"] == False:
if events["FError"] == True:
quit()
self.labl["text"] = "Loading"+"."*count
count += 1
if count > 3:
count = 1
self.labl["text"] = ""
self.inputtxt = tk.Text(self.root,height=1,width=40,undo=True)
self.inputtxt.bind("<Return>", self.sendinput)
self.sendButton = tk.Button(self.root, text="Send")
self.sendButton.bind("<Button-1>", self.sendinput)
self.sendButton.pack(padx=5,pady=5,side=tk.BOTTOM)
self.inputtxt.pack(padx=5,pady=5,side=tk.BOTTOM)
uc = Thread(target=self.updatechat,daemon=True)
uc.start()
self.root.protocol("WM_DELETE_WINDOW", cleanAndClose)
self.root.mainloop()
def updatechat(self):
global events
while True:
if events["recv"] != None:
try:
current = events["recv"]
events["recv"] = None
... # shorten to reasonable length (45 characters)
self.labl['text'] = ''
self.txtval = []
self.nochngtxtval.append(new+"\n")
for i in range(len(nochngtxtval)):
self.txtval.append(nochngtxtval[i])
self.txtval.pop(len(self.txtval)-1) # probably not necessary
self.txtval.append(new+"\n") # probably not necessary
self.txtval[len(self.txtval)-1] = self.txtval[len(self.txtval)-1][:-1]
for i in range(len(self.txtval)):
self.labl['text'] = self.labl['text']+self.txtval[i]
except Exception as e:
events["Error"] = str(e)
pass
def sendinput(self, event):
global events
inp = self.inputtxt.get("1.0", "end").strip()
events["send"] = inp
self.inputtxt.delete('1.0', "end")
... # start the logger and server threads
GUI()
I'm using my custom encryption which is linked on github https://github.com/Nidhogg-Wyrmborn/BBR
my server is named server.py in the same git repo as my encryption.
EDIT:
I added a test file which is called WindowClasses.py to my git repo which has no socket interactions and works fine, however the problem seems to be introduced the moment i use socket as displayed in the Client GUI. I hope this can help to ascertain the issue.
I'm been trying to create a csv file from this code, but it fails every time, I have tried different ways to place it inside the code but nothing has work so far.
I'm new to python and to Stack overflow.
If somebody can explain what I'm doing wrong it will be helpful.
Thanks in advance for any help.
from time import sleep
import os
import sys
from bleson import get_provider, Observer, UUID16
import csv
GOVEE_BT_mac_OUI_PREFIX = "A4:C1:38"
H5075_UPDATE_UUID16 = UUID16(0xEC88)
govee_devices = {}
# ###########################################################################
FORMAT_PRECISION = ".2f"
# Decode H5075 Temperature into degrees Fahrenheit
def decode_temp_in_f(encoded_data):
return format((((encoded_data / 10000) * 1.8) + 32), FORMAT_PRECISION)
# Decode H5075 percent humidity
def decode_humidity(encoded_data):
return format(((encoded_data % 1000) / 10), FORMAT_PRECISION)
#focus here
with open('temp.csv','w',newline='') as record:
record = csv.writer(record)
record.writerow(['Device Name','Device Address','Temp','Humidity'])
def print_values(mac):
govee_device = govee_devices[mac]
print(govee_device['name'],govee_device['address'],govee_device['tempInF'],govee_device['humidity'],govee_device['battery'])
record.writerow(govee_device['name'])
# On BLE advertisement callback
def on_advertisement(advertisement):
if advertisement.address.address.startswith(GOVEE_BT_mac_OUI_PREFIX):
mac = advertisement.address.address
if mac not in govee_devices:
govee_devices[mac] = {}
if H5075_UPDATE_UUID16 in advertisement.uuid16s:
# HACK: Proper decoding is done in bleson > 0.10
name = advertisement.name.split("'")[0]
encoded_data = int(advertisement.mfg_data.hex()[6:12], 16)
battery = int(advertisement.mfg_data.hex()[12:14], 16)
govee_devices[mac]["address"] = mac
govee_devices[mac]["name"] = name
govee_devices[mac]["mfg_data"] = advertisement.mfg_data
govee_devices[mac]["data"] = encoded_data
govee_devices[mac]["tempInF"] = decode_temp_in_f(encoded_data)
govee_devices[mac]["humidity"] = decode_humidity(encoded_data)
govee_devices[mac]["battery"] = battery
print_values(mac)
if advertisement.rssi is not None and advertisement.rssi != 0:
govee_devices[mac]["rssi"] = advertisement.rssi
# ###########################################################################
adapter = get_provider().get_adapter()
observer = Observer(adapter)
observer.on_advertising_data = on_advertisement
try:
while True:
observer.start()
sleep(2)
observer.stop()
except KeyboardInterrupt:
try:
observer.stop()
sys.exit(0)
except SystemExit:
observer.stop()
os._exit(0)
Error that Im getting is:
File "/home/pi/GoveeWatcher-master/python/goveeWatcher.py", line 37, in print_values
record.writerow(govee_device['name'])
ValueError: I/O operation on closed file.
I would be tempted to put the CSV writing functionality inside of the print_values function so it opens the file, writes the data, and then closes the file on each value that is found by the observer.
For example:
#focus here
def print_values(mac):
govee_device = govee_devices[mac]
print(govee_device['name'], govee_device['tempInF'])
with open('temp.csv','a',newline='') as record:
writer = csv.DictWriter(record, fieldnames=govee_device.keys())
writer.writerow(govee_device)
Hi I Have Terrible codes in Raspberry Pi 3. I am trying to read 4 RC522 Module and i can do it. But after few minutes I got "can't open device: Too many open files" Error, and my while loop terminated.
I didnt share all the functions. I guess important part is while loop. I create instance in every loop. I guess this is big mistake. I cant add delay. I tried assign null to my object but i got still same error. My Codes are Below
Note: I have 4 SPI address, and i create instance with them.
#!/usr/bin/env python
# -*- coding: utf8 -*-
import time
import sys
import os
import RPi.GPIO as GPIO
import MFRC522
import signal
from time import gmtime, strftime
from time import sleep
import requests
#import xml.etree.ElementTree as ET
#import xmltodict, json
from lxml import objectify
from bs4 import BeautifulSoup
continue_reading = True
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
GPIO.setup(37, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
global continue_reading
print "Ctrl+C captured, ending read."
continue_reading = False
GPIO.cleanup()
kullanici = "xxxx"
sifre = "xxxx"
birim = "xxxx"
ogrKEY = " "
def end_read(signal,frame):
global continue_reading
print "Ctrl+C captured, ending read."
continue_reading = False
GPIO.cleanup()
# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)
# Create an object of the class MFRC522
#
adresler = ["/dev/spidev0.0", "/dev/spidev0.1", "/dev/spidev1.0","/dev/spidev1.1"]
# Welcome message
print "Welcome to the MFRC522 data read example"
print "Press Ctrl-C to stop."
j = 0
# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:
MIFAREReader = None
pin = 0
if j == 100:
j = 0
i = j % 4
if i == 0:
MIFAREReader = MFRC522.MFRC522(adresler[0], 16)
pin = 15
elif i == 1:
MIFAREReader = MFRC522.MFRC522(adresler[1], 18)
pin = 13
elif i == 2:
MIFAREReader = MFRC522.MFRC522(adresler[2], 33)
pin = 7
else:
MIFAREReader = MFRC522.MFRC522(adresler[3], 31)
pin = 37
# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# If a card is found
if status == MIFAREReader.MI_OK:
print "Card detected"
# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()
# If we have the UID, continue
if status == MIFAREReader.MI_OK:
# print "su okuyucudan okundu" % i
# Print UID
print "Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3])
# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)
# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 10, key, uid)
# Check if authenticated
if status == MIFAREReader.MI_OK:
MIFAREReader.MFRC522_Read(10)
ogrKEY = MIFAREReader.returnOGR()
sonuc = parser(ogrKEY)
if sonuc == True:
openTurnsTile(pin)
else:
sonuc = personelKontrol(ogrKey)
if sonuc == True:
openTurnsTile(pin)
MIFAREReader.MFRC522_StopCrypto1()
else:
print "Authentication error"
j = j + 1
When you create the MFRC522 object it actually calls spi.openSPI() but never closes it. This python library is good for single instance but now that you are dealing with multiple instance where FDs are opened, needs to be closed as well using spi.closeSPI(), else you will get the error "Too many open FDs".
To check how many open FDs are there for your PID.
I'm new to python, multithreading, queue, and locking. What I'm trying to achieve is to login to many devices all at once, check for new image, download an image, then install it on all devices, in multi-threading process, download has to be done before start installing. I tried the following concept but I have no clue how to accomplish or connect/glue them together, any help will be appreciated in advance!
from threading import Thread
import Queue
import re
from LoginCli import Device_Under_test
import sys, os, string, threading
import time
# some global vars
num_threads = 25
ips_q = Queue.Queue()
out_q = Queue.Queue()
outlock = threading.Lock()
# build IP array
ips = []
for i in range(100,200):
ips.append("10.10.10."+str(i))
user = 'root'
pword = 'password'
log = 'output.log'
def login_to_device (i, q):
"""get hosts in queue"""
while True:
# get an IP item form queue
ip = q.get()
cmd = "check for image"
#login to device:this works just fine using my loginCli script
LoginCli = Device_Under_test(str(ip), user, pword)
print_cmd= LoginCli.send_exp(cmd)
with outlock:
print print_cmd
q.task_done()
def image_download (i, q):
while True:
#get an IP item form queue
ip = q.get()
cmd = "download for image"
#NOT sure if I need to login again!
LoginCli = Device_Under_test(str(ip), user, pword)
print_cmd= LoginCli.send_exp(cmd)
search = re.search(r'image download completed 100%', LoginCli)
#if is done 100% completed then start installing the image
#Once installing is completed then reboot all devices
with outlock:
print print_cmd
q.task_done()
# Not sure if I need these functions?
def image_downoad (i, q):
def image_install (i, q):
# start the thread pool
for i in range(num_threads):
worker = Thread(target=login_to_device, args=(i, ips_q))
worker.setDaemon(True)
worker.start()
for i in range(num_threads):
worker = Thread(target=image_downoad, args=(i, ips_q))
worker.setDaemon(True)
worker.start()
# fill queue
for ip in ips:
ips_q.put(ip)
# wait until worker threads are done to exit
ips_q.join()
# print result
while True:
try:
msg = out_q.get_nowait()
except Queue.Empty:
break
print msg