uint8_t AJRouter_Connect(AJ_BusAttachment* busAttachment, const char* routerName) { while (TRUE) { AJ_Status status = AJ_OK; #ifdef ONBOARDING_SERVICE status = AJOBS_EstablishWiFi(); if (status != AJ_OK) { AJ_AlwaysPrintf(("Failed to establish WiFi connectivity with status=%s\n", AJ_StatusText(status))); AJ_Sleep(AJAPP_CONNECT_PAUSE); return FALSE; } #endif AJ_AlwaysPrintf(("Attempting to connect to bus '%s'\n", routerName)); status = AJ_FindBusAndConnect(busAttachment, routerName, AJAPP_CONNECT_TIMEOUT); if (status != AJ_OK) { AJ_AlwaysPrintf(("Failed to connect to bus sleeping for %d seconds\n", AJAPP_CONNECT_PAUSE / 1000)); AJ_Sleep(AJAPP_CONNECT_PAUSE); #ifdef ONBOARDING_SERVICE if (status == AJ_ERR_DHCP) { AJOBS_SwitchToRetry(); } #endif continue; } const char* busUniqueName = AJ_GetUniqueName(busAttachment); if (busUniqueName == NULL) { AJ_AlwaysPrintf(("Failed to GetUniqueName() from newly connected bus, retrying\n")); continue; } AJ_AlwaysPrintf(("Connected to router with BusUniqueName=%s\n", busUniqueName)); break; } return TRUE; }
static uint8_t AJRouter_Disconnect(AJ_BusAttachment* busAttachment, uint8_t disconnectWiFi) { AJ_InfoPrintf(("AllJoyn disconnect\n")); AJ_Sleep(AJAPP_SLEEP_TIME); // Sleep a little to let any pending requests to router to be sent AJ_Disconnect(busAttachment); AJ_Sleep(AJAPP_SLEEP_TIME); // Sleep a little while before trying to reconnect return TRUE; }
static void set_SPI_registers(void) { volatile uint16_t spi_API = 0; AJ_AlwaysPrintf(("\n\n**************\nTEST: %s\n\n", __FUNCTION__)); // reset the target // spi_API = (1 << 15); // AJ_WSL_SPI_RegisterWrite(AJ_WSL_SPI_REG_SPI_CONFIG, spi_API); // AJ_Sleep(1 << 22); // one extra write to force the device out of the reset state. spi_API = 0x80; AJ_WSL_SPI_RegisterWrite(AJ_WSL_SPI_REG_SPI_CONFIG, spi_API); AJ_Sleep(100); // write spi_API = 0x80; // same as capture AJ_WSL_SPI_RegisterWrite(AJ_WSL_SPI_REG_SPI_CONFIG, spi_API); // AJ_InfoPrintf(("AJ_WSL_SPI_REG_SPI_CONFIG was %04x\n", spi_API)); AJ_WSL_SPI_RegisterRead(AJ_WSL_SPI_REG_WRBUF_SPC_AVA, (uint8_t*)&spi_API); spi_API = LE16_TO_CPU(spi_API); AJ_InfoPrintf(("AJ_WSL_SPI_REG_WRBUF_SPC_AVA was %04x\n", spi_API)); spi_API = 0x40; // same as capture AJ_WSL_SPI_RegisterWrite(AJ_WSL_SPI_REG_WRBUF_WATERMARK, spi_API); // AJ_InfoPrintf(("AJ_WSL_SPI_REG_SPI_CONFIG was %04x\n", spi_API)); spi_API = 0x400; // same as capture AJ_WSL_SPI_RegisterWrite(AJ_WSL_SPI_REG_INTR_CAUSE, spi_API); AJ_InfoPrintf(("AJ_WSL_SPI_REG_INTR_CAUSE was %04x\n", spi_API)); spi_API = 0x3ff; AJ_WSL_SPI_RegisterWrite(AJ_WSL_SPI_REG_INTR_ENABLE, spi_API); AJ_InfoPrintf(("AJ_WSL_SPI_REG_INTR_ENABLE was %04x\n", spi_API)); spi_API = 0x0e; AJ_WSL_SPI_RegisterWrite(AJ_WSL_SPI_REG_INTR_ENABLE, spi_API); AJ_InfoPrintf(("AJ_WSL_SPI_REG_INTR_ENABLE was %04x\n", spi_API)); spi_API = 0x1e; AJ_WSL_SPI_RegisterWrite(AJ_WSL_SPI_REG_INTR_ENABLE, spi_API); AJ_InfoPrintf(("AJ_WSL_SPI_REG_INTR_ENABLE was %04x\n", spi_API)); spi_API = 0x0; AJ_WSL_SPI_RegisterWrite(AJ_WSL_SPI_REG_INTR_ENABLE, spi_API); AJ_InfoPrintf(("AJ_WSL_SPI_REG_INTR_ENABLE was %04x\n", spi_API)); spi_API = 0x1e; AJ_WSL_SPI_RegisterWrite(AJ_WSL_SPI_REG_INTR_ENABLE, spi_API); AJ_InfoPrintf(("AJ_WSL_SPI_REG_INTR_ENABLE was %04x\n", spi_API)); AJ_Sleep(100); }
void Randomizer() { do { AJ_RandBytes((uint8_t*) &tid1, sizeof(tid1)); AJ_Sleep(10); AJ_RandBytes((uint8_t*) &tid2, sizeof(tid2)); AJ_Sleep(10); AJ_RandBytes((uint8_t*) &tid3, sizeof(tid3)); AJ_Sleep(10); AJ_RandBytes((uint8_t*) &tid4, sizeof(tid4)); AJ_InfoPrintf(("Randomizer values: %u %u %u %u\n", tid1, tid2, tid3, tid4)); } while (tid1 == 0 || tid2 == 0 || tid3 == 0 || tid4 == 0); }
uint8_t AJRouter_Disconnect(AJ_BusAttachment* busAttachment, uint8_t disconnectWiFi) { AJ_AlwaysPrintf(("AllJoyn disconnect\n")); AJ_Sleep(AJAPP_SLEEP_TIME); // Sleep a little to let any pending requests to router to be sent AJ_Disconnect(busAttachment); #ifdef ONBOARDING_SERVICE if (disconnectWiFi) { AJOBS_DisconnectWiFi(); } #endif AJ_Sleep(AJAPP_SLEEP_TIME); // Sleep a little while before trying to reconnect return TRUE; }
AJ_Status CPS_StartService(AJ_BusAttachment* bus, const char* busAddress, uint32_t timeout, uint8_t connected) { AJ_Status status = AJ_OK; while (TRUE) { AJ_InfoPrintf(("Attempting to connect to bus '%s'\n", busAddress)); status = AJ_Connect(bus, busAddress, timeout); if (status != AJ_OK) { AJ_ErrPrintf(("Failed to connect to bus '%s', sleeping for %d seconds...\n", busAddress, CPSC_CONNECT_PAUSE / 1000)); AJ_Sleep(CPSC_CONNECT_PAUSE); continue; } AJ_InfoPrintf(("Connected successfully\n")); isBusConnected = TRUE; status = AJ_BusSetSignalRule(bus, CPSAnnounceMatch, AJ_BUS_SIGNAL_ALLOW); if (status != AJ_OK) { AJ_ErrPrintf(("Could not set Announcement Interface AddMatch\n")); return status; } break; } ; return status; }
static uint8_t AJRouter_Connect(AJ_BusAttachment* busAttachment, const char* routerName) { AJ_Status status; const char* busUniqueName; while (TRUE) { AJ_InfoPrintf(("Attempting to connect to bus '%s'\n", routerName)); status = AJ_FindBusAndConnect(busAttachment, routerName, AJAPP_CONNECT_TIMEOUT); if (status != AJ_OK) { AJ_InfoPrintf(("Failed to connect to bus sleeping for %d seconds\n", AJAPP_CONNECT_PAUSE / 1000)); AJ_Sleep(AJAPP_CONNECT_PAUSE); continue; } busUniqueName = AJ_GetUniqueName(busAttachment); if (busUniqueName == NULL) { AJ_ErrPrintf(("Failed to GetUniqueName() from newly connected bus, retrying\n")); continue; } AJ_InfoPrintf(("Connected to router with BusUniqueName=%s\n", busUniqueName)); break; } /* Setup password based authentication listener for secured peer to peer connections */ AJ_BusSetPasswordCallback(busAttachment, PasswordCallback); /* Configure timeout for the link to the Router bus */ AJ_SetBusLinkTimeout(busAttachment, 60); // 60 seconds return TRUE; }
int AJ_Main(void) { #ifdef AJ_CONFIGURE_WIFI_UPON_START # error This sample cannot be built with AJ_CONFIGURE_WIFI_UPON_START defined #endif AJ_Status status = AJ_OK; AJ_BusAttachment bus; int32_t dhcp_attempts = 5; /* * One time initialization before calling any other AllJoyn APIs */ AJ_Initialize(); AJ_PrintXML(AppObjects); AJ_RegisterObjects(AppObjects, NULL); SetBusAuthPwdCallback(MyBusAuthPwdCB); // Windows, Linux and Arduino are already connected to the network when we get to this point. #if !(defined(ARDUINO) || defined(__linux) || defined(_WIN32) || defined(__MACH__)) #define AJ_DHCP_TIMEOUT 10000 // Step 1: connect to a WIFI network. // This will also attempt to acquire an IP from DHCP status = AJ_ConnectWiFi(ssid, secType, AJ_WIFI_CIPHER_CCMP, passphrase); // if DHCP timed out, try it again for up to five attempts while (status == AJ_ERR_TIMEOUT && --dhcp_attempts) { uint32_t ip, mask, gw; status = AJ_AcquireIPAddress(&ip, &mask, &gw, AJ_DHCP_TIMEOUT); if (status != AJ_OK) { AJ_ErrPrintf(("AJ_Net_Up(): AJ_AcquireIPAddress Failed\n")); } } if (status != AJ_OK) { printf("Unable to connect to wifi and acquire IP\n"); return status; } #endif //Now we need to find a daemon, connect to it and authenticate // see the ConnectToBus for an explanation. status = ConnectToBus(&bus); AJ_Sleep(10000); AJ_Disconnect(&bus); return status; }
void* RunFunc(void* threadArg) { while (ioThreadRunning) { if (consumed) { AJ_GetLine(cmdline, sizeof(cmdline), stdin); consumed = FALSE; } AJ_Sleep(1000); } return 0; }
AJ_Status AJOBS_ControllerAPI_GotoIdleWiFi(uint8_t reset) { AJ_Status status = AJ_OK; AJ_WiFiConnectState wifiConnectState = AJ_GetWifiConnectState(); if (wifiConnectState != AJ_WIFI_IDLE) { status = AJ_DisconnectWiFi(); if (reset) { status = AJ_ResetWiFi(); } } AJ_Sleep(1000); while ((wifiConnectState != AJ_WIFI_IDLE) && (wifiConnectState != AJ_WIFI_CONNECT_FAILED) && (wifiConnectState != AJ_WIFI_DISCONNECTING)) { wifiConnectState = AJ_GetWifiConnectState(); AJ_InfoPrintf(("WIFI_CONNECT_STATE: %s\n", AJ_WiFiConnectStateText(wifiConnectState))); AJ_Sleep(500); } status = AJOBS_ControllerAPI_DoScanInfo(); return status; }
/* * create the WMI request to open a socket on the target device */ int8_t AJ_WSL_NET_socket_open(uint16_t domain, uint16_t type, uint16_t protocol) { AJ_Status status; uint8_t handle = AJ_WSL_SOCKET_MAX; AJ_BufList* open; open = AJ_BufListCreate(); WSL_MarshalPacket(open, WSL_SOCKET, WSL_SOCK_OPEN, 0x0c, domain, type, protocol); WMI_MarshalHeader(open, 1, 1); AJ_WSL_WMI_PadPayload(open); //AJ_BufListPrintDumpContinuous(open); AJ_WSL_WMI_QueueWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_SOCKET, WSL_SOCK_OPEN), AJ_WSL_HTC_DATA_ENDPOINT1, open); // wait until the command completes { wsl_work_item* item = NULL; status = AJ_WSL_WMI_WaitForWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_SOCKET, WSL_SOCK_OPEN), &item); if (status != AJ_OK) { AJ_WSL_WMI_FreeWorkItem(item); return -1; } if (item) { if (item->itemType == AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_SOCKET, WSL_SOCK_OPEN)) { AJ_InfoPrintf(("AJ_WSL_NET_socket_open(): WORK ITEM RECEIVED\n")); uint16_t WMIEvent; uint32_t reserved; uint32_t _command; uint32_t _handle; uint32_t _error; uint32_t _mode; WMI_Unmarshal(item->node->buffer, "quuuuu", &WMIEvent, &reserved, &_command, &_handle, &_error, &_mode); AJ_InfoPrintf((" Socket Open: handle %08lx error %08lx\n", _handle, _error)); handle = AJ_WSL_FindOpenSocketContext(); if (handle != AJ_WSL_SOCKET_MAX) { AJ_WSL_SOCKET_CONTEXT[handle].targetHandle = _handle; AJ_WSL_SOCKET_CONTEXT[handle].valid = TRUE; AJ_WSL_SOCKET_CONTEXT[handle].domain = domain; AJ_WSL_SOCKET_CONTEXT[handle].type = type; AJ_WSL_SOCKET_CONTEXT[handle].protocol = protocol; } } else { AJ_WarnPrintf(("AJ_WSL_NET_socket_open(): BAD WORK ITEM RECEIVED\n")); } } AJ_WSL_WMI_FreeWorkItem(item); } AJ_Sleep(100); return handle; }
void Do_Connect() { while (!connected) { AJ_Status status; AJ_Printf("Attempting to connect to bus\n"); status = AJ_Connect(&bus, NULL, CONNECT_TIMEOUT); if (status != AJ_OK) { AJ_Printf("Failed to connect to bus sleeping for %lu seconds\n", CONNECT_PAUSE / 1000); AJ_Sleep(CONNECT_PAUSE); continue; } connected = TRUE; AJ_Printf("AllJoyn service connected to bus\n"); } }
void Do_Connect(AJ_BusAttachment* bus) { while (!connected) { AJ_Status status; AJ_InfoPrintf(("Attempting to connect to bus\n")); status = AJ_FindBusAndConnect(bus, NULL, CONNECT_TIMEOUT); if (status != AJ_OK) { AJ_InfoPrintf(("Failed to connect to bus sleeping for %lu seconds\n", CONNECT_PAUSE / 1000)); AJ_Sleep(CONNECT_PAUSE); continue; } connected = TRUE; AJ_BusAddSignalRule(bus, "Chat", InterfaceName, AJ_BUS_SIGNAL_ALLOW); AJ_InfoPrintf(("AllJoyn service connected to bus\n")); AJ_InfoPrintf(("Connected to Daemon:%s\n", AJ_GetUniqueName(bus))); } }
AJ_Status AJ_WSL_ipconfig(uint32_t mode, uint32_t* ip, uint32_t* mask, uint32_t* gateway) { AJ_Status status = AJ_ERR_DHCP; uint16_t ipv6[8] = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 }; wsl_work_item* item = NULL; switch (mode) { case (IPCONFIG_QUERY): { AJ_InfoPrintf(("AJ_WSL_ipconfig(): IPCONFIG_QUERY\n")); AJ_BufList* ipconfig; ipconfig = AJ_BufListCreate(); WSL_MarshalPacket(ipconfig, WSL_SOCKET, WSL_SOCK_IPCONFIG, 0x60, 0, ip, mask, gateway, &ipv6, &ipv6, &ipv6, &ipv6, 0, 0, 0, 0); WMI_MarshalHeader(ipconfig, 1, 1); AJ_WSL_WMI_PadPayload(ipconfig); AJ_WSL_WMI_QueueWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_SOCKET, WSL_SOCK_IPCONFIG), AJ_WSL_HTC_DATA_ENDPOINT1, ipconfig); { status = AJ_WSL_WMI_WaitForWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_SOCKET, WSL_SOCK_IPCONFIG), &item); if (item) { if (item->itemType == AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_SOCKET, WSL_SOCK_IPCONFIG)) { AJ_InfoPrintf(("AJ_WSL_ipconfig(): WORK ITEM RECEIVED\n")); uint16_t WMIEvent; uint32_t reserved; uint32_t _command; uint32_t _handle; uint32_t _error; uint32_t _mode; WMI_Unmarshal(item->node->buffer, "quuuuuuuu", &WMIEvent, &reserved, &_command, &_handle, &_error, &_mode, ip, mask, gateway); if (ip != 0) { status = AJ_OK; } } else { AJ_WarnPrintf(("AJ_WSL_ipconfig(): BAD WORK ITEM RECEIVED\n")); } } } } AJ_WSL_WMI_FreeWorkItem(item); break; case (IPCONFIG_STATIC): AJ_InfoPrintf(("AJ_WSL_ipconfig(): IPCONFIG_STATIC\n")); AJ_BufList* ipconfig_dhcp_static; ipconfig_dhcp_static = AJ_BufListCreate(); WSL_MarshalPacket(ipconfig_dhcp_static, WSL_SOCKET, WSL_SOCK_IPCONFIG, 0x60, 1, ip, mask, gateway, &ipv6, &ipv6, &ipv6, &ipv6, 0, 0, 0, 0); WMI_MarshalHeader(ipconfig_dhcp_static, 1, 1); AJ_WSL_WMI_PadPayload(ipconfig_dhcp_static); //AJ_BufListPrintDumpContinuous(ipconfig_dhcp_static); AJ_WSL_WMI_QueueWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_SOCKET, WSL_SOCK_IPCONFIG), AJ_WSL_HTC_DATA_ENDPOINT1, ipconfig_dhcp_static); status = AJ_WSL_WMI_WaitForWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_SOCKET, WSL_SOCK_IPCONFIG), &item); AJ_WSL_WMI_FreeWorkItem(item); AJ_Sleep(1000); break; case (IPCONFIG_DHCP): AJ_InfoPrintf(("AJ_WSL_ipconfig(): IPCONFIG_DHCP\n")); AJ_BufList* ipconfig_dhcp; ipconfig_dhcp = AJ_BufListCreate(); WSL_MarshalPacket(ipconfig_dhcp, WSL_SOCKET, WSL_SOCK_IPCONFIG, 0x60, 2, ip, mask, gateway, &ipv6, &ipv6, &ipv6, &ipv6, 0, 0, 0, 0); WMI_MarshalHeader(ipconfig_dhcp, 1, 1); AJ_WSL_WMI_PadPayload(ipconfig_dhcp); AJ_WSL_WMI_QueueWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_SOCKET, WSL_SOCK_IPCONFIG), AJ_WSL_HTC_DATA_ENDPOINT1, ipconfig_dhcp); status = AJ_WSL_WMI_WaitForWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_SOCKET, WSL_SOCK_IPCONFIG), &item); AJ_WSL_WMI_FreeWorkItem(item); AJ_Sleep(100); break; } return status; }
AJ_EXPORT AJ_Status AJ_WSL_NET_connect(const char* SSID, const char* passphrase, WSL_NET_AUTH_MODE auth, WSL_NET_CRYPTO_TYPE crypto, uint8_t softAP) { AJ_Status status; wsl_scan_list* list; list = (wsl_scan_list*)AJ_WSL_GetScanList(); WSL_ClearScanList(list); AJ_WSL_NET_SetPowerMode(2); uint8_t bss_mac[6]; // Open auth does not require you to explicitly set the BSSID so this secondary scan is not needed if (!softAP) { if (auth != WSL_NET_AUTH_NONE) { // Do a scan of just the SSID you want AJ_WSL_SetProbedSSID(SSID, 1); { AJ_BufList* start_scan; uint8_t found = 0; int i; AJ_WSL_NET_set_scan_params(); while (!found) { wsl_work_item* item; AJ_InfoPrintf(("AJ_WSL_NET_scan(): START_SCAN\n")); start_scan = AJ_BufListCreate(); AJ_WSL_SetProbedSSID(SSID, 1); AJ_WSL_NET_set_scan_params(); AJ_WSL_NET_BSS_FILTER(6); WSL_MarshalPacket(start_scan, WSL_START_SCAN, 0, 0, 0, 0, 0, 0, 0, 0); WMI_MarshalHeader(start_scan, 1, 1); AJ_WSL_WMI_PadPayload(start_scan); //AJ_BufListPrintDumpContinuous(start_scan); AJ_WSL_WMI_QueueWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_NETWORK, WSL_NET_SCAN), AJ_WSL_HTC_DATA_ENDPOINT1, start_scan); status = AJ_WSL_WMI_WaitForWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_NETWORK, WSL_NET_SCAN), &item); AJ_WSL_WMI_FreeWorkItem(item); // Get the new list (just of the SSID provided in the connect command) AJ_WSL_NET_scan_stop(); list = (wsl_scan_list*)AJ_WSL_GetScanList(); if (list->size == 0) { AJ_AlwaysPrintf(("Could not find access point %s\n", SSID)); WSL_ClearScanList(list); AJ_Sleep(AJ_WSL_CONNECT_WAIT); continue; } WSL_PrintScanSorted(); // Find the SSID you want to connect to in the second scan list for (i = 0; i < list->size; i++) { if (0 == strcmp(list->list[i].ssid, SSID)) { memcpy(&bss_mac, list->list[i].bssid, 6); found = 1; break; } } WSL_ClearScanList(list); } } } } { AJ_BufList* connect; AJ_BufList* connectOut; static const uint8_t zero_mac[6] = { 0, 0, 0, 0, 0, 0 }; uint8_t connect_mac[6]; wsl_work_item* item = NULL; uint8_t found = 0; connect = AJ_BufListCreate(); /* Three different ways connect can be called. * 1. SoftAP: The devices mac is fetched and used * 2. Using Auth: The SSID's mac is found and used * 3. Open auth: A zero'ed mac is used */ if (softAP) { WSL_MarshalPacket(connect, WSL_SET_SOFT_AP, 0, 0x04, 0x01, auth, crypto, 0x00, crypto, 0x00, strlen(SSID), SSID, 0x0, getDeviceMac(), 0x0044, 0x0000); WMI_MarshalHeader(connect, 1, 1); } else if ((auth != WSL_NET_AUTH_NONE) && (crypto != WSL_NET_CRYPTO_WEP)) { WSL_MarshalPacket(connect, WSL_CONNECT, 0, 0x01, 0x01, auth, crypto, 0x00, crypto, 0x00, strlen(SSID), SSID, 0x0, &bss_mac, 0x0044, 0x0000); WMI_MarshalHeader(connect, 1, 1); } else { // if the auth mode is open, use zero_mac, and set flags to zero WSL_MarshalPacket(connect, WSL_CONNECT, 0, 0x01, 0x01, auth, crypto, 0x00, crypto, 0x00, strlen(SSID), SSID, 0x0, &zero_mac, 0x0000, 0x0000); WMI_MarshalHeader(connect, 1, 1); } AJ_InfoPrintf(("AJ_WSL_NET_connect(): CONNECT\n")); AJ_WSL_WMI_PadPayload(connect); //AJ_BufListPrintDumpContinuous(connect); connectOut = AJ_BufListCreateCopy(connect); AJ_WSL_WMI_QueueWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_NETWORK, WSL_NET_CONNECT), AJ_WSL_HTC_DATA_ENDPOINT1, connectOut); if (softAP) { AJ_AlwaysPrintf(("Waiting for a connection to the softAP %s\n", SSID)); memcpy(&connect_mac, (uint8_t*)getDeviceMac(), sizeof(connect_mac)); while (WSL_MacsAreEqual((uint8_t*)&connect_mac, (uint8_t*)getDeviceMac()) == TRUE) { status = AJ_WSL_WMI_WaitForWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_NETWORK, WSL_NET_CONNECT), &item); if (item) { if (item->itemType == WSL_NET_CONNECT) { AJ_InfoPrintf(("AJ_WSL_ip6config(): WORK ITEM RECEIVED\n")); uint16_t WMIEvent; uint32_t toss; uint16_t channel; WMI_Unmarshal(item->node->buffer, "quqM", &WMIEvent, &toss, &channel, &connect_mac); } else { AJ_WarnPrintf(("AJ_WSL_NET_connect(): BAD WORK ITEM RECEIVED\n")); } AJ_WSL_WMI_FreeWorkItem(item); found = 1; } } } else { status = AJ_WSL_WMI_WaitForWorkItem(0, AJ_WSL_WORKITEM(AJ_WSL_WORKITEM_NETWORK, WSL_NET_CONNECT), &item); AJ_WSL_WMI_FreeWorkItem(item); } AJ_BufListFree(connect, 1); return status; } }
int AJ_Main(void) { AJ_Status status = AJ_OK; uint8_t connected = FALSE; /* One time initialization before calling any other AllJoyn APIs. */ AJ_Initialize(); /* This is for debug purposes and is optional. */ AJ_PrintXML(AppObjects); AJ_RegisterObjects(AppObjects, NULL); while (TRUE) { AJ_Message msg; if (!connected) { status = AJ_StartService(&busAttachment, NULL, CONNECT_TIMEOUT, FALSE, ServicePort, ServiceName, AJ_NAME_REQ_DO_NOT_QUEUE, NULL); if (status != AJ_OK) { continue; } AJ_InfoPrintf(("StartService returned %d\n", status)); connected = TRUE; } status = AJ_UnmarshalMsg(&busAttachment, &msg, UNMARSHAL_TIMEOUT); if (AJ_ERR_TIMEOUT == status) { continue; } if (AJ_OK == status) { switch (msg.msgId) { case AJ_METHOD_ACCEPT_SESSION: { uint16_t port; char* joiner; uint32_t sessionId; AJ_UnmarshalArgs(&msg, "qus", &port, &sessionId, &joiner); status = AJ_BusReplyAcceptSession(&msg, TRUE); AJ_InfoPrintf(("Accepted session. Port=%u, session_id=%u joiner='%s'.\n", port, sessionId, joiner)); } break; case BASIC_SIGNAL_SERVICE_GET_NAME: status = AJ_BusPropGet(&msg, GetName, NULL); break; case BASIC_SIGNAL_SERVICE_SET_NAME: status = AJ_BusPropSet(&msg, SetName, NULL); if (AJ_OK == status) { status = SendSignal(); AJ_InfoPrintf(("SendSignal reports status 0x%04x.\n", status)); } break; case AJ_SIGNAL_SESSION_LOST_WITH_REASON: { uint32_t id, reason; AJ_UnmarshalArgs(&msg, "uu", &id, &reason); AJ_AlwaysPrintf(("Session lost. ID = %u, reason = %u", id, reason)); } break; default: /* Pass to the built-in handlers. */ status = AJ_BusHandleBusMessage(&msg); break; } } /* Messages MUST be discarded to free resources. */ AJ_CloseMsg(&msg); if ((status == AJ_ERR_READ) || (status == AJ_ERR_WRITE)) { AJ_AlwaysPrintf(("AllJoyn disconnect.\n")); AJ_Disconnect(&busAttachment); connected = FALSE; /* Sleep a little while before trying to reconnect. */ AJ_Sleep(SLEEP_TIME); } } AJ_AlwaysPrintf(("Basic service exiting with status 0x%04x.\n", status)); return status; }
void AJ_Main(void) { uint8_t i = 0; AJ_Status status = AJ_ERR_FAILURE; /* the glass is half-empty */ AJ_BusAttachment bus; /* these variables are used when kicking off DHCP */ uint32_t current_ip_address = 0; uint32_t current_subnet_mask = 0; uint32_t current_default_gateway = 0; AJ_Time dhcpTimer; uint32_t timeTakenForDhcp = 0; AJ_Initialize(); AJ_Printf("\nAllJoyn Release: %s\n\n", AJ_GetVersion()); AJ_Printf("INFO: The parameter RUN_NEGATIVE_TESTS is %s\n", (RUN_NEGATIVE_TESTS ? "true" : "false")); AJ_Printf("INFO: The parameter DELAY_BETWEEN_SCANS is %u ms\n", DELAY_BETWEEN_SCANS); AJ_Printf("INFO: The parameter DELAY_BETWEEN_ASSOCIATIONS is %u ms\n", DELAY_BETWEEN_ASSOCIATIONS); AJ_Printf("INFO: The parameter DHCP_TIMEOUT is %u ms\n", DHCP_TIMEOUT); AJ_Printf("INFO: The parameter DISCOVER_TIMEOUT is %u ms\n", DISCOVER_TIMEOUT); /* reset the wifi to start with a clean slate */ status = AJ_ResetWiFi(); if (AJ_OK != status) { AJ_Printf("WARN: AJ_ResetWiFi returned %s (code: %u).\n", AJ_StatusText(status), status); } /* * Repeatedly do the following: * a. scan for access points in the vicinity * b. For each open access point in the returned results: * i. associate using AJ_ConnectWiFi * ii. acquire an ip address using AJ_AcquireIPAddress * iii. perform a short-lived discovery on some random node prefix * using AJ_FindBusAndConnect * iv. disassociate using AJ_DisconnectWiFi * c. For each secured access point in the returned results: * i. Connect to it with intentionally incorrect parameters * (Negative test) */ while (TRUE) { AJ_RandBytes(¤tContext, sizeof(currentContext)); uint8_t currentMaxAps = 0; AJ_RandBytes(¤tMaxAps, sizeof(currentMaxAps)); /* Reset numValidScanEntries, before every scan attempt. */ numValidScanEntries = 0; status = AJ_WiFiScan((void*) (sentinelForWifiScanContext + currentContext), wifiScanResultCallback, currentMaxAps); if (AJ_OK != status) { if (AJ_ERR_FAILURE == status && 0 != currentMaxAps) { scanStats.numFailed++; } else if (AJ_ERR_RESOURCES == status) { scanStats.numFailed++; } AJ_Printf("Failed to scan: %s (code: %u)\n", AJ_StatusText(status), status); /* No point in attempting to do wifi operations, when scan failed */ continue; } else { /* * A success was returned from AJ_WiFiScan. Were any results * returned after all?? */ if (0 < numValidScanEntries) { scanStats.numSuccessful++; } else { AJ_Printf("WARN: AJ_WiFiScan returned %s (code: %u), but returned ZERO scan results...\n", AJ_StatusText(status), status); scanStats.numFailed++; /* When num of scan results is zero, there is nothing to do */ continue; } } /* numValidScanEntries is an index into the array. Hence +1. */ if (currentMaxAps < numValidScanEntries + 1) { AJ_Printf("WARN: Scan returned more results (%u) than requested (%u).\n", numValidScanEntries + 1, currentMaxAps); } else { AJ_Printf("Wifi scan successful (got %u results).\n", numValidScanEntries); } for (i = 0; i < numValidScanEntries; i++) { if (AJ_WIFI_SECURITY_NONE != wifiScanInfo[i].secType) { /* On some targets, it is not possible to check for 802.11 * authentication failure when security type is WEP. * Hence, run negative tests only for WPA/WPA2-based APs. */ if (RUN_NEGATIVE_TESTS && AJ_WIFI_SECURITY_WEP != wifiScanInfo[i].secType) { /* Run a negative test for wifi association */ AJ_Printf("RUN (negative test): Attempting to associate with %s using a randomly generated passphrase...", wifiScanInfo[i].ssid); char random_passphrase[128 + 1]; AJ_RandHex(random_passphrase, sizeof(random_passphrase), (sizeof(random_passphrase) - 1) / 2); /* Set a random passphrase length based on security type */ uint8_t randomPassphraseLen = 0; /* WPA / WPA2 - assuming min len is 8 and max is 64 */ AJ_RandBytes(&randomPassphraseLen, sizeof(randomPassphraseLen)); randomPassphraseLen = 8 + randomPassphraseLen % (64 - 8 + 1); random_passphrase[randomPassphraseLen] = '\0'; status = AJ_ConnectWiFi(wifiScanInfo[i].ssid, wifiScanInfo[i].secType, wifiScanInfo[i].cipherType, random_passphrase); if (AJ_OK == status) { /* negative test failed */ AJ_Printf("FAIL (negative test): Associated with SSID: %s BSSID: %x:%x:%x:%x:%x:%x Security: %s(%s) Passphrase: %s RSSI: %u ...\n", wifiScanInfo[i].ssid, wifiScanInfo[i].bssid[0], wifiScanInfo[i].bssid[1], wifiScanInfo[i].bssid[2], wifiScanInfo[i].bssid[3], wifiScanInfo[i].bssid[4], wifiScanInfo[i].bssid[5], secStr[wifiScanInfo[i].secType], ciphStr[wifiScanInfo[i].cipherType], random_passphrase, wifiScanInfo[i].rssi); /* negative test failed - don't go any further */ AJ_ASSERT(0); } else { AJ_Printf("Done (negative test).\n"); } status = AJ_DisconnectWiFi(); AJ_Sleep(DELAY_BETWEEN_ASSOCIATIONS); } continue; } else { AJ_Printf("Attempting to associate with SSID: %s BSSID: %x:%x:%x:%x:%x:%x Security: %s(%s) RSSI: %u ...\n", wifiScanInfo[i].ssid, wifiScanInfo[i].bssid[0], wifiScanInfo[i].bssid[1], wifiScanInfo[i].bssid[2], wifiScanInfo[i].bssid[3], wifiScanInfo[i].bssid[4], wifiScanInfo[i].bssid[5], secStr[wifiScanInfo[i].secType], ciphStr[wifiScanInfo[i].cipherType], wifiScanInfo[i].rssi); status = AJ_ConnectWiFi(wifiScanInfo[i].ssid, wifiScanInfo[i].secType, wifiScanInfo[i].cipherType, ""); if (AJ_OK != status) { associationStats.numFailed++; AJ_Printf("Failed to associate : %s (code: %u)\n", AJ_StatusText(status), status); /* * No point in proceeding any further when WiFi association * has failed */ continue; } else { associationStats.numSuccessful++; } AJ_Printf("Successfully associated. Attempting to get IP Address via DHCP...\n"); AJ_InitTimer(&dhcpTimer); status = AJ_AcquireIPAddress(¤t_ip_address, ¤t_subnet_mask, ¤t_default_gateway, DHCP_TIMEOUT); timeTakenForDhcp = AJ_GetElapsedTime(&dhcpTimer, FALSE); if (AJ_OK != status) { if (AJ_ERR_TIMEOUT == status) { dhcpStats.numTimedout++; AJ_Printf("Timedout (%u ms) while trying to get IP Address via DHCP\n", timeTakenForDhcp); /* * Discovery timed out. * Check whether the API returned in a timely manner. * See whether the actual duration is off by +/- 500ms. * Delay beyond that is unusual. */ if (500 < abs(DHCP_TIMEOUT - timeTakenForDhcp)) { AJ_Printf("WARN: AJ_AcquireIPAddress API did not return in a timely manner. Timeout parameter: %u Actual time elapsed: %u\n", DHCP_TIMEOUT, timeTakenForDhcp); } } else { dhcpStats.numFailed++; AJ_Printf("Failed to get IP Address via DHCP : %s (code: %u)\n", AJ_StatusText(status), status); } /* * No point in proceeding any further when IP address was * not acquired */ continue; } else { dhcpStats.numSuccessful++; AJ_Printf("Successfully obtained\n"); AJ_Printf("\tIP Addresss : %s\n", TestAddrStr(current_ip_address)); AJ_Printf("\tSubnet Mask : %s\n", TestAddrStr(current_subnet_mask)); AJ_Printf("\tDefault Gateway: %s\n", TestAddrStr(current_default_gateway)); } /* Generate a random name using routingNodePrefix */ char currentRoutingNodeName[32 + 1]; strncpy(currentRoutingNodeName, routingNodePrefix, sizeof(routingNodePrefix)); AJ_RandHex(currentRoutingNodeName + strlen(routingNodePrefix), sizeof(currentRoutingNodeName) - sizeof(routingNodePrefix), (sizeof(currentRoutingNodeName) - sizeof(routingNodePrefix) - 1) / 2); currentRoutingNodeName[32] = '\0'; /* just to be safe */ AJ_Printf("Attempting to discover routing node: %s...", currentRoutingNodeName); status = AJ_FindBusAndConnect(&bus, currentRoutingNodeName, DISCOVER_TIMEOUT); if (AJ_ERR_TIMEOUT == status) { /* this is the expected result */ discoverStats.numTimedout++; AJ_Printf("Done (discovery of routing node).\n"); } else if (AJ_OK != status) { discoverStats.numFailed++; AJ_Printf("Failed to connect to routing node: %s (code: %u)\n", AJ_StatusText(status), status); } else if (AJ_OK == status) { /* * the test attempted to discovery a randomly generated * routing node prefix and it worked - highly unlikely event */ AJ_Printf("FATAL: Was able to discover and connect to routing node with prefix %s. Got unique address %s.", currentRoutingNodeName, AJ_GetUniqueName(&bus)); AJ_ASSERT(0); } status = AJ_DisconnectWiFi(); if (AJ_OK != status) { disassociationStats.numFailed++; AJ_Printf("Failed to disassociate: %s (code: %u)\n", AJ_StatusText(status), status); } else { disassociationStats.numSuccessful++; AJ_Printf("Disassociated from access point. "); } AJ_Sleep(DELAY_BETWEEN_ASSOCIATIONS); } } PrintStats(); AJ_Sleep(DELAY_BETWEEN_SCANS); } }
/* * Configure the SPI hardware, including SPI clock speed, mode, delays, chip select pins * It uses values listed in */ void AJ_WSL_SPI_InitializeSPIController(void) { uint32_t config; /* Initialize and enable DMA controller. */ pmc_enable_periph_clk(ID_DMAC); dmac_init(DMAC); dmac_set_priority_mode(DMAC, DMAC_PRIORITY_ROUND_ROBIN); dmac_enable(DMAC); /* Configure DMA TX channel. */ config = 0; config |= DMAC_CFG_DST_PER(AJ_SPI_TX_INDEX) | DMAC_CFG_DST_H2SEL | DMAC_CFG_SOD | DMAC_CFG_FIFOCFG_ALAP_CFG; dmac_channel_set_configuration(DMAC, AJ_DMA_TX_CHANNEL, config); /* Configure DMA RX channel. */ config = 0; config |= DMAC_CFG_SRC_PER(AJ_SPI_RX_INDEX) | DMAC_CFG_SRC_H2SEL | DMAC_CFG_SOD | DMAC_CFG_FIFOCFG_ALAP_CFG; dmac_channel_set_configuration(DMAC, AJ_DMA_RX_CHANNEL, config); /* Enable receive channel interrupt for DMAC. */ uint8_t* interruptEnableAddress = AJ_SPI_ISER1_IEN_ADDR; *interruptEnableAddress = AJ_SPI_DMAC_IEN_BIT; dmac_enable_interrupt(DMAC, (1 << AJ_DMA_RX_CHANNEL)); dmac_enable_interrupt(DMAC, (1 << AJ_DMA_TX_CHANNEL)); //AJ_WSL_DMA_Setup(); dmac_channel_disable(DMAC, AJ_DMA_TX_CHANNEL); dmac_channel_disable(DMAC, AJ_DMA_RX_CHANNEL); /* * Configure the hardware to enable SPI and some output pins */ { pmc_enable_periph_clk(ID_PIOA); pmc_enable_periph_clk(ID_PIOB); pmc_enable_periph_clk(ID_PIOC); pmc_enable_periph_clk(ID_PIOD); // make all of these pins controlled by the right I/O controller pio_configure_pin_group(PIOA, 0xFFFFFFFF, PIO_TYPE_PIO_PERIPH_A); pio_configure_pin_group(PIOB, 0xFFFFFFFF, PIO_TYPE_PIO_PERIPH_B); pio_configure_pin_group(PIOC, 0xFFFFFFFF, PIO_TYPE_PIO_PERIPH_C); pio_configure_pin_group(PIOD, 0xFFFFFFFF, PIO_TYPE_PIO_PERIPH_D); /* * Reset the device by toggling the CHIP_POWER */ ioport_set_pin_dir(AJ_WSL_SPI_CHIP_POWER_PIN, IOPORT_DIR_OUTPUT); ioport_set_pin_level(AJ_WSL_SPI_CHIP_POWER_PIN, IOPORT_PIN_LEVEL_LOW); AJ_Sleep(10); ioport_set_pin_level(AJ_WSL_SPI_CHIP_POWER_PIN, IOPORT_PIN_LEVEL_HIGH); /* * Reset the device by toggling the CHIP_PWD# signal */ ioport_set_pin_dir(AJ_WSL_SPI_CHIP_PWD_PIN, IOPORT_DIR_OUTPUT); ioport_set_pin_level(AJ_WSL_SPI_CHIP_PWD_PIN, IOPORT_PIN_LEVEL_LOW); AJ_Sleep(10); ioport_set_pin_level(AJ_WSL_SPI_CHIP_PWD_PIN, IOPORT_PIN_LEVEL_HIGH); /* configure the pin that detects SPI data ready from the target chip */ ioport_set_pin_dir(AJ_WSL_SPI_CHIP_SPI_INT_PIN, IOPORT_DIR_INPUT); ioport_set_pin_sense_mode(AJ_WSL_SPI_CHIP_SPI_INT_PIN, IOPORT_SENSE_LEVEL_LOW); pio_handler_set(PIOC, ID_PIOC, AJ_WSL_SPI_CHIP_SPI_INT_BIT, (PIO_PULLUP | PIO_IT_FALL_EDGE), &AJ_WSL_SPI_CHIP_SPI_ISR); pio_handler_set_priority(PIOD, (IRQn_Type) ID_PIOC, 0xB); pio_enable_interrupt(PIOC, AJ_WSL_SPI_CHIP_SPI_INT_BIT); } spi_enable_clock(AJ_WSL_SPI_DEVICE); spi_reset(AJ_WSL_SPI_DEVICE); spi_set_lastxfer(AJ_WSL_SPI_DEVICE); spi_set_master_mode(AJ_WSL_SPI_DEVICE); spi_disable_mode_fault_detect(AJ_WSL_SPI_DEVICE); spi_set_peripheral_chip_select_value(AJ_WSL_SPI_DEVICE, AJ_WSL_SPI_DEVICE_NPCS); spi_set_clock_polarity(AJ_WSL_SPI_DEVICE, AJ_WSL_SPI_DEVICE_NPCS, AJ_WSL_SPI_CLOCK_POLARITY); spi_set_clock_phase(AJ_WSL_SPI_DEVICE, AJ_WSL_SPI_DEVICE_NPCS, AJ_WSL_SPI_CLOCK_PHASE); spi_set_bits_per_transfer(AJ_WSL_SPI_DEVICE, AJ_WSL_SPI_DEVICE_NPCS, SPI_CSR_BITS_8_BIT); spi_set_baudrate_div(AJ_WSL_SPI_DEVICE, AJ_WSL_SPI_DEVICE_NPCS, (sysclk_get_cpu_hz() / AJ_WSL_SPI_CLOCK_RATE)); spi_set_transfer_delay(AJ_WSL_SPI_DEVICE, AJ_WSL_SPI_DEVICE_NPCS, AJ_WSL_SPI_DELAY_BEFORE_CLOCK, AJ_WSL_SPI_DELAY_BETWEEN_TRANSFERS); spi_set_fixed_peripheral_select(AJ_WSL_SPI_DEVICE); spi_configure_cs_behavior(AJ_WSL_SPI_DEVICE, AJ_WSL_SPI_DEVICE_NPCS, SPI_CS_RISE_FORCED); spi_enable_interrupt(AJ_WSL_SPI_DEVICE, SPI_IER_TDRE | SPI_IER_RDRF); spi_enable(AJ_WSL_SPI_DEVICE); }
int main() { AJ_Status status; memset(&txBuffer, 'T', sizeof(txBuffer)); memset(&rxBuffer, 'R', sizeof(rxBuffer)); int blocks; int blocksize = LOCAL_DATA_PACKET_SIZE; for (blocks = 0; blocks < 16; blocks++) { memset(txBuffer + (blocks * blocksize), 0x41 + (uint8_t)blocks, blocksize); } #ifdef READTEST status = AJ_SerialInit("/tmp/COM0", BITRATE, AJ_SERIAL_WINDOW_SIZE, AJ_SERIAL_ENABLE_CRC, AJ_SERIAL_PACKET_SIZE); #else status = AJ_SerialInit("/tmp/COM1", BITRATE, AJ_SERIAL_WINDOW_SIZE, AJ_SERIAL_ENABLE_CRC, AJ_SERIAL_PACKET_SIZE); #endif AJ_Printf("serial init was %u\n", status); uint32_t timerEndProc = 9999; status = AJ_TimerRegister(100000, &TimerCallbackEndProc, NULL, &timerEndProc); AJ_Printf("Added id %u\n", timerEndProc); int iter; int i; #ifdef READTEST AJ_Sleep(2000); // wait for the writing side to be running, this should test the queuing of data. for (iter = 0; iter < 10; iter++) { AJ_Printf("iteration %d\n########################################################################\n", iter); AJ_SerialRecv(rxBuffer, sizeof(rxBuffer), 10000, NULL); if (0 == memcmp(txBuffer, rxBuffer, sizeof(rxBuffer))) { AJ_Printf("Passed#: buffers match.\n"); } else { AJ_Printf("FAILED#: buffers mismatch.\n"); AJ_DumpBytes("RXBUFFER:", rxBuffer, sizeof(rxBuffer)); AJ_DumpBytes("TXBUFFER:", txBuffer, sizeof(txBuffer)); exit(-1); } //AJ_SerialSend(txBuffer, sizeof(txBuffer)); } AJ_Printf("post serial recv\n"); AJ_Sleep(4000); #else AJ_Sleep(500); for (iter = 0; iter < 10; iter++) { printf("iteration %d\n########################################################################\n", iter); AJ_SerialSend(txBuffer, sizeof(txBuffer)); /*AJ_SerialRecv(rxBuffer, sizeof(rxBuffer), 10000, NULL); if (0 == memcmp(txBuffer, rxBuffer, sizeof(rxBuffer))) { AJ_Printf("Passed##: buffers match.\n"); } else { AJ_Printf("FAILED##: buffers mismatch.\n"); AJ_DumpBytes("RXBUFFER:", rxBuffer, sizeof(rxBuffer)); AJ_DumpBytes("TXBUFFER:", txBuffer, sizeof(txBuffer)); exit(-1); }*/ } AJ_Printf("post serial send\n"); AJ_Sleep(4000); #endif /*while (1) { usleep(4000); }*/ return(0); }
AJ_Status AJ_StartClient2(AJ_BusAttachment* bus, const char* daemonName, uint32_t timeout, uint8_t connected, const char* name, uint16_t port, uint32_t* sessionId, const AJ_SessionOpts* opts ) { AJ_Status status = AJ_OK; AJ_Time timer; AJ_Time unmarshalTimer; uint8_t foundName = FALSE; uint8_t clientStarted = FALSE; uint8_t initial = TRUE; AJ_InitTimer(&timer); while (TRUE) { if (AJ_GetElapsedTime(&timer, TRUE) > timeout) { return AJ_ERR_TIMEOUT; } if (!initial || !connected) { initial = FALSE; AJ_InfoPrintf(("Attempting to connect to bus\n")); status = AJ_Connect(bus, daemonName, CONNECT_TIMEOUT); if (status != AJ_OK) { AJ_WarnPrintf(("Failed to connect to bus sleeping for %d seconds\n", CONNECT_PAUSE / 1000)); AJ_Sleep(CONNECT_PAUSE); continue; } AJ_InfoPrintf(("AllJoyn client connected to bus\n")); } /* * Kick things off by finding the service names */ status = AJ_BusFindAdvertisedName(bus, name, AJ_BUS_START_FINDING); if (status == AJ_OK) { break; } AJ_WarnPrintf(("FindAdvertisedName failed\n")); AJ_Disconnect(bus); } *sessionId = 0; while (!clientStarted && (status == AJ_OK)) { AJ_Message msg; if (AJ_GetElapsedTime(&timer, TRUE) > timeout) { return AJ_ERR_TIMEOUT; } status = AJ_UnmarshalMsg(bus, &msg, UNMARSHAL_TIMEOUT); /* * TODO This is a temporary hack to work around buggy select imlpementations */ AJ_InitTimer(&unmarshalTimer); if (status == AJ_ERR_TIMEOUT && (AJ_GetElapsedTime(&unmarshalTimer, TRUE) < UNMARSHAL_TIMEOUT || !foundName)) { /* * Timeouts are expected until we find a name */ status = AJ_OK; continue; } if (status != AJ_OK) { break; } switch (msg.msgId) { case AJ_REPLY_ID(AJ_METHOD_FIND_NAME): case AJ_REPLY_ID(AJ_METHOD_FIND_NAME_BY_TRANSPORT): if (msg.hdr->msgType == AJ_MSG_ERROR) { status = AJ_ERR_FAILURE; } else { uint32_t disposition; AJ_UnmarshalArgs(&msg, "u", &disposition); if ((disposition != AJ_FIND_NAME_STARTED) && (disposition != AJ_FIND_NAME_ALREADY)) { status = AJ_ERR_FAILURE; } } break; case AJ_SIGNAL_FOUND_ADV_NAME: { AJ_Arg arg; AJ_UnmarshalArg(&msg, &arg); AJ_InfoPrintf(("FoundAdvertisedName(%s)\n", arg.val.v_string)); foundName = TRUE; status = AJ_BusJoinSession(bus, arg.val.v_string, port, opts); } break; case AJ_REPLY_ID(AJ_METHOD_JOIN_SESSION): { uint32_t replyCode; if (msg.hdr->msgType == AJ_MSG_ERROR) { status = AJ_ERR_FAILURE; } else { status = AJ_UnmarshalArgs(&msg, "uu", &replyCode, sessionId); if (replyCode == AJ_JOINSESSION_REPLY_SUCCESS) { clientStarted = TRUE; AJ_BusSetSignalRule2(bus, "NameOwnerChanged", "org.freedesktop.DBus", AJ_BUS_SIGNAL_ALLOW); } else { status = AJ_ERR_FAILURE; } } } break; case AJ_SIGNAL_SESSION_LOST: /* * Force a disconnect */ status = AJ_ERR_READ; break; default: /* * Pass to the built-in bus message handlers */ status = AJ_BusHandleBusMessage(&msg); break; } AJ_CloseMsg(&msg); } if (status != AJ_OK) { AJ_WarnPrintf(("AllJoyn disconnect bus status=%s\n", AJ_StatusText(status))); AJ_Disconnect(bus); } return status; }
int AJ_Main() { AJ_Status status; memset(&txBuffer, 'T', sizeof(txBuffer)); memset(&rxBuffer, 'R', sizeof(rxBuffer)); int blocks; int blocksize = LOCAL_DATA_PACKET_SIZE; for (blocks = 0; blocks < 16; blocks++) { memset(txBuffer + (blocks * blocksize), 0x41 + (uint8_t)blocks, blocksize); } #ifdef READTEST status = AJ_SerialInit("/dev/ttyUSB0", BITRATE, AJ_SERIAL_WINDOW_SIZE, AJ_SERIAL_PACKET_SIZE); #else status = AJ_SerialInit("/dev/ttyUSB1", BITRATE, AJ_SERIAL_WINDOW_SIZE, AJ_SERIAL_PACKET_SIZE); #endif AJ_AlwaysPrintf(("serial init was %u\n", status)); #ifdef READTEST AJ_Sleep(2000); // wait for the writing side to be running, this should test the queuing of data. // try to read everything at once int i = 0; //for ( ; i < 10000; ++i) { while (1) { AJ_SerialRecv(rxBuffer, sizeof(rxBuffer), 50000, NULL); } /* //Read small chunks of a packet at one time. for (blocks = 0 ; blocks < 16*4; blocks++) { AJ_SerialRecv(rxBuffer+(blocks*blocksize/4), blocksize/4, 2000, NULL); // AJ_Sleep(200); } */ AJ_DumpBytes("Post serial recv", rxBuffer, sizeof(rxBuffer)); AJ_Sleep(500); #else AJ_Sleep(5000); int i = 0; while (1) { AJ_SerialSend(txBuffer, sizeof(txBuffer)); ++i; if (i % 500 == 0) { AJ_AlwaysPrintf(("Hit iteration %d\n", i)); } } AJ_AlwaysPrintf(("post serial send\n")); #endif while (1) { AJ_StateMachine(); } return(0); }
static AJ_Status StartClient(AJ_BusAttachment* bus, const char* daemonName, uint32_t timeout, uint8_t connected, const char* name, uint16_t port, const char** interfaces, uint32_t* sessionId, char* serviceName, const AJ_SessionOpts* opts) { AJ_Status status = AJ_OK; AJ_Time timer; uint8_t found = FALSE; uint8_t clientStarted = FALSE; uint32_t elapsed = 0; char* rule; size_t ruleLen; const char* base = "interface='org.alljoyn.About',sessionless='t'"; const char* impl = ",implements='"; const char** ifaces; AJ_InfoPrintf(("AJ_StartClient(bus=0x%p, daemonName=\"%s\", timeout=%d., connected=%d., interface=\"%p\", sessionId=0x%p, serviceName=0x%p, opts=0x%p)\n", bus, daemonName, timeout, connected, interfaces, sessionId, serviceName, opts)); AJ_InitTimer(&timer); if ((name == NULL && interfaces == NULL) || (name != NULL && interfaces != NULL)) { return AJ_ERR_INVALID; } while (elapsed < timeout) { if (!connected) { status = AJ_FindBusAndConnect(bus, daemonName, AJ_CONNECT_TIMEOUT); elapsed = AJ_GetElapsedTime(&timer, TRUE); if (status != AJ_OK) { elapsed += AJ_CONNECT_PAUSE; if (elapsed > timeout) { break; } AJ_WarnPrintf(("AJ_StartClient(): Failed to connect to bus, sleeping for %d seconds\n", AJ_CONNECT_PAUSE / 1000)); AJ_Sleep(AJ_CONNECT_PAUSE); continue; } AJ_InfoPrintf(("AJ_StartClient(): AllJoyn client connected to bus\n")); } if (name != NULL) { /* * Kick things off by finding the service names */ status = AJ_BusFindAdvertisedName(bus, name, AJ_BUS_START_FINDING); AJ_InfoPrintf(("AJ_StartClient(): AJ_BusFindAdvertisedName()\n")); } else { /* * Kick things off by finding all services that implement the interface */ ruleLen = strlen(base) + 1; ifaces = interfaces; while (*ifaces != NULL) { ruleLen += strlen(impl) + strlen(*ifaces) + 1; ifaces++; } rule = (char*) AJ_Malloc(ruleLen); if (rule == NULL) { status = AJ_ERR_RESOURCES; break; } strcpy(rule, base); ifaces = interfaces; while (*ifaces != NULL) { strcat(rule, impl); if ((*ifaces)[0] == '$') { strcat(rule, &(*ifaces)[1]); } else { strcat(rule, *ifaces); } strcat(rule, "'"); ifaces++; } status = AJ_BusSetSignalRule(bus, rule, AJ_BUS_SIGNAL_ALLOW); AJ_InfoPrintf(("AJ_StartClient(): Client SetSignalRule: %s\n", rule)); AJ_Free(rule); } if (status == AJ_OK) { break; } if (!connected) { AJ_WarnPrintf(("AJ_StartClient(): Client disconnecting from bus: status=%s.\n", AJ_StatusText(status))); AJ_Disconnect(bus); } } if (elapsed > timeout) { AJ_WarnPrintf(("AJ_StartClient(): Client timed-out trying to connect to bus: status=%s.\n", AJ_StatusText(status))); return AJ_ERR_TIMEOUT; } timeout -= elapsed; if (status != AJ_OK) { return status; } *sessionId = 0; if (serviceName != NULL) { *serviceName = '\0'; } while (!clientStarted && (status == AJ_OK)) { AJ_Message msg; status = AJ_UnmarshalMsg(bus, &msg, AJ_UNMARSHAL_TIMEOUT); if ((status == AJ_ERR_TIMEOUT) && !found) { /* * Timeouts are expected until we find a name or service */ if (timeout < AJ_UNMARSHAL_TIMEOUT) { return status; } timeout -= AJ_UNMARSHAL_TIMEOUT; status = AJ_OK; continue; } if (status == AJ_ERR_NO_MATCH) { // Ignore unknown messages status = AJ_OK; continue; } if (status != AJ_OK) { AJ_ErrPrintf(("AJ_StartClient(): status=%s\n", AJ_StatusText(status))); break; } switch (msg.msgId) { case AJ_REPLY_ID(AJ_METHOD_FIND_NAME): case AJ_REPLY_ID(AJ_METHOD_FIND_NAME_BY_TRANSPORT): if (msg.hdr->msgType == AJ_MSG_ERROR) { AJ_ErrPrintf(("AJ_StartClient(): AJ_METHOD_FIND_NAME: %s\n", msg.error)); status = AJ_ERR_FAILURE; } else { uint32_t disposition; AJ_UnmarshalArgs(&msg, "u", &disposition); if ((disposition != AJ_FIND_NAME_STARTED) && (disposition != AJ_FIND_NAME_ALREADY)) { AJ_ErrPrintf(("AJ_StartClient(): AJ_ERR_FAILURE\n")); status = AJ_ERR_FAILURE; } } break; case AJ_SIGNAL_FOUND_ADV_NAME: { AJ_Arg arg; AJ_UnmarshalArg(&msg, &arg); AJ_InfoPrintf(("FoundAdvertisedName(%s)\n", arg.val.v_string)); found = TRUE; status = AJ_BusJoinSession(bus, arg.val.v_string, port, opts); } break; case AJ_SIGNAL_ABOUT_ANNOUNCE: { uint16_t version, port; AJ_InfoPrintf(("AJ_StartClient(): AboutAnnounce from (%s)\n", msg.sender)); if (!found) { found = TRUE; AJ_UnmarshalArgs(&msg, "qq", &version, &port); status = AJ_BusJoinSession(bus, msg.sender, port, opts); if (serviceName != NULL) { strncpy(serviceName, msg.sender, AJ_MAX_NAME_SIZE); serviceName[AJ_MAX_NAME_SIZE] = '\0'; } if (status != AJ_OK) { AJ_ErrPrintf(("AJ_StartClient(): BusJoinSession failed (%s)\n", AJ_StatusText(status))); } } } break; case AJ_REPLY_ID(AJ_METHOD_JOIN_SESSION): { uint32_t replyCode; if (msg.hdr->msgType == AJ_MSG_ERROR) { AJ_ErrPrintf(("AJ_StartClient(): AJ_METHOD_JOIN_SESSION: %s\n", msg.error)); status = AJ_ERR_FAILURE; } else { status = AJ_UnmarshalArgs(&msg, "uu", &replyCode, sessionId); if (replyCode == AJ_JOINSESSION_REPLY_SUCCESS) { clientStarted = TRUE; } else { AJ_ErrPrintf(("AJ_StartClient(): AJ_METHOD_JOIN_SESSION reply (%d)\n", replyCode)); status = AJ_ERR_FAILURE; } } } break; case AJ_SIGNAL_SESSION_LOST_WITH_REASON: /* * Force a disconnect */ { uint32_t id, reason; AJ_UnmarshalArgs(&msg, "uu", &id, &reason); AJ_InfoPrintf(("Session lost. ID = %u, reason = %u", id, reason)); } AJ_ErrPrintf(("AJ_StartClient(): AJ_SIGNAL_SESSION_LOST_WITH_REASON: AJ_ERR_READ\n")); status = AJ_ERR_READ; break; default: /* * Pass to the built-in bus message handlers */ AJ_InfoPrintf(("AJ_StartClient(): AJ_BusHandleBusMessage()\n")); status = AJ_BusHandleBusMessage(&msg); break; } AJ_CloseMsg(&msg); } if (status != AJ_OK && !connected) { AJ_WarnPrintf(("AJ_StartClient(): Client disconnecting from bus: status=%s\n", AJ_StatusText(status))); AJ_Disconnect(bus); } return status; }
AJ_Status AJ_StartService(AJ_BusAttachment* bus, const char* daemonName, uint32_t timeout, uint8_t connected, uint16_t port, const char* name, uint32_t flags, const AJ_SessionOpts* opts ) { AJ_Status status; AJ_Time timer; uint8_t serviceStarted = FALSE; AJ_InfoPrintf(("AJ_StartService(bus=0x%p, daemonName=\"%s\", timeout=%d., connected=%d., port=%d., name=\"%s\", flags=0x%x, opts=0x%p)\n", bus, daemonName, timeout, connected, port, name, flags, opts)); AJ_InitTimer(&timer); while (TRUE) { if (AJ_GetElapsedTime(&timer, TRUE) > timeout) { return AJ_ERR_TIMEOUT; } if (!connected) { AJ_InfoPrintf(("AJ_StartService(): AJ_FindBusAndConnect()\n")); status = AJ_FindBusAndConnect(bus, daemonName, AJ_CONNECT_TIMEOUT); if (status != AJ_OK) { AJ_WarnPrintf(("AJ_StartService(): connect failed: sleeping for %d seconds\n", AJ_CONNECT_PAUSE / 1000)); AJ_Sleep(AJ_CONNECT_PAUSE); continue; } AJ_InfoPrintf(("AJ_StartService(): connected to bus\n")); } /* * Kick things off by binding a session port */ AJ_InfoPrintf(("AJ_StartService(): AJ_BindSessionPort()\n")); status = AJ_BusBindSessionPort(bus, port, opts, 0); if (status == AJ_OK) { break; } AJ_ErrPrintf(("AJ_StartService(): AJ_Disconnect(): status=%s.\n", AJ_StatusText(status))); AJ_Disconnect(bus); } while (!serviceStarted && (status == AJ_OK)) { AJ_Message msg; status = AJ_UnmarshalMsg(bus, &msg, AJ_UNMARSHAL_TIMEOUT); if (status == AJ_ERR_NO_MATCH) { // Ignore unknown messages status = AJ_OK; continue; } if (status != AJ_OK) { AJ_ErrPrintf(("AJ_StartService(): status=%s.\n", AJ_StatusText(status))); break; } switch (msg.msgId) { case AJ_REPLY_ID(AJ_METHOD_BIND_SESSION_PORT): if (msg.hdr->msgType == AJ_MSG_ERROR) { AJ_ErrPrintf(("AJ_StartService(): AJ_METHOD_BIND_SESSION_PORT: %s\n", msg.error)); status = AJ_ERR_FAILURE; } else { AJ_InfoPrintf(("AJ_StartService(): AJ_BusRequestName()\n")); status = AJ_BusRequestName(bus, name, flags); } break; case AJ_REPLY_ID(AJ_METHOD_REQUEST_NAME): if (msg.hdr->msgType == AJ_MSG_ERROR) { AJ_ErrPrintf(("AJ_StartService(): AJ_METHOD_REQUEST_NAME: %s\n", msg.error)); status = AJ_ERR_FAILURE; } else { AJ_InfoPrintf(("AJ_StartService(): AJ_BusAdvertiseName()\n")); status = AJ_BusAdvertiseName(bus, name, AJ_TRANSPORT_ANY, AJ_BUS_START_ADVERTISING, 0); } break; case AJ_REPLY_ID(AJ_METHOD_ADVERTISE_NAME): if (msg.hdr->msgType == AJ_MSG_ERROR) { AJ_ErrPrintf(("AJ_StartService(): AJ_METHOD_ADVERTISE_NAME: %s\n", msg.error)); status = AJ_ERR_FAILURE; } else { serviceStarted = TRUE; } break; default: /* * Pass to the built-in bus message handlers */ AJ_InfoPrintf(("AJ_StartService(): AJ_BusHandleBusMessage()\n")); status = AJ_BusHandleBusMessage(&msg); break; } AJ_CloseMsg(&msg); } if (status == AJ_OK) { status = AJ_AboutInit(bus, port); } else { AJ_WarnPrintf(("AJ_StartService(): AJ_Disconnect(): status=%s\n", AJ_StatusText(status))); AJ_Disconnect(bus); } return status; }
int AJ_Main(void) { AJ_Status status = AJ_OK; uint8_t connected = FALSE; uint8_t done = FALSE; /* * One time initialization before calling any other AllJoyn APIs */ AJ_Initialize(); AJ_RegisterObjects(NULL, proxyObjects); while (!done) { AJ_Message msg; if (!connected) { const char* announceRule = "type='signal',sessionless='t',interface='org.alljoyn.About',member='Announce'"; status = AJ_FindBusAndConnect(&bus, NULL, AJ_CONNECT_TIMEOUT); if (status != AJ_OK) { AJ_WarnPrintf(("AJ_FindBusAndConnect(): failed - sleeping for %d seconds\n", AJ_CONNECT_PAUSE / 1000)); AJ_Sleep(AJ_CONNECT_PAUSE); continue; } AJ_AboutRegisterAnnounceHandlers(peerDescriptions, ArraySize(peerDescriptions)); AJ_BusSetSignalRule(&bus, announceRule, AJ_BUS_SIGNAL_ALLOW); connected = TRUE; } status = AJ_UnmarshalMsg(&bus, &msg, UNMARSHAL_TIMEOUT); if (AJ_ERR_TIMEOUT == status) { continue; } if (AJ_OK == status) { switch (msg.msgId) { case AJ_REPLY_ID(AJ_METHOD_JOIN_SESSION): if (msg.hdr->msgType != AJ_MSG_ERROR) { uint32_t result; status = AJ_UnmarshalArgs(&msg, "uu", &result, &sessionId); if (status == AJ_OK) { if (result == AJ_JOINSESSION_REPLY_SUCCESS) { AJ_AlwaysPrintf(("joined session %u\n", sessionId)); DoCat(); } else { AJ_AlwaysPrintf(("joined session rejected %d\n", result)); } } } else { AJ_ErrPrintf(("JoinSession reply was error: %s\n", msg.error)); } break; case AJ_REPLY_ID(BASIC_CLIENT_CAT): if (msg.hdr->msgType != AJ_MSG_ERROR) { AJ_Arg arg; status = AJ_UnmarshalArg(&msg, &arg); if (AJ_OK == status) { AJ_AlwaysPrintf(("cat returned \"%s\"\n", arg.val.v_string)); if (!waitVar) { done = TRUE; } } } else { AJ_ErrPrintf(("Reply was error: %s\n", msg.error)); } break; case AJ_SIGNAL_MP_SESSION_CHANGED_WITH_REASON: { uint32_t sessId; const char* peer; uint32_t added; uint32_t reason; status = AJ_UnmarshalArgs(&msg, "usbu", &sessId, &peer, &added, &reason); if (added) { AJ_AlwaysPrintf(("Member \"%s\" added to session %u\n", peer, sessId)); } else { AJ_AlwaysPrintf(("Member \"%s\" removed from session %u\n", peer, sessId)); } } break; case AJ_SIGNAL_SESSION_LOST_WITH_REASON: AJ_AlwaysPrintf(("Session lost\n")); break; default: /* Pass to the built-in handlers. */ status = AJ_BusHandleBusMessage(&msg); break; } } /* Messages MUST be discarded to free resources. */ AJ_CloseMsg(&msg); if (status == AJ_ERR_READ) { AJ_AlwaysPrintf(("Connection lost\n")); AJ_Disconnect(&bus); exit(0); } } AJ_AlwaysPrintf(("Basic client exiting with status %d.\n", status)); return status; }
int AJ_Main(void) { AJ_Status status = AJ_OK; uint8_t isUnmarshalingSuccessful = FALSE; AJSVC_ServiceStatus serviceStatus; AJ_Message msg; uint8_t forcedDisconnnect = FALSE; uint8_t rebootRequired = FALSE; uint8_t sent = FALSE; AJ_Initialize(); AJ_AboutSetIcon(aboutIconContent, aboutIconContentSize, aboutIconMimetype, aboutIconUrl); status = PropertyStore_Init(); if (status != AJ_OK) { goto Exit; } status = NotificationProducer_Init(); if (status != AJ_OK) { goto Exit; } SetBusAuthPwdCallback(MyBusAuthPwdCB); while (TRUE) { status = AJ_OK; serviceStatus = AJSVC_SERVICE_STATUS_NOT_HANDLED; if (!isBusConnected) { status = AJSVC_RoutingNodeConnect(&busAttachment, ROUTING_NODE_NAME, AJAPP_CONNECT_TIMEOUT, AJAPP_CONNECT_PAUSE, AJAPP_BUS_LINK_TIMEOUT, &isBusConnected); if (!isBusConnected) { // Failed to connect to Routing Node? continue; // Retry establishing connection to Routing Node } } status = AJApp_ConnectedHandler(&busAttachment); if (status == AJ_OK) { status = AJ_UnmarshalMsg(&busAttachment, &msg, AJAPP_UNMARSHAL_TIMEOUT); isUnmarshalingSuccessful = (status == AJ_OK); if (status == AJ_ERR_TIMEOUT) { if (AJ_ERR_LINK_TIMEOUT == AJ_BusLinkStateProc(&busAttachment)) { status = AJ_ERR_READ; // something's not right. force disconnect } else { // nothing on bus, do our own thing SendNotification(&busAttachment); sent = TRUE; } } if (isUnmarshalingSuccessful) { if (serviceStatus == AJSVC_SERVICE_STATUS_NOT_HANDLED) { serviceStatus = AJApp_MessageProcessor(&busAttachment, &msg, &status); } if (serviceStatus == AJSVC_SERVICE_STATUS_NOT_HANDLED) { //Pass to the built-in bus message handlers status = AJ_BusHandleBusMessage(&msg); } AJ_NotifyLinkActive(); } //Unmarshaled messages must be closed to free resources AJ_CloseMsg(&msg); } if (sent) { AJ_Sleep(10000); // Give the notification message a chance to reach a peer Consumer before exiting. AJApp_DisconnectHandler(&busAttachment, TRUE); AJSVC_RoutingNodeDisconnect(&busAttachment, TRUE, AJAPP_SLEEP_TIME, AJAPP_SLEEP_TIME, NULL); break; } if (status == AJ_ERR_READ || status == AJ_ERR_RESTART || status == AJ_ERR_RESTART_APP) { if (isBusConnected) { forcedDisconnnect = (status != AJ_ERR_READ); rebootRequired = (status == AJ_ERR_RESTART_APP); AJApp_DisconnectHandler(&busAttachment, forcedDisconnnect); AJSVC_RoutingNodeDisconnect(&busAttachment, forcedDisconnnect, AJAPP_SLEEP_TIME, AJAPP_SLEEP_TIME, &isBusConnected); if (rebootRequired) { AJ_Reboot(); } } } } // while (TRUE) return 0; Exit: return (1); }
int AJ_Main() { AJ_Status status; while (1) { int windows = 1 << (rand() % 3); // randomize window width 1,2,4 int blocksize = 50 + (rand() % 1000); // randomize packet size 50 - 1050 AJ_AlwaysPrintf(("Windows:%i Blocksize:%i\n", windows, blocksize)); txBuffer = (uint8_t*) AJ_Malloc(blocksize); rxBuffer = (uint8_t*) AJ_Malloc(blocksize); memset(txBuffer, 0x41, blocksize); memset(rxBuffer, 'r', blocksize); #ifdef READTEST status = AJ_SerialInit("/dev/ttyUSB0", BITRATE, windows, blocksize); #else status = AJ_SerialInit("/dev/ttyUSB1", BITRATE, windows, blocksize); #endif AJ_AlwaysPrintf(("serial init was %u\n", status)); if (status != AJ_OK) { continue; // init failed perhaps from bad parameters, start the loop again } // Change the buffer transmission function to one that fuzzes the output. AJ_SetTxSerialTransmit(&FuzzBuffer); #ifdef READTEST AJ_Sleep(2000); // wait for the writing side to be running, this should test the queuing of data. // try to read everything at once int i = 0; while (1) { AJ_SerialRecv(rxBuffer, blocksize, 50000, NULL); } AJ_DumpBytes("Post serial recv", rxBuffer, blocksize); AJ_Sleep(500); #else AJ_Sleep(5000); int i = 0; while (1) { // change the packet to be sent every time through the loop. memset(txBuffer, 0x41 + (i % 26), blocksize); memset(rxBuffer, 0x41 + (i % 26), blocksize); AJ_SerialSend(txBuffer, blocksize); ++i; if (i % 20 == 0) { AJ_AlwaysPrintf(("Hit iteration %d\n", i)); break; } AJ_SerialRecv(rxBuffer, blocksize, 5000, NULL); } AJ_AlwaysPrintf(("post serial send\n")); #endif // clean up and start again AJ_SerialShutdown(); AJ_Free(txBuffer); AJ_Free(rxBuffer); } return(0); }
AJ_Status AJ_StartService2(AJ_BusAttachment* bus, const char* daemonName, uint32_t timeout, uint8_t connected, uint16_t port, const char* name, uint32_t flags, const AJ_SessionOpts* opts ) { AJ_Status status; AJ_Time timer; uint8_t serviceStarted = FALSE; uint8_t initial = TRUE; AJ_InitTimer(&timer); while (TRUE) { if (AJ_GetElapsedTime(&timer, TRUE) > timeout) { return AJ_ERR_TIMEOUT; } if (!initial || !connected) { initial = FALSE; AJ_InfoPrintf(("Attempting to connect to bus\n")); status = AJ_Connect(bus, daemonName, CONNECT_TIMEOUT); if (status != AJ_OK) { AJ_WarnPrintf(("Failed to connect to bus sleeping for %d seconds\n", CONNECT_PAUSE / 1000)); AJ_Sleep(CONNECT_PAUSE); continue; } AJ_InfoPrintf(("AllJoyn service connected to bus\n")); } /* * Kick things off by binding a session port */ status = AJ_BusBindSessionPort(bus, port, opts); if (status == AJ_OK) { break; } AJ_ErrPrintf(("Failed to send bind session port message\n")); AJ_Disconnect(bus); } while (!serviceStarted && (status == AJ_OK)) { AJ_Message msg; AJ_GetElapsedTime(&timer, TRUE); status = AJ_UnmarshalMsg(bus, &msg, UNMARSHAL_TIMEOUT); /* * TODO This is a temporary hack to work around buggy select imlpementations */ if (status == AJ_ERR_TIMEOUT) { if (AJ_GetElapsedTime(&timer, TRUE) < UNMARSHAL_TIMEOUT) { AJ_WarnPrintf(("Spurious timeout error - continuing\n")); status = AJ_OK; continue; } } if (status != AJ_OK) { break; } switch (msg.msgId) { case AJ_REPLY_ID(AJ_METHOD_BIND_SESSION_PORT): if (msg.hdr->msgType == AJ_MSG_ERROR) { status = AJ_ERR_FAILURE; } else { status = AJ_BusRequestName(bus, name, flags); } break; case AJ_REPLY_ID(AJ_METHOD_REQUEST_NAME): if (msg.hdr->msgType == AJ_MSG_ERROR) { status = AJ_ERR_FAILURE; } else { status = AJ_BusAdvertiseName(bus, name, AJ_TRANSPORT_ANY, AJ_BUS_START_ADVERTISING); } break; case AJ_REPLY_ID(AJ_METHOD_ADVERTISE_NAME): if (msg.hdr->msgType == AJ_MSG_ERROR) { status = AJ_ERR_FAILURE; } else { serviceStarted = TRUE; AJ_BusSetSignalRule2(bus, "NameOwnerChanged", "org.freedesktop.DBus", AJ_BUS_SIGNAL_ALLOW); } break; default: /* * Pass to the built-in bus message handlers */ status = AJ_BusHandleBusMessage(&msg); break; } AJ_CloseMsg(&msg); } if (status != AJ_OK) { AJ_WarnPrintf(("AllJoyn disconnect bus status=%s\n", AJ_StatusText(status))); AJ_Disconnect(bus); } return status; }
int AJ_Main() { AJ_Status status = AJ_OK; AJ_BusAttachment bus; uint8_t connected = FALSE; uint32_t sessionId = 0; /* * One time initialization before calling any other AllJoyn APIs */ AJ_Initialize(); AJ_PrintXML(AppObjects); AJ_RegisterObjects(AppObjects, NULL); SetBusAuthPwdCallback(MyBusAuthPwdCB); while (TRUE) { AJ_Message msg; if (!connected) { status = AJ_StartService(&bus, NULL, CONNECT_TIMEOUT, FALSE, ServicePort, ServiceName, AJ_NAME_REQ_DO_NOT_QUEUE, NULL); if (status != AJ_OK) { continue; } AJ_InfoPrintf(("StartService returned AJ_OK\n")); AJ_InfoPrintf(("Connected to Daemon:%s\n", AJ_GetUniqueName(&bus))); connected = TRUE; #ifdef SECURE_OBJECT status = AJ_SetObjectFlags("/org/alljoyn/alljoyn_test", AJ_OBJ_FLAG_SECURE, 0); if (status != AJ_OK) { AJ_ErrPrintf(("Error calling AJ_SetObjectFlags.. [%s] \n", AJ_StatusText(status))); return -1; } #endif #if defined(SECURE_INTERFACE) || defined(SECURE_OBJECT) /* Register a callback for providing bus authentication password */ AJ_BusSetPasswordCallback(&bus, PasswordCallback); AJ_BusEnableSecurity(&bus, suites, numsuites); AJ_BusSetAuthListenerCallback(&bus, AuthListenerCallback); #endif /* Configure timeout for the link to the daemon bus */ AJ_SetBusLinkTimeout(&bus, 60); // 60 seconds } status = AJ_UnmarshalMsg(&bus, &msg, UNMARSHAL_TIMEOUT); if (AJ_ERR_TIMEOUT == status && AJ_ERR_LINK_TIMEOUT == AJ_BusLinkStateProc(&bus)) { status = AJ_ERR_READ; } if (status != AJ_OK) { if (status == AJ_ERR_TIMEOUT) { AppDoWork(); continue; } } if (status == AJ_OK) { switch (msg.msgId) { case AJ_REPLY_ID(AJ_METHOD_ADD_MATCH): if (msg.hdr->msgType == AJ_MSG_ERROR) { AJ_InfoPrintf(("Failed to add match\n")); status = AJ_ERR_FAILURE; } else { status = AJ_OK; } break; case AJ_METHOD_ACCEPT_SESSION: { uint16_t port; char* joiner; AJ_UnmarshalArgs(&msg, "qus", &port, &sessionId, &joiner); if (port == ServicePort) { status = AJ_BusReplyAcceptSession(&msg, TRUE); AJ_InfoPrintf(("Accepted session session_id=%u joiner=%s\n", sessionId, joiner)); } else { status = AJ_BusReplyAcceptSession(&msg, FALSE); AJ_InfoPrintf(("Accepted rejected session_id=%u joiner=%s\n", sessionId, joiner)); } } break; case APP_MY_PING: status = AppHandlePing(&msg); break; case APP_GET_PROP: status = AJ_BusPropGet(&msg, PropGetHandler, NULL); break; case APP_SET_PROP: status = AJ_BusPropSet(&msg, PropSetHandler, NULL); if (status == AJ_OK) { AJ_InfoPrintf(("Property successfully set to %d.\n", propVal)); } else { AJ_InfoPrintf(("Property set attempt unsuccessful. Status = 0x%04x.\n", status)); } break; case AJ_SIGNAL_SESSION_LOST_WITH_REASON: { uint32_t id, reason; AJ_UnmarshalArgs(&msg, "uu", &id, &reason); AJ_InfoPrintf(("Session lost. ID = %u, reason = %u", id, reason)); if (CancelAdvertiseName) { status = AJ_BusAdvertiseName(&bus, ServiceName, AJ_TRANSPORT_ANY, AJ_BUS_START_ADVERTISING, 0); } status = AJ_ERR_SESSION_LOST; } break; case AJ_SIGNAL_SESSION_JOINED: if (CancelAdvertiseName) { status = AJ_BusAdvertiseName(&bus, ServiceName, AJ_TRANSPORT_ANY, AJ_BUS_STOP_ADVERTISING, 0); } break; case AJ_REPLY_ID(AJ_METHOD_CANCEL_ADVERTISE): case AJ_REPLY_ID(AJ_METHOD_ADVERTISE_NAME): if (msg.hdr->msgType == AJ_MSG_ERROR) { status = AJ_ERR_FAILURE; } break; case APP_MY_SIGNAL: AJ_InfoPrintf(("Received my_signal\n")); status = AJ_OK; if (ReflectSignal) { AJ_Message out; AJ_MarshalSignal(&bus, &out, APP_MY_SIGNAL, msg.destination, msg.sessionId, 0, 0); AJ_MarshalArgs(&out, "a{ys}", 0, NULL); AJ_DeliverMsg(&out); AJ_CloseMsg(&out); } break; default: /* * Pass to the built-in bus message handlers */ status = AJ_BusHandleBusMessage(&msg); break; } // Any received packets indicates the link is active, so call to reinforce the bus link state AJ_NotifyLinkActive(); } /* * Unarshaled messages must be closed to free resources */ AJ_CloseMsg(&msg); if ((status == AJ_ERR_READ) || (status == AJ_ERR_LINK_DEAD)) { AJ_InfoPrintf(("AllJoyn disconnect\n")); AJ_InfoPrintf(("Disconnected from Daemon:%s\n", AJ_GetUniqueName(&bus))); AJ_Disconnect(&bus); connected = FALSE; /* * Sleep a little while before trying to reconnect */ AJ_Sleep(10 * 1000); } } AJ_WarnPrintf(("svclite EXIT %d\n", status)); return status; }
AJ_Status AJ_RunAllJoynService(AJ_BusAttachment* bus, AllJoynConfiguration* config) { uint8_t connected = FALSE; AJ_Status status = AJ_OK; while (TRUE) { AJ_Time start = { 0, 0 }; AJ_Message msg; uint32_t now; // get the next timeout //Timer* timer = GetNextTimeout(); uint32_t next; // wait forever uint32_t timeout = (uint32_t) -1; if (!connected) { status = AJ_StartService2( bus, config->daemonName, config->connect_timeout, config->connected, config->session_port, config->service_name, config->flags, config->opts); if (status != AJ_OK) { continue; } AJ_InfoPrintf(("StartService returned AJ_OK\n")); AJ_InfoPrintf(("Connected to Daemon:%s\n", AJ_GetUniqueName(bus))); connected = TRUE; /* Register a callback for providing bus authentication password */ AJ_BusSetPasswordCallback(bus, config->password_callback); /* Configure timeout for the link to the daemon bus */ AJ_SetBusLinkTimeout(bus, config->link_timeout); if (config->connection_handler != NULL) { (config->connection_handler)(connected); } } // absolute time in milliseconds now = AJ_GetElapsedTime(&start, FALSE); next = RunExpiredTimers(now); if (next != (uint32_t) -1) { // if no timers running, wait forever timeout = next; } status = AJ_UnmarshalMsg(bus, &msg, min(500, timeout)); if (AJ_ERR_TIMEOUT == status && AJ_ERR_LINK_TIMEOUT == AJ_BusLinkStateProc(bus)) { status = AJ_ERR_READ; } if (status == AJ_ERR_TIMEOUT) { // go back around and handle the expired timers continue; } if (status == AJ_OK) { uint8_t handled = FALSE; const MessageHandlerEntry* message_entry = config->message_handlers; const PropHandlerEntry* prop_entry = config->prop_handlers; // check the user's handlers first. ANY message that AllJoyn can handle is override-able. while (handled != TRUE && message_entry->msgid != 0) { if (message_entry->msgid == msg.msgId) { if (msg.hdr->msgType == AJ_MSG_METHOD_CALL) { // build a method reply AJ_Message reply; status = AJ_MarshalReplyMsg(&msg, &reply); if (status == AJ_OK) { status = (message_entry->handler)(&msg, &reply); } if (status == AJ_OK) { status = AJ_DeliverMsg(&reply); } } else { // call the handler! status = (message_entry->handler)(&msg, NULL); } handled = TRUE; } ++message_entry; } // we need to check whether this is a property getter or setter. // these are stored in an array because multiple getters and setters can exist if running more than one bus object while (handled != TRUE && prop_entry->msgid != 0) { if (prop_entry->msgid == msg.msgId) { // extract the method from the ID; GetProperty or SetProperty uint32_t method = prop_entry->msgid & 0x000000FF; if (method == AJ_PROP_GET) { status = AJ_BusPropGet(&msg, prop_entry->callback, prop_entry->context); } else if (method == AJ_PROP_SET) { status = AJ_BusPropSet(&msg, prop_entry->callback, prop_entry->context); } else { // this should never happen!!! AJ_ASSERT(!"Invalid property method"); } handled = TRUE; } ++prop_entry; } // handler not found! if (handled == FALSE) { if (msg.msgId == AJ_METHOD_ACCEPT_SESSION) { uint8_t accepted = (config->acceptor)(&msg); status = AJ_BusReplyAcceptSession(&msg, accepted); } else { status = AJ_BusHandleBusMessage(&msg); } } // Any received packets indicates the link is active, so call to reinforce the bus link state AJ_NotifyLinkActive(); } /* * Unarshaled messages must be closed to free resources */ AJ_CloseMsg(&msg); if (status == AJ_ERR_READ) { AJ_InfoPrintf(("AllJoyn disconnect\n")); AJ_InfoPrintf(("Disconnected from Daemon:%s\n", AJ_GetUniqueName(bus))); AJ_Disconnect(bus); connected = FALSE; if (config->connection_handler != NULL) { (config->connection_handler)(connected); } /* * Sleep a little while before trying to reconnect */ AJ_Sleep(10 * 1000); } } // this will never actually return! return AJ_OK; }
void delay(int msec) { // console_write("DELAY%d\n", sec); AJ_Sleep(msec); }