//The setup function is called once at startup of the sketch void setup() { // Add your initialization code here // Note : This will initialize Serial port on Arduino at 115200 bauds OC_LOG_INIT(); OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); uint16_t port = OC_WELL_KNOWN_PORT; // Connect to Ethernet or WiFi network if (ConnectToNetwork() != 0) { OC_LOG(ERROR, TAG, PCF("Unable to connect to network")); return; } // Initialize the OC Stack in Server mode if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK) { OC_LOG(ERROR, TAG, PCF("OCStack init error")); return; } // Declare and create the example resource: Light createLightResource(); }
//**************************************************************************** // //! \brief OOB Application Main Task - Initializes SimpleLink Driver and //! Handles HTTP Requests //! \param[in] pvParameters is the data passed to the Task //! //! \return None // //**************************************************************************** static void OOBTask(void *pvParameters) { //Read Device Mode Configuration ReadDeviceConfiguration(); //Connect to Network ConnectToNetwork(); //Handle Async Events while(1) { //LED Actions if(g_ucLEDStatus == LED_ON) { GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(500); } if(g_ucLEDStatus == LED_OFF) { GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(500); } if(g_ucLEDStatus==LED_BLINK) { GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(500); GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(500); } } }
//The setup function is called once at startup of the sketch void setup() { // Add your initialization code here // Note : This will initialize Serial port on Arduino at 115200 bauds OC_LOG_INIT(); OC_LOG(DEBUG, TAG, ("Demoserver is starting...")); // Connect to Ethernet or WiFi network if (ConnectToNetwork() != 0) { OC_LOG(ERROR, TAG, ("Unable to connect to network")); return; } // Initialize the OC Stack in Server mode if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) { OC_LOG(ERROR, TAG, ("OCStack init error")); return; } // Initialize Grove related Devices sensor_init(); led_init(); lcd_init(); buzzer_init(); button_init(); // Declare and create the resource: grove createDemoResource(); }
//The setup function is called once at startup of the sketch void setup() { pinMode(dht11_pin, OUTPUT); digitalWrite(dht11_pin, HIGH); // Add your initialization code here OC_LOG_INIT(); OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); uint16_t port = OC_WELL_KNOWN_PORT; // Connect to Ethernet or WiFi network if (ConnectToNetwork() != 0) { OC_LOG(ERROR, TAG, "Unable to connect to network"); return; } // Initialize the OC Stack in Server mode if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK) { OC_LOG(ERROR, TAG, PCF("OCStack init error")); return; } OCStartPresence(60); // Declare and create the example resource: TH createTHResource(); }
//The setup function is called once at startup of the sketch void setup() { // Add your initialization code here // Note : This will initialize Serial port on Arduino at 115200 bauds OC_LOG_INIT(); pinMode(SDCARD_CS, OUTPUT); digitalWrite(SDCARD_CS, HIGH); //Deselect the SD card pinMode(FANPIN, OUTPUT); digitalWrite(FANPIN, LOW); Serial.println("OCServer is starting..."); unsigned int port = OC_WELL_KNOWN_PORT; // Connect to Ethernet or WiFi network if (ConnectToNetwork() != 0) { Serial.println("Unable to connect to network"); return; } Serial.println("Connected to Ethernet network"); // Initialize the OC Stack in Server mode if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK) { Serial.println("OCStack init error"); return; } Serial.println("OC Initialized"); // Declare and create the resource: Fan createFanResource(); }
//**************************************************************************** // //! \brief Handles HTTP Server Task //! //! \param[in] pvParameters is the data passed to the Task //! //! \return None // //**************************************************************************** static void HTTPServerTask(void *pvParameters) { long lRetVal = -1; InitializeAppVariables(); // // Following function configure the device to default state by cleaning // the persistent settings stored in NVMEM (viz. connection profiles & // policies, power policy etc) // // Applications may choose to skip this step if the developer is sure // that the device is in its default state at start of applicaton // // Note that all profiles and persistent settings that were done on the // device will be lost // lRetVal = ConfigureSimpleLinkToDefaultState(); if(lRetVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == lRetVal) UART_PRINT("Failed to configure the device in its default state\n\r"); LOOP_FOREVER(); } UART_PRINT("Device is configured in default state \n\r"); memset(g_ucSSID,'\0',AP_SSID_LEN_MAX); //Read Device Mode Configuration ReadDeviceConfiguration(); //Connect to Network lRetVal = ConnectToNetwork(); //Stop Internal HTTP Server lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); if(lRetVal < 0) { ERR_PRINT(lRetVal); LOOP_FOREVER(); } //Start Internal HTTP Server lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID); if(lRetVal < 0) { ERR_PRINT(lRetVal); LOOP_FOREVER(); } //Handle Async Events while(1) { } }
//The setup function is called once at startup of the sketch void setup() { // Add your initialization code here // Note : This will initialize Serial port on Arduino at 115200 bauds OIC_LOG_INIT(); OIC_LOG(DEBUG, TAG, ("OCServer is starting...")); // Connect to Ethernet or WiFi network if (ConnectToNetwork() != 0) { Serial.print("Unable to connect to Network"); OIC_LOG(ERROR, TAG, ("Unable to connect to network")); return; } // Initialize the OC Stack in Server mode if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) { OIC_LOG(ERROR, TAG, ("OCStack init error")); return; } // DEBUG PIN pinMode(LED_PIN, OUTPUT); // Button resource OCBaseResourceT *temperatureResource = createResource("/a/temperatureSensor", OIC_DEVICE_SENSOR, OC_RSRVD_INTERFACE_DEFAULT, (OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_ACTIVE), temperatureIOHandler); temperatureResource->name = "LM35 Temperature Sensor"; addType(temperatureResource, OIC_TYPE_TEMPERATURE); // READ only interface addInterface(temperatureResource, OC_RSRVD_INTERFACE_READ); OCIOPort port; port.pin = TEMPERATURE_PIN_IN; port.type = IN; // Setup ADC analogReference(INTERNAL1V1); ResourceData data; data.str = "0.0"; addAttribute(&temperatureResource->attribute, "temperature", data, STRING, &port); printResource(temperatureResource); }
ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass, NetworkEventCallback cb) { char *fwVersion; int status = WL_IDLE_STATUS; int res; // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { OC_LOG(ERROR, ES_NH_TAG, "WiFi shield not present"); return ES_ERROR; } // Verify that WiFi Shield is running the firmware with all UDP fixes fwVersion = WiFi.firmwareVersion(); OC_LOG_V(INFO, ES_NH_TAG, "WiFi Shield Firmware version %s", fwVersion); if (strncmp(fwVersion, ARDUINO_WIFI_SHIELD_UDP_FW_VER, sizeof(ARDUINO_WIFI_SHIELD_UDP_FW_VER)) != 0) { OC_LOG(DEBUG, ES_NH_TAG, "!!!!! Upgrade WiFi Shield Firmware version !!!!!!"); //return ES_ERROR; } OC_LOG_V(INFO, ES_NH_TAG, "Finding SSID: %s", ssid); while (findNetwork(ssid) == 0) // found { delay(1000); } if (cb != NULL) { cb(ES_NETWORKFOUND); } if (WiFi.status() == WL_CONNECTED) WiFi.disconnect(); res = ConnectToNetwork(ssid, pass); if (res == 0) { return ES_NETWORKCONNECTED; } else { return ES_NETWORKNOTCONNECTED; } }
//The setup function is called once at startup of the sketch void setup() { // Add your initialization code here // Note : This will initialize Serial port on Arduino at 115200 bauds OIC_LOG_INIT(); OIC_LOG(DEBUG, TAG, ("OCServer is starting...")); // Connect to Ethernet or WiFi network if (ConnectToNetwork() != 0) { Serial.print("Unable to connect to Network"); OIC_LOG(ERROR, TAG, ("Unable to connect to network")); return; } // Initialize the OC Stack in Server mode if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) { OIC_LOG(ERROR, TAG, ("OCStack init error")); return; } // DEBUG PIN pinMode(LED_PIN, OUTPUT); // Button resource OCBaseResourceT *buttonResource = createResource("/a/button", OIC_DEVICE_BUTTON, OC_RSRVD_INTERFACE_DEFAULT, (OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW), buttonIOHandler); buttonResource->name = "Marks Button"; OCIOPort port; port.pin = TEST_BUT_PIN; port.type = IN; ResourceData data; data.b = false; addAttribute(&buttonResource->attribute, "state", data, BOOL, &port); printResource(buttonResource); }
//The setup function is called once at startup of the sketch void setup() { Serial.begin(115200); // Add your initialization code here OC_LOG_INIT(); OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); // uint16_t port = OC_WELL_KNOWN_PORT; // Connect to Ethernet or WiFi network if (ConnectToNetwork() != 0) { OC_LOG(ERROR, TAG, "Unable to connect to network"); return; } // Initialize the OC Stack in Server mode if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK) { OC_LOG(ERROR, TAG, PCF("OCStack init error")); return; } OCStartPresence(60); // Declare and create the example resource createResource(); // This call displays the amount of free SRAM available on Arduino PrintArduinoMemoryStats(); #if (ARDUINO == 0) ble.init( (long)115200, BLE_MASTER, trackeeID); #elif (ARDUINO == 1) ble.init( (long)115200, BLE_SLAVER, slaveList[0]); #elif (ARDUINO == 2) ble.init( (long)115200, BLE_SLAVER, slaveList[1]); #endif // ble.StatusRead(); OC_LOG_V(INFO, TAG, "Program Start-\r\n"); }
//***************************************************************************** // //! Network Task //! //! \param pvParameters - Parameters to the task's entry function //! //! \return None //! //***************************************************************************** void Network( void *pvParameters ) { long lRetVal = -1; //Initialize Global Variable InitializeAppVariables(); //Connect to Network lRetVal = ConnectToNetwork(); if(lRetVal < 0) { UART_PRINT("Failed to establish connection w/ an AP \n\r"); LOOP_FOREVER(); } //Cread UDP Socket and Bind to Local IP Address lRetVal = CreateUdpServer(&g_UdpSock); if(lRetVal < 0) { UART_PRINT("Failed to Create UDP Server \n\r"); LOOP_FOREVER(); } #ifdef MULTICAST //Add to Multicast Group lRetVal = ReceiveMulticastPacket(); if(lRetVal < 0) { UART_PRINT("Failed to Create UDP Server \n\r"); LOOP_FOREVER(); } //Delete the Networking Task as Service Discovery is not needed osi_TaskDelete(&g_NetworkTask); #else //Discover CC3200 Audio Devices mDNS_Task(); #endif }
//The setup function is called once at startup of the sketch void setup() { // Add your initialization code here // Note : This will initialize Serial port on Arduino at 115200 bauds // OC_LOG_INIT(); Serial.begin(115200); Serial1.begin(115200); // OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); // OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); // Connect to Ethernet or WiFi network if (ConnectToNetwork() != 0) { // OC_LOG(ERROR, TAG, PCF("Unable to connect to network")); return; } // Initialize the OC Stack in Server mode if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) { // OC_LOG(ERROR, TAG, PCF("OCStack init error")); return; } // Declare and create the example resource: Light createLightResource(); speaker.state = 0; speaker.volume = 40; speaker.next_song = 1; speaker.present_song = 1; speaker.time = 0; //OC_LOG(DEBUG, TAG, PCF("소라 놋북 터진 날 15.07.31 ...")); }
//**************************************************************************** // //! \brief OOB Application Main Task - Initializes SimpleLink Driver and //! Handles HTTP Requests //! \param[in] pvParameters is the data passed to the Task //! //! \return None // //**************************************************************************** static void OOBTask(void *pvParameters) { long lRetVal = -1; //Read Device Mode Configuration ReadDeviceConfiguration(); //Connect to Network lRetVal = ConnectToNetwork(); if(lRetVal < 0) { ERR_PRINT(lRetVal); LOOP_FOREVER(); } //Handle Async Events while(1) { //LED Actions if(g_ucLEDStatus == LED_ON) { GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(500); } if(g_ucLEDStatus == LED_OFF) { GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(500); } if(g_ucLEDStatus==LED_BLINK) { GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(500); GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(500); } } }
void main() { //temp variable useful for loops int i; //temp variables for serial communication int c; unsigned int bytesRead; //variables for wifi communication int newMode; int interfacePacketRecieved; int network; #GLOBAL_INIT { setMode(ROBOT_ENABLE); rx.state = WAIT; /*********************** Initialization of Packets ***********************/ // Initialize software version aPacket[1] = SOFTWARE_VERSION_ID >> 8; aPacket[2] = SOFTWARE_VERSION_ID & 0xFF; // Initialize UDP response packets gPacket[0] = 'G'; gPacket[1] = ROBOTMODE; gPacket[2] = SOFTWARE_VERSION_ID >> 8; gPacket[3] = SOFTWARE_VERSION_ID & 0xFF; gPacket[4] = 0; // user version id gPacket[5] = 0; gPacket[6] = 0; // battery voltage gPacket[7] = 0; // Initialize J packet values to 0 memset(jPacket, 0, J_PACKET_LENGTH); // Initialize X default packet (autonomous mode dummy packet) to 0 memset(xPacketDefaultValues, 0, X_PACKET_LENGTH); } ///////////////////////////////////////////////////////////////////////// // Configure Port D -- Leave PD4-PD7 untouched (used for other purposes) ///////////////////////////////////////////////////////////////////////// WrPortI(PDCR, &PDCRShadow, RdPortI(PDCR) & 0xF0); // clear bits to pclk/2 WrPortI(PDFR, &PDFRShadow, RdPortI(PDFR) & 0xF0); // no special functions WrPortI(PDDCR, &PDDCRShadow, RdPortI(PDDCR) & 0xF0); // clear bits to drive // high and low WrPortI(PDDR, &PDDRShadow, RdPortI(PDDR) | 0x0D); // set outputs high WrPortI(PDDDR, &PDDDRShadow, RdPortI(PDDDR) | 0x0D); // set inputs and // outputs //Initialize serial communication serialInit(); //Initialize controls as neutral //memset(interface.axis, 127, sizeof(interface.axis)); //memset(interface.btn, 0, sizeof(interface.btn)); //Decide which router to connect to if (BitRdPortI(PDDR, 1) == 1) { //USER settings BitWrPortI(PDDR, &PDDRShadow, 1, 0); // turn off user LED network = USER_ROUTER; printf("USER\n"); } else { //COMPETITION Settings BitWrPortI(PDDR, &PDDRShadow, 0, 0); // turn on user LED network = COMP_ROUTER; setMode(ROBOT_DISABLE); printf("COMPETITION\n"); } // */ printf("Robot Mode: %d \n", ROBOTMODE); // Wait for X2 handshake (to learn team #) before attempting connection printf("Waiting for X2...\n"); while (x2Connection != X2_CONN_ESTABLISHED) { if ((c = serCgetc()) != -1) { byteReceived(c); } } printf("X2 connection established\n"); sendPacket('F', F_PACKET_LENGTH, fPacket); ConnectToNetwork(network, teamNo); //Main Loop while(1) { // Receive field, interface & X2 reply packets as they come costate { //Check to see if we have new field communication if (udpRecieveFieldPacket()) { newMode = ProcessFieldPacket(); if (newMode != -1) { // Set robot mode flags setMode(newMode); // If disable flag set: zero motor values if (newMode & ROBOT_DISABLE) disableRobot(); // Send X2 packet with new mode flags sendPacket('F', F_PACKET_LENGTH, fPacket); // Send back response packet with our robot mode flags // and code versions sendFieldSocket(gPacket, G_PACKET_LENGTH); //printf("Robot Mode: %d \n", ROBOTMODE); } } //Check to see if we have new field commuication, and we can use it if (udpRecieveInterfacePacket()) { if (interBuf[0] == 'I') { udpNewData = TRUE; } } // Receive X2 serial data in bursts of up to X2_RX_BURST_LENGTH bytesRead = 0; while ((c = serCgetc()) != -1 && bytesRead <= X2_RX_BURST_LENGTH) { byteReceived((unsigned char)c); bytesRead += 1; } } // */ // Time out if no UDP packets received after 500 ms // TODO: Update the interface to send an enable packet. In the meantime // this feature is only activated in competition mode costate { if (network == COMP_ROUTER) { waitfor( udpNewData || DelayMs(500) ); if (!udpNewData) disableRobot(); } } // Send X2 packets costate { // FOR TESTING // udpNewData = TRUE; waitfor( udpNewData ); // Check that disable bit is not set if (!(ROBOTMODE & ROBOT_DISABLE)) { // If in autonomous mode, send a dummy 'X' packet to keep the // motor refreshing, but do not send actual joystick values if (ROBOTMODE & ROBOT_AUTON) sendPacket('X', X_PACKET_LENGTH, xPacketDefaultValues); // Otherwise in enable mode, send the received joystick values else sendPacket('X', X_PACKET_LENGTH, interBuf+1); x2OkToSend = FALSE; udpNewData = FALSE; // Wait for reply before sending another packet waitfor( x2OkToSend || DelayMs(500) ); if (!x2OkToSend) { // no reply came within 500ms timeout //printf("disable"); disableRobot(); } } } costate { // If auto bit is set, blink the LED fast if (ROBOTMODE & ROBOT_AUTON) { BitWrPortI(PDDR, &PDDRShadow, 0, 0); // turn on user LED waitfor (DelayMs(100)); BitWrPortI(PDDR, &PDDRShadow, 1, 0); // turn off user LED waitfor (DelayMs(100)); // Otherwise if disable bit is set, blink the LED slowly } else if (ROBOTMODE & ROBOT_DISABLE) { BitWrPortI(PDDR, &PDDRShadow, 0, 0); // turn on user LED waitfor (DelayMs(500)); BitWrPortI(PDDR, &PDDRShadow, 1, 0); // turn off user LED waitfor (DelayMs(500)); } } } // while(1) } // main
ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass, NetworkEventCallback cb) { char *fwVersion; int status = WL_IDLE_STATUS; int res; // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { OIC_LOG(ERROR, ES_NH_TAG, "WiFi shield not present"); return ES_ERROR; } // Verify that WiFi Shield is running the firmware with all UDP fixes fwVersion = WiFi.firmwareVersion(); OIC_LOG_V(INFO, ES_NH_TAG, "WiFi Shield Firmware version %s", fwVersion); if (strncmp(fwVersion, ARDUINO_WIFI_SHIELD_UDP_FW_VER, sizeof(ARDUINO_WIFI_SHIELD_UDP_FW_VER)) != 0) { OIC_LOG(DEBUG, ES_NH_TAG, "!!!!! Upgrade WiFi Shield Firmware version !!!!!!"); return ES_ERROR; } //Retry counter is reset everytime the ConnectToWiFiNetwork is invoked g_retryCounter = 0; OIC_LOG_V(INFO, ES_NH_TAG, "Finding SSID: %s", ssid); while ((findNetwork(ssid) == 0) && g_retryCounter < ES_MAX_NETWORK_RETRY) // found { delay(1000); g_retryCounter++; } if(g_retryCounter == ES_MAX_NETWORK_RETRY){ OIC_LOG_V(ERROR, ES_NH_TAG, "Connection to network failed after %d attempts", g_retryCounter); return ES_ERROR; } if (cb != NULL) { cb(ES_OK); } if (WiFi.status() == WL_CONNECTED) WiFi.disconnect(); //Retry counter is reset everytime the ConnectToWiFiNetwork is invoked g_retryCounter = 0; res = ConnectToNetwork(ssid, pass); if (res == 0) { return ES_NETWORKCONNECTED; } else { return ES_NETWORKNOTCONNECTED; } }
//The setup function is called once at startup of the sketch void setup() { // Add your initialization code here // Note : This will initialize Serial port on Arduino at 115200 bauds OIC_LOG_INIT(); OIC_LOG(DEBUG, TAG, ("OCServer is starting...")); // mDNSAP pinMode(LED_PIN, OUTPUT); pinMode(TEST_LED_PIN, OUTPUT); pinMode(TEST_BUT_PIN, INPUT); digitalWrite(LED_PIN, LOW); digitalWrite(TEST_LED_PIN, LOW); // Connect to Ethernet or WiFi network if (ConnectToNetwork() != 0) { Serial.print("Unable to connect to Network"); OIC_LOG(ERROR, TAG, ("Unable to connect to network")); return; } // Initialize the OC Stack in Server mode if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) { OIC_LOG(ERROR, TAG, ("OCStack init error")); return; } OCBaseResourceT *newResource = createResource("/a/button", "oic.r.button", OC_RSRVD_INTERFACE_DEFAULT, (OC_DISCOVERABLE | OC_OBSERVABLE), buttonIOHandler); newResource->name = "Marks Button"; /* OCIOPort port; port.pin = TEST_BUT_PIN; port.type = IN; Value value = malloc(sizeof(int)); int intVal = 0; *((int*)value) = intVal; addAttribute(&newResource->attribute, "power", value, INT, &port);*/ //printResourceData(newResource); OCBaseResourceT *resource = createResource("/a/light/hosting", "oic.r.light", OC_RSRVD_INTERFACE_DEFAULT, (OC_DISCOVERABLE | OC_OBSERVABLE), lightIOHandler); resource->name = "Mark's Light"; addType(resource, "oic.r.switch.binary"); addType(resource, "oic.r.light.brightness"); addType(resource, "oic.r.resourcehosting"); OCIOPort port; port.pin = TEST_LED_PIN; port.type = OUT; Value value = malloc(sizeof(bool)); bool boolVal = false; *((bool*)value) = boolVal; addAttribute(&resource->attribute, "state", value, BOOL, &port); value = malloc(sizeof(int)); int intVal = 0; *((int*)value) = intVal; addAttribute(&resource->attribute, "power", value, INT, &port); //printResourceData(resource); /* OCBaseResourceT *humidtyResource = createResource("/a/temperatureSensor", "oic.r.sensor", OC_RSRVD_INTERFACE_DEFAULT, (OC_DISCOVERABLE | OC_OBSERVABLE), NULL); */ // Start the thread to take for change in the input of the resources Scheduler.startLoop(checkInputThread); // Alive LED Scheduler.startLoop(aliveThread); /* char *heapend=sbrk(0); register char * stack_ptr asm ("sp"); struct mallinfo mi=mallinfo(); OIC_LOG_V(DEBUG, TAG, "\nDynamic ram used: %d\n",mi.uordblks); OIC_LOG_V(DEBUG, TAG, "Program static ram used %d\n",&_end - ramstart); OIC_LOG_V(DEBUG, TAG, "Stack ram used %d\n\n",ramend - stack_ptr); OIC_LOG_V(DEBUG, TAG, "My guess at free mem: %d\n",stack_ptr - heapend + mi.fordblks);*/ }
/** * Download and install from a remote location using HTTP. * @param url the url indicating the location of the widget. * @param widget receives the constructed widget on success. */ STDMETHODIMP CBondiWidgetLibrary::RemoteInstall(BSTR url, IBondiWidget** widget) { HRESULT hRes = S_OK; try { TCHAR appDataPath[MAX_PATH]; WidgetUtils::GetAppFolder(NULL,appDataPath); TCHAR canonicalURL[1024]; DWORD nSize = 1024; InternetCanonicalizeUrl(url, canonicalURL, &nSize, ICU_BROWSER_MODE); // Check for an internet connection. if (InternetAttemptConnect(0) != ERROR_SUCCESS) BONDI_RAISE_ERROR(E_BONDI_WIDGET_NO_INTERNET,_T("no internet connection found")); // Open a connection. HINTERNET hINet = InternetOpen(agentName,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,INTERNET_FLAG_NO_CACHE_WRITE); if (hINet != 0) { HANDLE hConnection = ConnectToNetwork(25); if (hConnection != NULL) { // Attempt to access the resource at the url. DWORD options = INTERNET_FLAG_NEED_FILE|INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_RESYNCHRONIZE|INTERNET_FLAG_RELOAD; HINTERNET hFile = InternetOpenUrl( hINet, canonicalURL, NULL, 0, options, 0 ); if (hFile != 0) { // Determine the file name to store the downloaded widget resource. TCHAR fName[MAX_PATH]; _tsplitpath_s(url, NULL, 0, NULL, 0, fName, _MAX_FNAME, NULL, 0); // Create the target local file. _bstr_t downloadPath = appDataPath + _bstr_t("\\") + _bstr_t(fName) + _bstr_t(".wgt"); HANDLE target = ::CreateFile(downloadPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); // Read chunks. BYTE buffer[1024]; DWORD dwRead; while (::InternetReadFile( hFile, buffer, 1024, &dwRead ) ) { if ( dwRead == 0 ) break; ::WriteFile(target,buffer,dwRead,&dwRead,NULL); } ::CloseHandle(target); InternetCloseHandle(hFile); CComObject<CBondiWidget>* newWidget; BONDI_CHECK_ERROR(CComObject<CBondiWidget>::CreateInstance(&newWidget),(IBondiWidgetLibrary*)this); newWidget->AddRef(); // Do the installation. _bstr_t locale("en"); hRes = newWidget->Install(downloadPath,locale,VARIANT_FALSE,VARIANT_FALSE); BONDI_CHECK_ERROR(hRes,(IBondiWidget*)newWidget); if (hRes == S_OK) { // Set the install URL. CComPtr<IBondiWidgetAppConfig> appConfig; BONDI_CHECK_ERROR(newWidget->get_AppSettings(&appConfig),(IBondiWidget*)newWidget); if (appConfig != NULL) BONDI_CHECK_ERROR(appConfig->PutBondiSetting(_T("bondi.installUri"),canonicalURL,VARIANT_TRUE),appConfig); newWidget->InitialiseAppSettings(); // We've finished with the temporary downloaded resource. ::DeleteFile(downloadPath); *widget = (IBondiWidget*)newWidget; } else { // Didn't install (probably because of an existing widget). *widget = NULL; } } else { DWORD err = GetLastError(); BONDI_RAISE_ERROR(E_BONDI_WIDGET_URL_OPEN_FAILED,_T("couldn't open url: ") + CString(canonicalURL)); } #ifdef UNDER_CE ConnMgrReleaseConnection(hConnection,1); CloseHandle(hConnection); #endif } InternetCloseHandle(hINet); } else { BONDI_RAISE_ERROR(E_BONDI_WIDGET_NO_INTERNET,_T("error opening internet connection")); } } catch (_com_error& err) { hRes = BONDI_SET_ERROR(err,"CBondiWidgetLibrary::RemoteInstall - COM exception"); } catch (...) { hRes = BONDI_SET_ERROR(E_FAIL,"CBondiWidgetLibrary::RemoteInstall - C++ exception"); } return hRes; }