Send USSD command to mobile phone connected via bluez to raspberrypi 4 - bluetooth

I just start working with ofono and when I want to send USSD command.
when I use initiate-ussd <modem> I get this error:
Traceback (most recent call last):
File "/home/pi/workspace/libs/ofono/test/./initiate-ussd", line 27, in <module>
properties = ussd.GetProperties()
File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 72, in _call_
return self._proxy_method(*args, **keywords)
File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 141, in _call_
return self._connection.call_blocking(self._named_service,
File "/usr/lib/python3/dist-packages/dbus/connection.py", line 652, in call_blocking
reply_message = self.send_message_with_reply_and_block(
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownMethod: Method "GetProperties" with signature "" on interface "org.ofono.SupplementaryServices" doesn't exist
my list-modems :
[ /hfp/org/bluez/hci0/dev_97_E7_F5_A2_E4_0B ]
Online = 1
Powered = 1
Lockdown = 0
Emergency = 0
Serial = 97:E7:F5:A2:E4:0B
Interfaces = org.ofono.VoiceCallManager org.ofono.CallVolume org.ofono.Handsfree org.ofono.NetworkRegistration
Features = net
Name = Nexus 6P
Type = hfp
[ org.ofono.VoiceCallManager ]
EmergencyNumbers = 118 110 08 911 000 112 999 119
[ org.ofono.CallVolume ]
SpeakerVolume = 50
MicrophoneVolume = 50
Muted = 0
[ org.ofono.Handsfree ]
InbandRinging = 1
EchoCancelingNoiseReduction = 1
DistractedDrivingReduction = 0
VoiceRecognition = 0
Features = three-way-calling echo-canceling-and-noise-reduction voice-recognition release-all-held create-multiparty hf-indicators
BatteryChargeLevel = 5
[ org.ofono.NetworkRegistration ]
Status = registered
Mode = auto-only
Name = SomeThing
Strength = 100
I'm able to make a phone call and receive it. but no USSD.
Got that I didn't have a org.ofono.SupplementaryServices in my Interfaces so how can I add this to my interfaces?
I'm using bluez5, ofono and i'm connecting my cell phone to raspberrypi 4.
Also I intent to send and receive SMS too. But I got the same error on org.ofono.MessageManager.
Thanks a lot

Related

why i got "rospy.ServiceException"?

i am working with ros about 3 month! I work on a robot controller.
i got error in ui about this client:
import sys
import rospy
from database_helper.srv import get_moves, get_movesRequest, get_movesResponse, get_move
def get_data(name: str):
"""This function can extract model names from DB"""
try:
rospy.init_node("get_moves_client")
except:
pass
rospy.wait_for_service('get_moves')
try:
moves = rospy.ServiceProxy('get_moves', get_moves)
except rospy.ServiceException as e:
print(31)
print(e)
return
id = 0
try:
for i in (moves(True).moves):
if i.name == name:
id = i.id
#print(id)
break
except:
print(43)
return
rospy.wait_for_service('get_move')
move = rospy.ServiceProxy('get_move', get_move)
wps = move(id).waypoints
list_of_data = []
try:
for i in range(len(wps)):
print(i)
data = {}
data['x_traj'] = wps[i].x
data['y_traj'] = wps[i].y
data['z_traj'] = wps[i].z
data['time_tarj'] = wps[i].displacement_time_to_next_waypoint
data['order_traj'] = wps[i].order
data['pitch_traj'] = wps[i].pitch
data['roll_traj'] = wps[i].roll
data['yaw_traj'] = wps[i].yaw
data['focus_camer'] = wps[i].camera_focus
data['iris_camera'] = wps[i].camera_iris
data['rail_direction'] = wps[i].rail_direction
data['rail_speed'] = wps[i].rail_speed
data['zoom_camera'] = wps[i].camera_zoom
data['rail_time'] = wps[i].rail_time
data['rail_displacement'] = wps[i].rail_displacement
list_of_data.append(data)
except rospy.ServiceException:
pass
print(list_of_data)
return list_of_data
this client can get data from DB and save with dict and save all dict in a list.
i most write "try/except" and i see 43 number! so i know my except is in for i in range(len(wps)):
the amazing point is, i can run this script and i get answer, but if call this script in my ui, after i using save waypoint and i try to load waypoint, i get ServiceException!
my "add_move.py" code:
from typing import List, Dict
import rospy
from database_helper.srv import add_move
from database_helper.msg import move, waypoint
def _add_move(name: str, wp: List[Dict]):
"""This Function can for send insert query for DB"""
rospy.init_node('add_move_client', anonymous=True)
rospy.wait_for_service('add_move')
_move = move()
_move.name = name
for i in range(len(wp)):
_waypoint = waypoint()
_waypoint.x = wp[i]['x_traj']
_waypoint.y = wp[i]['y_traj']
_waypoint.z = wp[i]['z_traj']
_waypoint.displacement_time_to_next_waypoint = wp[i]['time_tarj']
_waypoint.pitch = wp[i]['pich_traj']
_waypoint.roll = wp[i]['roul_traj']
_waypoint.yaw = wp[i]['ya_traj']
_waypoint.camera_focus = wp[i]['focus_camer']
_waypoint.camera_iris = wp[i]['iris_camera']
_waypoint.camera_zoom = wp[i]['zoom_camera']
_waypoint.rail_speed = wp[i]['speed_rail']
_waypoint.rail_displacement = wp[i]['disp_or_time_rail']
_waypoint.rail_direction = wp[i]['direction_rail']
_move.waypoints.append(_waypoint)
add = rospy.ServiceProxy('add_move', add_move)
return add(_move).id
if __name__ == "__main__":
from random import randint
data = {'x_traj': 12, 'y_traj': 12, 'z_traj': 33, 'time_tarj': 11,
'pich_traj': 13, 'roul_traj': 43, 'ya_traj': 21,
'focus_camer': 11, 'iris_camera': 55, 'zoom_camera': 32,
'disp_or_time_rail': 21, 'speed_rail': 109, 'direction_rail':44,
'joint1_slider': 12, 'joint2_slider': 666, 'joint3_slider': 567,
'joint4_slider': 32, 'joint5_slider': 79, 'joint6_spin': 100
}
wp = []
wp.append(data)
print(_add_move("t1", wp))
my error in terminal without "try/except" is:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 223, in deserialize_messages
msg_queue.append(data.deserialize(q))
File "/home/ajax/Documents/iotive/devel/lib/python3/dist-packages/database_helper/srv/_get_moves.py", line 247, in deserialize
val2 = database_helper.msg.waypoint()
File "/home/ajax/Documents/iotive/devel/lib/python3/dist-packages/database_helper/msg/_waypoint.py", line 95, in __init__
self.rail_displacement = 0
AttributeError: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_base.py", line 735, in receive_once
p.read_messages(b, msg_queue, sock)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 361, in read_messages
rospy.msg.deserialize_messages(b, msg_queue, self.recv_data_class, queue_size=self.queue_size, max_msgs=1, start=1) #rospy.msg
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 245, in deserialize_messages
raise genpy.DeserializationError("cannot deserialize: %s"%str(e))
genpy.message.DeserializationError: cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 522, in call
responses = transport.receive_once()
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_base.py", line 751, in receive_once
raise TransportException("receive_once[%s]: DeserializationError %s"%(self.name, str(e)))
rospy.exceptions.TransportException: receive_once[/get_moves]: DeserializationError cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./benchmark_new_version_4_1.py", line 730, in get_data_query
self.wp_saver = get_data(response)
File "/home/ajax/Documents/iotive/src/gui/ui/scripts/get_moves_clinet.py", line 36, in get_data
for i in (moves(True).moves):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 442, in __call__
return self.call(*args, **kwds)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 532, in call
raise ServiceException("transport error completing service call: %s"%(str(e)))
rospy.service.ServiceException: transport error completing service call: receive_once[/get_moves]: DeserializationError cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
what is my wrong?
srv/get_move:
int32 id
---
waypoint[] waypoints
srv/get_moves:
bool add_waypoints
---
move[] moves
msg/move:
int32 id
string name
waypoint[] waypoints
msg/waypoint:
int32 id
int32 order
float64 x
float64 y
float64 z
float64 roll
float64 pitch
float64 yaw
int32 camera_focus
int32 camera_iris
int32 camera_zoom
int32 rail_displacement
int32 rail_time
int32 rail_speed
bool rail_direction
int32 displacement_time_to_next_waypoint
So we need to remove service variables when we do not have anything else.
like this:
rospy.wait_for_service('get_moves')
moves = rospy.ServiceProxy('get_moves', get_moves)
id = 0
for i in (moves(True).moves):
if i.name == name:
id = i.id
#print(id)
break
rospy.wait_for_service('get_move')
move = rospy.ServiceProxy('get_move', get_move)
wps = move(id).waypoints
list_of_data = []
for i in range(len(wps)):
print(i)
data = {}
data['order_traj'] = wps[i].order
data['x_traj'] = wps[i].x
data['y_traj'] = wps[i].y
data['z_traj'] = wps[i].z
data['time_tarj'] = wps[i].displacement_time_to_next_waypoint
data['order_traj'] = wps[i].order
data['pitch_traj'] = wps[i].pitch
data['roll_traj'] = wps[i].roll
data['yaw_traj'] = wps[i].yaw
data['focus_camer'] = wps[i].camera_focus
data['iris_camera'] = wps[i].camera_iris
data['rail_direction'] = wps[i].rail_direction
data['rail_speed'] = wps[i].rail_speed
data['zoom_camera'] = wps[i].camera_zoom
data['rail_time'] = wps[i].rail_time
data['rail_displacement'] = wps[i].rail_displacement
list_of_data.append(data)
del move
del moves
print(list_of_data)
return list_of_data
I discovered this last night!

BLE communication between two Raspberry Pi 4

I am collecting pressure sensor data from 4 Arduino Nano 33 ble to a raspberry pi 4. I am able to receive the data from all the sensors. Now, I want to send this received data to another Raspberry Pi 4 using BLE communication in real-time such that the first Raspberry Pi acts as a repeater. I searched but could not find a suitable approach or solution to implement this.
The first Raspberry Pi could act as a peripheral/client sending all the received sensor data and the second raspberry pi could act as a central/server to receive all the sensor data which can be further displayed on web interfaces or stored in a database.
I tried connecting initially with one Arduino and sending its data over raspberry Pi. I have written the code for Raspberry Pi Client and Server using Bluedot library in Python.
Raspberry Pi 4 Client code
import sys
import time
from bluepy import btle
from bluedot.btcomm import BluetoothClient
from signal import pause
def data_3():
mac_adrs3 = 'f3:9a:9a:e8:54:5c'
print("Connecting..")
tp3_sense = btle.Peripheral(mac_adrs3)
print("Discovering Services..")
_=tp3_sense.services
tire3_sensing_service = tp3_sense.getServiceByUUID("2b7537ab-8899-4359-a78a-096e076a4605")
print("Discovering characteristics..")
_= tire3_sensing_service.getCharacteristics()
return tire3_sensing_service
def byte_array_to_int(value):
value = bytearray(value)
value = int.from_bytes(value, byteorder='little')
return value
def byte_array_to_char(value):
value = value.decode("utf-8")
return value
def decimal_exponent_two(value):
return value/100
def decimal_exponent_one(value):
return value/10
def pascals_to_kilopascals(value):
return value / 1000
def read_pressure3(service3):
pres3_char = service3.getCharacteristics("9c30d6b2-e3d3-4eae-8641-425a36d550ec")[0]
pres3 = pres3_char.read()
pres3 = byte_array_to_int(pres3)
#pres3 = decimal_exponent_one(pres3)
#pres3 = pascals_to_kilopascals(pres3)
print(f"Barometric pressure 3 : {round(pres3,2)} kPa")
return pres3
def read_temperature3(service3):
temp3_char = service3.getCharacteristics("e986145c-ead6-41a7-9718-d2b0b4834a11")[0]
temp3 = temp3_char.read()
temp3 = byte_array_to_int(temp3)
#temp3 = decimal_exponent_two(temp3)
print(f"temperature 3 : {round(temp3,2)} C")
return temp3
def loop():
c = data_3()
while True:
time.sleep(1.0)
print("\n")
read_temperature3(c)
read_pressure3(c)
t3 = read_temperature3(c)
p3 = read_pressure3(c)
r = BluetoothClient("DC:A6:32:4C:9D:ED", data_received_callback=None, port=2)
r.send(f"temp 3 : {t3} ")
r.send("\n")
r.send(f"pressure 3 : {p3} ")
#pause()
#time.sleep(1.0)
def main():
loop()
if __name__ == "__main__":
main()
Raspberry Pi Server code
from bluedot.btcomm import BluetoothServer
from signal import pause
def data_received(data):
print(data)
s.send(data)
s = BluetoothServer(data_received)
pause()
I am able to receive two readings and after that the client disconnects with the below error.
pi#raspberrypi:~/Desktop/rpible $ python3 onearduino_senddata.py
Connecting..
Discovering Services..
Discovering characteristics..
temperature 3 : 0 C
Barometric pressure 3 : 100 kPa
temperature 3 : 0 C
Barometric pressure 3 : 100 kPa
Traceback (most recent call last):
File "onearduino_senddata.py", line 83, in <module>
main()
File "onearduino_senddata.py", line 80, in main
loop()
File "onearduino_senddata.py", line 70, in loop
r = BluetoothClient("DC:A6:32:4C:9D:ED", data_received_callback=None, port=2)
File "/usr/local/lib/python3.7/dist-packages/bluedot/btcomm.py", line 567, in __init__
self.connect()
File "/usr/local/lib/python3.7/dist-packages/bluedot/btcomm.py", line 660, in connect
self._client_sock.connect((server_mac, self._port))
OSError: [Errno 16] Device or resource busy
please help to solve this issue.
Found the solution.
Create the client once outside the while loop and then the data transfer happens.
updated loop function.
def loop():
c = data_3()
//create the client connection here
r = BluetoothClient("DC:A6:32:4C:9D:ED", data_received_callback=None)
while True:
time.sleep(1.0)
print("\n")
t3 = read_temperature3(c)
p3 = read_pressure3(c)
r.send(f"temp 3 : {t3} ")
r.send("\n")
r.send(f"pressure 3 : {p3} ")

TypeError: an integer is required when trying to sniff and spoof a packet against TELNET (EDITED)

Trying to sniff and spoof packet while using MITM attack against telnet/netcat, but I get these messages when I send the spoofed packet.
The telnet attack code:
#!/usr/bin/python3
from scapy.all import *
def spoof_pkt(pkt):
data = pkt[TCP].payload.load
print("*** %s, length=: %d" % (data, len(data)))
newpkt = IP(pkt[IP])
del(newpkt.chksum)
del(newpkt[TCP].payload)
del(newpkt[TCP].chksum)
data_list = list(data)
for i in range(0, len(data_list)):
**(LINE 19)** -> if chr(data_list[i]).isalpha():
data_list[i] = ord('A')
newdata = bytes(data_list)
send(newpkt/newdata)
pkt = sniff(filter="tcp and host 10.0.2.7", prn=spoof_pkt)
Error message(Edited! new error)
> Original Packet.........
('Source IP: ', '10.0.2.5')
('Destination IP: ', '10.0.2.7')
('Message: ', 'a')
Message Length: 1
Traceback (most recent call last):
File "./telnet", line 27, in <module>
pkt = sniff(filter='tcp port 23', prn=spoof_pkt)
File "/home/seed/.local/lib/python2.7/site-packages/scapy/sendrecv.py", line 780,
in sniff r = prn(p)
File "./telnet", line 19, in spoof_pkt
if chr(data_list[i]).isalpha():
TypeError: an integer is required
You can wrap your IP packet with bytes().
Like: newpkt = IP(bytes(pkt[IP]))
I also feel you are getting the TypeError: an integer is required error because of bad identation. It should be:
for i in range(0, len(data_list)):
if chr(data_list[i]).isalpha():
data_list[i] = ord('A')
newdata = bytes(data_list)
send(newpkt/newdata)

Address generation for bitcoin with Python error

I am trying to understand bitcoin with python and trying to create my own vanity address generator.
Below is a snippet of the while loop. I keep getting an error after the loop runs about 10 times. Any help would be highly appreciated. i have searched the forum and have found answers.
But they don't work. IE. i changed the
intermed = hashlib.sha256(string).digest()
a few times modifying the code but still the same result.
Traceback (most recent call last):
File "main.py", line 38, in <module>
compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key)
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/bitcoin/mai
n.py", line 452, in pubkey_to_address
return bin_to_b58check(bin_hash160(pubkey), magicbyte) File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/bitcoin/mai
n.py", line 334, in bin_hash160
intermed = hashlib.sha256(string).digest()
TypeError: Unicode-objects must be encoded before hashing
while True:
pk = binascii.hexlify(os.urandom(32)).decode('utf-8').upper()
privkey = f"{pk:0>64}"
pub = privtopub(privkey) # Get pub addr from priv key
addr = pubtoaddr(pub) # Get the 1Btc... address
decoded_private_key = bitcoin.decode_privkey(privkey, 'hex')
wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
# Add suffix '01' to indicate a compressed private Key
compressed_private_key = privkey + '01'
# generate a WIF format from the compressed private key (WIF-compressed)
wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
# Multiply de EC generator G with the priveate key to get a public key point
pubkey = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
# Encode as hex, prefix 04
hex_encoded_public_key = bitcoin.encode_pubkey(pubkey, 'hex')
# Compress public key, adjust prefix depending on whether y is even or odd
(public_key_x, public_key_y) = pubkey
if public_key_y % 2 == 0:
compressed_prefix = '02'
else:
compressed_prefix = '03'
hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16)
print ('Compressed Public Key: ' + hex_compressed_public_key)
# Generate compressedd bitcoin address from compressed public key
compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key)
print ("private key: " + privkey )
print ("uncompressed address: "+ addr )
print ('Compressed address: ' + bitcoin.pubkey_to_address(hex_compressed_public_key))
C_address = bitcoin.pubkey_to_address(hex_compressed_public_key)
U_address = addr
You have to encode your hex_compressed_public_key to generate the address.
compressed_address_base58check = bitcoin.pubkey_to_address(hex_compressed_public_key.encode('utf-8'))

python3 mapping the unique value between two files and merge the unique lines from both files

I'm figuring out the unique values between two files and wants to megre the lines from both files into one line if the unique values exists into both files.
More explicitely, i'm looking for MAC ADDRESS that's column three in the file1 making that a key and wants to match it over file2 and if that matches then merge both the file's matches into one line.
file1
192.168.100.1 0 001c.0718.1ed6 Vlan100, Port-Channel230
192.168.100.2 0 fa16.3e88.245d Vlan100, Port-Channel230
192.168.100.3 0 001c.0718.1f52 Vlan100, Port-Channel230
192.168.100.4 0 001c.0724.tb6a Vlan100, Port-Channel51
192.168.100.5 0 01c.0718.1t9c Vlan100, Port-Channel230
192.168.100.6 0 fa16.3ed8.dd6c Vlan100, Port-Channel27
192.168.100.7 0 fa16.3e22.20c3 Vlan100, Port-Channel230
192.168.100.8 0 fa16.3ecd.e1db Vlan100, Port-Channel27
192.168.100.9 0 001c.0718.9c8f Vlan100, Port-Channel230
file2
4 001c.0724.tb6a DYNAMIC Po17 1 13 days, 22:08:51 ago
4 001c.0718.1f52 DYNAMIC Po15 1 12 days, 5:07:20 ago
4 001c.0718.1ed6 DYNAMIC Po11 1 12 days, 5:05:44 ago
4 001c.0718.1t9c DYNAMIC Po9 1 12 days, 5:07:16 ago
4 001c.0718.9c8f STATIC Po9 1 12 days, 5:07:16 ago
Code : Below is the code which i tried based on the pattern and fit from the examples i found from googles, but it throws the error while executing it.
!#/usr/bin/python3
# port_details.py
mapping_dict = {}
INPUT_FILE_1 = 'file1'
INPUT_FILE_2 = 'file2'
with open(INPUT_FILE_1) as file1:
while True:
line = file1.readline()
print(line)
if not line:
break
#_, mac, _, port = line.strip()
ip_addr, _, mac, _, status = line.split()
mapping_dict[mac.lower()] = status
with open(INPUT_FILE_2) as file2:
while True:
line = file2.readline()
if not line:
break
#ip_addr, _, mac, _ = line.strip()
_, value_id, _, port = line.split()
status = mapping_dict.get(mac, '')
print(ip_addr, mac, port, status)
Error While running, i tried diffrent values for the error but didn't get it running still looking around, any hint or suggestion will be much appreciated.
Traceback (most recent call last):
File "./srdjan1.py", line 13, in <module>
ip_addr, _, mac, _, status = line.split()
ValueError: not enough values to unpack (expected 5, got 4)
Desired Value Would Be:
192.168.100.1 001c.0718.1ed6 Po11 Vlan100 Port-Channel230
I got the solution, using dictionary to hold the values along with re for whitespaces.
import re
INPUT_FILE_1 = 'file1.txt'
INPUT_FILE_2 = 'file2.txt'
dict1 = {}
dict2 = {}
def fl2():
with open(INPUT_FILE_2) as file2:
while True:
line = file2.readline()
if not line:
break
data1 = re.split("\s+",line)
dict1[data1[2]] = data1[4]
file2.close()
return dict1
with open(INPUT_FILE_1) as file1:
dict2 = fl2()
while True:
line = file1.readline()
if not line:
break
data = re.split("\s+",line)
if data[2] in dict2:
print(data[0],data[2],dict2[data[2]])
result as expected:
./port_details.py
192.168.1.1 001001c Good

Resources