How to make these websockets work asynchronously? - python

I do not know much about asynchrony, I tried to turn for loops into async for, but now only
the first element of the generator is working, the rest are ignored. What is wrong with
this code?
async def get_requests(self, data, request_type):
for x in data:
r = [
'subscribe_on_model',
{
'collection': None,
'id': None,
'recursive': ''
}
]
r[1]['collection'] = request_type
r[1]['id'] = x
yield r
async def get_results(self):
async with BaseWebsocket(self.uri) as ws:
await ws.receive()
sport_keys = list(self.sports.keys())
sport_values = list(self.sports.values())
bundle_requests = self.get_requests(sport_values, 'LineSport')
async for bundle_request in bundle_requests:
results = []
sport_name = sport_keys[sport_values.index(bundle_request[1]['id'])]
b_request = [bundle_request]
await ws.send(b_request)
b_response = await ws.receive()
bundle_ids = b_response[0][1].get('lineCountryIds')
if bundle_ids:
championship_requests = self.get_requests(bundle_ids, 'LineCountry')
async for championship_request in championship_requests:
c_request = [championship_request]
await ws.send(c_request)
c_response = await ws.receive()
championship_ids = c_response[0][1].get('lineChampionshipIds')
if championship_ids:
event_requests = self.get_requests(championship_ids, 'LineChampionship')

Related

AttributeError: 'InputDriver' object has no attribute '_signals'

I'm getting error in this line:
line 21: dindrv = InputDriver(dut, 'din_value', dut.CLK)
self is already defined in:
class InputDriver(BusDriver):
signals = ['rdy', 'en', 'data']
def __init__(self,dut,name,clk):
BusDriver.__init__(self,dut,name,clk) --->line 35
self.bus.en.value = 0
self.clk = clk
The error is:
Traceback (most recent call last):
File "/home/trisha77/interfaces-trisha2915/tests/ifc_test.py", line
21, in ifc_test
dindrv = InputDriver(dut, 'din_value', dut.CLK)
File "/home/trisha77/interfaces-trisha2915/tests/ifc_test.py", line
35, in __init__
BusDriver.__init__(self,dut,name,clk)
File
"/home/trisha77/.local/lib/python3.10/site-packages/cocotb_busdrivers/__init__.py",
line 236, in__init__
self.entity, name, self._signals,
optional_signals=self._optional_signals,
AttributeError: 'InputDriver' object has no attribute '_signals'
I tried giving dindrv = InputDriver(self, dut, 'din_value', dut.CLK)
But in this case, it is showing the error as:
NameError: name 'self' is not defined
The whole code:
import cocotb
from cocotb.triggers import Timer, RisingEdge, ReadOnly,NextTimeStep
from cocotb_bus.drivers import BusDriver
def sb_fn(actual_value):
global expected_value
assert actual_value == expected_value.pop(0), "Scoreboard Matching Failed"
#cocotb.test() async def ifc_test(dut):
global exp_dout
din_value = (4, 6, 7, 5)
exp_dout = (22)
dut.RST_N.value = 1
await Timer(1,'ns')
dut.RST_N.value = 0
await RisingEdge(dut.CLK)
await RisingEdge(dut.CLK)
dut.RST_N.value = 1
self.dindrv = InputDriver(self, dut, 'din_value', dut.CLK)
OutputDriver(dut, 'dout_value', dut.CLK, sb_fn)
for i in range(4):
dindrv.append(din[i])
while len(exp_dout)>0:
await Timer(2,'ns')
class InputDriver(BusDriver):
signals = ['din_rdy', 'din_en', 'din_value']
def __init__(self,dut,name,clk):
BusDriver.__init__(self,dut,name,clk)
self.bus.en.value = 0
self.clk = clk async def driver_send(self,value,sync=True):
if self.bus.rdy.value != 1:
await RisingEdge(self.bus.rdy)
self.bus.en.value = 1
self.bus.data.value = value
await ReadOnly()
await RisingEdge(self.clk)
self.bus.en.value = 1
await NextTimeStep()
class OutputDriver(BusDriver):
signals = ['rdy', 'en', 'data']
def __init__(self,dut,name,clk):
BusDriver.__init__(self,dut,dut.v,clk, sb_callback)
self.bus.en.value = 0
self.clk = clk
self.callback = sb_callback
self.append(0)
async def driver_send(self,value,sync=True):
while True:
if self.bus.rdy.value != 1:
await RisingEdge(self.bus.rdy)
self.bus.en.value = 1
await ReadOnly()
self.callback(self.bus.data.value)
await RisingEdge(self.clk)
self.bus.en.value = 0
await NextTimeStep()

Flet telethon login page is not working (async)

I am programming Telegram Login page with Flet Gui and Telethon module. The problem I am facing is the code is not sending verification code to entered phone number nor showing any error it just stops at await client.send_code_request(phone_number). I expect the code to send code to specified number
# you can get telegram development credentials in telegram API Development Tools
api_id = ""
api_hash = ""
client = TelegramClient(StringSession(), api_id, api_hash)
def main(page: Page):
page.title = "Tel"
def startup_async():
new_event_loop().run_until_complete(startup())
def get_verif_async(phone_num):
print('ciao')
new_event_loop().run_until_complete(get_verification_code(phone_num))
def set_verif_async(phone_number, code_num):
print('Line 25 \n phone: ' + phone_number + " code: " + code_num)
new_event_loop().run_until_complete(set_verification_code(phone_number, code_num))
async def get_verification_code(phone_number):
print("29 " + phone_number)
if phone_number and re.match(r"^\+\d+$", phone_number):
print("31")
if not await client.is_user_authorized():
await client.send_code_request(phone_number)
page.go("/code_screen")
else:
print(36)
page.add(ft.Text(value='error'))
#view.update()
async def set_verification_code(phone_number, code_number):
print("42")
await client.sign_in(phone_number, code_number)
page.go("/homepage")
async def startup():
print('startup')
await client.connect()
if not await client.is_user_authorized():
page.route = "/login_screen"
else:
page.route = "/homepage"
def route_change(e):
page.views.clear()
if page.route == "/login_screen":
global phone_num_field
phone_num_field = ft.TextField(hint_text="Your phone number", expand=True)
page.views.append(
View(
"/login_screen",
[
AppBar(title=Text("Login"), bgcolor=colors.SURFACE_VARIANT),
phone_num_field,
#ElevatedButton(text='Get code', on_click= get_verif_async(phone_num_field.value)),
ElevatedButton(text='Get code', on_click=lambda x: get_verif_async(phone_num_field.value))
],
)
)
if page.route == "/code_screen":
code_field = ft.TextField(hint_text="code", expand=True)
page.views.append(
View(
"/code_screen",
[
AppBar(title=Text("Code"), bgcolor=colors.SURFACE_VARIANT),
code_field,
phone_num_field,
#ElevatedButton(text='Get code', on_click= get_verif_async(phone_num_field.value)),
ElevatedButton(text='Enter code', on_click=lambda x: set_verif_async(phone_num_field.value, code_field.value)),
ElevatedButton(text='Back', on_click=lambda x: page.go("/login_screen"))
],
)
)
if page.route == "/homepage":
page.views.append(
View(
"/homepage",
[
AppBar(title=Text("homepage"), bgcolor=colors.SURFACE_VARIANT),
],
)
)
page.update()
def view_pop(e):
page.views.pop()
top_view = page.views[-1]
page.go(top_view.route)
# async script startup
startup_async()
page.on_route_change = route_change
page.on_view_pop = view_pop
page.go(page.route)
ft.app(target=main)

OCPP 1.6 Remote Start Transaction

This is our CentralSystem.py
We have a LIVE charger configured to connect to our websocket
Ex - ws://HostName:Port/Charger Serial Number
As soon as the Charger is connected to our central system, it automatically sends us the following:
Charge point /D5200372001000010101 connected
INFO:ocpp:D5200372001000010101: receive message [2,"530","Heartbeat",{}]
Heartbeat
INFO:ocpp:D5200372001000010101: send [3,"530",{"currentTime":"2022-06-10T10:43:26Z"}]
INFO:ocpp:D5200372001000010101: receive message [2,"531","Heartbeat",{}]
Heartbeat
Issue 1 - We receive the heartbeat every 2mins but do not see anything for BootNotification and Status Notification when no vehicle is connected.
However, when the vehicle is connected, we do see a Status Notification and Heartbeats.
Issue 2 - Now, we have a mobile app that is built using Flutter which should allow us to enable "Remote Start Transaction". What is the best way to achieve this? Should we connect to the same websocket endpoint and call RemoteStartTransaction.
import asyncio
import logging
from asyncio import constants
import websockets
from datetime import datetime, timezone
from ocpp.routing import on
from ocpp.v16 import ChargePoint as cp
from ocpp.v16.enums import Action, RegistrationStatus, RemoteStartStopStatus
import ocpp.v16.enums as enums
from ocpp.v16 import call_result, call
import requests
logging.basicConfig(level=logging.INFO)
class ChargePoint(cp):
chargingProfile = {}
#on(Action.RemoteStartTransaction)
async def on_remote_start(self, id_tag, connector_id):
print("remotely starting")
return await self.remote_start_transaction()
#on(Action.BootNotification)
def on_boot_notification(self, charge_point_vendor, charge_point_model, **kwargs):
print("Boot Notification")
return call_result.BootNotificationPayload(
# current_time=datetime.utcnow().isoformat() + 'Z',
current_time=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') + "Z",
interval=100,
status=RegistrationStatus.accepted
)
#on(Action.StatusNotification)
def on_status_notification(self, connector_id, error_code, status, **kwargs):
print("Status Notification")
return call_result.StatusNotificationPayload()
#on(Action.Heartbeat)
def on_heartbeat(self):
print("Heartbeat")
return call_result.HeartbeatPayload(
current_time=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') + "Z"
)
#on(Action.Authorize)
def on_authorize(self, id_tag):
print("Authorize")
query = {'access_token': 'masterKey'}
response = requests.get('http://ec2-13-233-102-233.ap-south-1.compute.amazonaws.com:3000/chargersOnboarding/',
params=query)
data = response.json()
isFound = "false"
status = ""
for item in data['rows']:
if item['RFID'] == id_tag:
isFound = "true"
if item['status'] == 0:
status = "Accepted"
else:
status = "Expired"
break
else:
continue
if isFound == "true":
print("Authorized")
return call_result.AuthorizePayload(
id_tag_info={
# "expiryDate": "2022-02-04T13:00:00.21Z",
"expiryDate": "2023-05-19T13:00:00.21Z",
"parentIdTag": id_tag,
"status": status
},
)
else:
print("Not Authorized")
return call_result.AuthorizePayload(
id_tag_info={
"expiryDate": "",
"parentIdTag": id_tag,
"status": "Invalid"
},
)
#on(Action.StartTransaction)
def on_start_transaction(self, connector_id, id_tag, meter_start, timestamp, **kwargs):
print("START TRANSACTION COMING FROM CHARGER")
query = {'access_token': 'masterKey'}
response = requests.get('http://ec2-13-233-102-233.ap-south-1.compute.amazonaws.com:3000/chargersOnboarding/',
params=query)
data = response.json()
isFound = "false"
status = ""
for item in data['rows']:
if item['RFID'] == id_tag:
isFound = "true"
if item['status'] == 0:
status = "Accepted"
else:
status = "Expired"
break
else:
continue
if isFound == "true":
return call_result.StartTransactionPayload(
id_tag_info={
# "expiryDate": "2022-02-04T13:00:00.21Z",
"expiryDate": "2023-05-19T13:00:00.21Z",
"parentIdTag": id_tag,
"status": status
},
transaction_id=int(1)
)
else:
print("Not Authorized")
return call_result.StartTransactionPayload(
id_tag_info={
"expiryDate": "",
"parentIdTag": id_tag,
"status": "Invalid"
},
transaction_id=int(1)
)
#on(Action.StopTransaction)
def on_stop_transaction(self, transaction_id, timestamp, meter_stop, id_tag, **kwargs):
query = {'access_token': 'masterKey'}
response = requests.get('http://ec2-13-233-102-233.ap-south-1.compute.amazonaws.com:3000/chargersOnboarding/',
params=query)
data = response.json()
isFound = "false"
status = ""
for item in data['rows']:
if item['RFID'] == id_tag:
isFound = "true"
if item['status'] == 0:
status = "Accepted"
else:
status = "Expired"
break
else:
continue
if isFound == "true":
return call_result.StopTransactionPayload(
id_tag_info={
# "expiryDate": "2022-02-04T13:00:00.21Z",
"expiryDate": "2023-05-19T13:00:00.21Z",
"parentIdTag": id_tag,
"status": status
},
# transaction_id=int(1)
)
else:
print("Not Authorized")
return call_result.StopTransactionPayload(
id_tag_info={
"expiryDate": "",
"parentIdTag": id_tag,
"status": "Invalid"
},
transaction_id=int(1)
)
#on(Action.MeterValues)
def on_meter_value(self, **kwargs):
return call_result.MeterValuesPayload()
#on(Action.DataTransfer)
def on_data_transfer(self, vendor_id, message_id, data):
return call_result.DataTransferPayload(
status='Accepted'
)
#on(Action.ChangeAvailability)
def on_change_availabilty(self, connector_id, type):
return call_result.ChangeAvailabilityPayload(
status='Accepted'
)
async def send_limitation(self, limit):
response = await self.call(call.SetChargingProfilePayload(
connector_id=0,
cs_charging_profiles={
'chargingProfileId': 1,
'stackLevel': 0,
'chargingProfilePurpose': enums.ChargingProfilePurposeType.chargepointmaxprofile,
'chargingProfileKind': enums.ChargingProfileKindType.absolute,
'chargingSchedule': {
'startSchedule': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') + "Z",
'chargingRateUnit': enums.ChargingRateUnitType.amps,
'chargingSchedulePeriod': [{
'startPeriod': 0,
'limit': limit
}]
}
}
))
print("SEND Limitation")
print(response)
async def remote_start_transaction(self):
obj = {
'chargingProfileId': 1,
'stackLevel': 0,
'chargingProfilePurpose': enums.ChargingProfilePurposeType.chargepointmaxprofile,
'chargingProfileKind': enums.ChargingProfileKindType.absolute,
'chargingSchedule': {
'startSchedule': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') + "Z",
'chargingRateUnit': enums.ChargingRateUnitType.amps,
'chargingSchedulePeriod': [{
'startPeriod': 0,
'limit': 8.0
}]
},
}
print("REMOTE START!!!")
request = call.RemoteStartTransactionPayload(
id_tag='5C1DEA5A',
charging_profile=obj,
connector_id=1
)
response = await self.call(request)
print(response)
if response.status == RemoteStartStopStatus.accepted:
print("Transaction Started!!!")
else:
print("Transaction Failed to Start!!!")
print(response.status)
# websockets.send("Transaction Started!!!")
async def remote_stop_transaction(self):
print("REMOTE STOP!!!")
request = call.RemoteStopTransactionPayload(
transaction_id=1
)
response = await self.call(request)
if response.status == RemoteStartStopStatus.accepted:
print("Stopping transaction")
# websockets.send("Transaction Stopped!!!")
async def on_connect(websocket, path):
charge_point_id = path.strip('/')
cp = ChargePoint(charge_point_id, websocket)
try:
print(f'Charge point {path} connected')
await asyncio.gather(cp.start())
except websockets.exceptions.ConnectionClosed:
print(f"Charge Point {path} disconnected")
async def main():
server = await websockets.serve(
on_connect,
'0.0.0.0',
9000,
subprotocols=['ocpp1.6'],
ping_interval=None,
ping_timeout=None
)
logging.info("Server Started listening to new connections...")
await server.wait_closed()
if __name__ == '__main__':
asyncio.run(main())
> async def send_heartbeat(self, interval):
> request = call.HeartbeatPayload()
> while True:
> await self.call(request)
> await asyncio.sleep(interval)
>
> await asyncio.gather(cp.start(), cp.send_heartbeat(10))

Discord bot doesn't work and not changing status

At first my discord bot doesn't work, in this code is erorr and i can't find it, and second is that it doesn't changing status, it was changing when you put just 2 text but when trying to put client.guilds it not
#tasks.loop( seconds = 12 )
async def changeStatus():
iterationPosition = 0
status = [f' on { len(client.guilds) } servers', '~help']
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=status[iterationPosition]))
iterationPosition = 0 if (iterationPosition is len(status) - 1) else (iterationPosition + 1)
#client.event
async def on_ready():
print( 'bot connected' )
changeStatus.start()
*Working code but with problem that he writes me answer to commands as many times as all servers he on
tasks.iterationPosition = 0
#tasks.loop( seconds = 5 )
async def changeStatus():
status = [f" on { len(client.guilds) } servers", "~help"]
await client.change_presence(
activity=discord.Activity(
type=discord.ActivityType.playing, name=status[tasks.iterationPosition]
)
)
tasks.iterationPosition = (
0
if (tasks.iterationPosition is len(status) - 1)
else (tasks.iterationPosition + 1)
)
#client.event
async def on_ready():
print( 'bot connected' )
changeStatus.start()
In your code you always assign 0 to iterationPosition at the start of loop, instead put it in "global" scope like this:
tasks.iterationPosition = 0
#tasks.loop(seconds=12)
async def changeStatus():
status = [f" on { len(client.guilds) } servers", "~help"]
await client.change_presence(
activity=discord.Activity(
type=discord.ActivityType.playing, name=status[tasks.iterationPosition]
)
)
tasks.iterationPosition = (
0
if (tasks.iterationPosition is len(status) - 1)
else (tasks.iterationPosition + 1)
)

How do I inject username into footer?

I am trying to interject a username into the footer of a discord embedded message, that says who requested the command and I've tried varies things and I cant get it to work the way I want it to. Any help would be appreciated. I want it to go into the price command
#client.command(pass_context=True)
async def ping(ctx):
username = ctx.message.author.display_name
channel = ctx.message.channel
t1 = time.perf_counter()
await client.send_typing(channel)
t2 = time.perf_counter()
embed=discord.Embed(title="Pong at {username}".format(username=username), description='It took {}ms.'.format(round((t2-t1)*1000)), color=0xDA70D6)
await client.say(embed=embed)
#client.command(aliases= ['price', 'p'])
async def calc(quantity: int, itemA: str, itemB: str):
#itemAPrice = get_value(itemA)
#itemBPrice = get_value(itemB)
itemAPrice = items[aliases[itemA]]
itemBPrice = items[aliases[itemB]]
if itemAPrice and itemBPrice:
itemQuotient = itemAPrice/itemBPrice
itemBEquivalent = round(quantity * itemQuotient, 2)
embed=discord.Embed(title="Exchange Rate", description='{quantity} {itemA} is equal to {itemBEquivalent} {itemB}'.format(quantity = quantity, itemA = itemA, itemBEquivalent = itemBEquivalent, itemB = itemB), color=0xDA70D6)
await client.say(embed=embed)
elif not itemAPrice:
await client.say('No match found for ' + itemA)
elif not itemBPrice:
await client.say('No match found for ' + itemB)
Pass the invocation context into the command, then use that to get the name of the user who invoked the command. From there, you can use ctx.message.author.name, and insert that in your footer:
#client.command(aliases= ['price', 'p'], pass_context=True)
async def calc(ctx, quantity: int, itemA: str, itemB: str):
itemAPrice = items[aliases[itemA]]
itemBPrice = items[aliases[itemB]]
if itemAPrice and itemBPrice:
itemQuotient = itemAPrice/itemBPrice
itemBEquivalent = round(quantity * itemQuotient, 2)
embed=discord.Embed(title="Exchange Rate", description='{quantity} {itemA} is equal to {itemBEquivalent} {itemB}'.format(quantity = quantity, itemA = itemA, itemBEquivalent = itemBEquivalent, itemB = itemB), color=0xDA70D6)
embed.set_footer(text="Command invoked by {}".format(ctx.message.author.name))
await client.say(embed=embed)
elif not itemAPrice:
await client.say('No match found for ' + itemA)
elif not itemBPrice:
await client.say('No match found for ' + itemB)
If you want to mention the user, you can use ctx.message.author.mention instead
Looks like you can't, only text and icon are supported
https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed.set_footer

Categories

Resources